From 1bf1084f2b10c3b47fd1a588d85d21ed0eb41d0c Mon Sep 17 00:00:00 2001 From: Lorry Tar Creator Date: Tue, 27 Jun 2017 06:07:23 +0000 Subject: webkitgtk-2.16.5 --- .../UserInterface/ActivateButtonNavigationItem.js | 103 - .../UserInterface/ActivateButtonToolbarItem.js | 59 - .../ApplicationCacheDetailsSidebarPanel.js | 152 - .../UserInterface/ApplicationCacheFrame.js | 74 - .../ApplicationCacheFrameContentView.css | 33 - .../ApplicationCacheFrameContentView.js | 250 - .../ApplicationCacheFrameTreeElement.js | 61 - .../UserInterface/ApplicationCacheIcons.css | 32 - .../UserInterface/ApplicationCacheManager.js | 198 - .../UserInterface/ApplicationCacheManifest.js | 42 - .../ApplicationCacheManifestTreeElement.js | 74 - .../UserInterface/ApplicationCacheObserver.js | 47 - .../UserInterface/BackForwardEntry.js | 122 - .../UserInterface/Base/DOMUtilities.js | 314 + .../UserInterface/Base/EventListener.js | 90 + .../UserInterface/Base/EventListenerSet.js | 91 + .../UserInterface/Base/ImageUtilities.js | 53 + .../Base/InspectorFrontendHostStub.js | 200 + .../UserInterface/Base/LinkedList.js | 112 + .../UserInterface/Base/ListMultimap.js | 117 + .../UserInterface/Base/LoadLocalizedStrings.js | 34 + .../UserInterface/Base/MIMETypeUtilities.js | 122 + Source/WebInspectorUI/UserInterface/Base/Main.js | 2693 +++ Source/WebInspectorUI/UserInterface/Base/Object.js | 229 + .../WebInspectorUI/UserInterface/Base/Platform.js | 61 + .../WebInspectorUI/UserInterface/Base/Setting.js | 118 + .../UserInterface/Base/URLUtilities.js | 265 + .../WebInspectorUI/UserInterface/Base/Utilities.js | 1509 ++ .../UserInterface/Base/WebInspector.js | 26 + .../UserInterface/Base/YieldableTask.js | 156 + .../WebInspectorUI/UserInterface/BinarySearch.js | 85 - .../UserInterface/BlankStylePropertiesSection.js | 99 - .../UserInterface/BottomUpProfileDataGridTree.js | 265 - .../UserInterface/BoxModelDetailsSectionRow.css | 133 - .../UserInterface/BoxModelDetailsSectionRow.js | 428 - Source/WebInspectorUI/UserInterface/Branch.js | 149 - .../WebInspectorUI/UserInterface/BranchManager.js | 113 - Source/WebInspectorUI/UserInterface/Breakpoint.css | 69 - Source/WebInspectorUI/UserInterface/Breakpoint.js | 566 - .../UserInterface/BreakpointAction.js | 93 - .../UserInterface/BreakpointActionView.css | 85 - .../UserInterface/BreakpointActionView.js | 202 - .../UserInterface/BreakpointIcons.css | 32 - .../UserInterface/BreakpointTreeElement.css | 47 - .../UserInterface/BreakpointTreeElement.js | 173 - .../UserInterface/ButtonNavigationItem.css | 72 - .../UserInterface/ButtonNavigationItem.js | 208 - .../UserInterface/ButtonToolbarItem.css | 90 - .../UserInterface/ButtonToolbarItem.js | 61 - .../WebInspectorUI/UserInterface/CSSCompletions.js | 272 - .../UserInterface/CSSKeywordCompletions.js | 902 - Source/WebInspectorUI/UserInterface/CSSMedia.js | 65 - Source/WebInspectorUI/UserInterface/CSSObserver.js | 87 - Source/WebInspectorUI/UserInterface/CSSProperty.js | 454 - Source/WebInspectorUI/UserInterface/CSSRule.js | 204 - .../UserInterface/CSSStyleDeclaration.js | 310 - .../UserInterface/CSSStyleDeclarationSection.css | 153 - .../UserInterface/CSSStyleDeclarationSection.js | 261 - .../CSSStyleDeclarationTextEditor.css | 161 - .../UserInterface/CSSStyleDeclarationTextEditor.js | 1006 - .../UserInterface/CSSStyleDetailsSidebarPanel.css | 71 - .../UserInterface/CSSStyleDetailsSidebarPanel.js | 240 - .../UserInterface/CSSStyleManager.js | 367 - .../WebInspectorUI/UserInterface/CSSStyleSheet.js | 155 - Source/WebInspectorUI/UserInterface/CallFrame.js | 105 - .../UserInterface/CallFrameIcons.css | 36 - .../UserInterface/CallFrameTreeElement.js | 87 - .../UserInterface/CanvasDataGridNode.js | 67 - .../WebInspectorUI/UserInterface/CanvasObserver.js | 47 - .../UserInterface/CanvasProfileObject.js | 47 - .../UserInterface/CanvasProfileType.js | 108 - .../UserInterface/CanvasProfileView.js | 100 - .../UserInterface/ClusterContentView.css | 32 - .../UserInterface/ClusterContentView.js | 257 - .../UserInterface/CodeMirrorAdditions.js | 541 - .../CodeMirrorColorEditingController.js | 161 - .../CodeMirrorCompletionController.css | 28 - .../CodeMirrorCompletionController.js | 824 - .../CodeMirrorDragToAlterNumberController.css | 28 - .../CodeMirrorDragToAlterNumberController.js | 234 - .../UserInterface/CodeMirrorFormatters.js | 403 - .../UserInterface/CodeMirrorOverrides.css | 83 - .../CodeMirrorTokenTrackingController.css | 31 - .../CodeMirrorTokenTrackingController.js | 509 - Source/WebInspectorUI/UserInterface/Color.js | 665 - .../WebInspectorUI/UserInterface/ColorPicker.css | 50 - Source/WebInspectorUI/UserInterface/ColorPicker.js | 144 - Source/WebInspectorUI/UserInterface/ColorWheel.css | 40 - Source/WebInspectorUI/UserInterface/ColorWheel.js | 282 - .../UserInterface/CompletionSuggestionsView.css | 78 - .../UserInterface/CompletionSuggestionsView.js | 228 - .../UserInterface/ComputedStyleDetailsPanel.css | 37 - .../UserInterface/ComputedStyleDetailsPanel.js | 219 - .../WebInspectorUI/UserInterface/ConsoleCommand.js | 99 - .../UserInterface/ConsoleCommandResult.js | 60 - .../WebInspectorUI/UserInterface/ConsoleGroup.js | 101 - .../WebInspectorUI/UserInterface/ConsoleMessage.js | 115 - .../UserInterface/ConsoleMessageImpl.js | 714 - .../UserInterface/ConsoleObserver.js | 65 - .../WebInspectorUI/UserInterface/ConsolePrompt.css | 37 - .../WebInspectorUI/UserInterface/ConsolePrompt.js | 294 - .../UserInterface/ContentBrowser.css | 34 - .../WebInspectorUI/UserInterface/ContentBrowser.js | 532 - Source/WebInspectorUI/UserInterface/ContentFlow.js | 108 - .../UserInterface/ContentFlowDOMTreeContentView.js | 97 - .../UserInterface/ContentFlowIcon.css | 32 - .../UserInterface/ContentFlowTreeElement.js | 44 - .../WebInspectorUI/UserInterface/ContentView.css | 36 - Source/WebInspectorUI/UserInterface/ContentView.js | 318 - .../UserInterface/ContentViewContainer.css | 39 - .../UserInterface/ContentViewContainer.js | 413 - Source/WebInspectorUI/UserInterface/ContextMenu.js | 299 - .../UserInterface/ControlToolbarItem.css | 70 - .../UserInterface/ControlToolbarItem.js | 41 - .../UserInterface/Controllers/AnalyzerManager.js | 122 + .../UserInterface/Controllers/Annotator.js | 110 + .../Controllers/ApplicationCacheManager.js | 204 + .../Controllers/BasicBlockAnnotator.js | 131 + .../UserInterface/Controllers/BranchManager.js | 110 + .../Controllers/BreakpointLogMessageLexer.js | 197 + .../Controllers/BreakpointPopoverController.js | 382 + .../UserInterface/Controllers/CSSStyleManager.js | 551 + .../CodeMirrorBezierEditingController.js | 68 + .../CodeMirrorColorEditingController.js | 64 + .../Controllers/CodeMirrorCompletionController.css | 29 + .../Controllers/CodeMirrorCompletionController.js | 875 + .../CodeMirrorDragToAdjustNumberController.css | 28 + .../CodeMirrorDragToAdjustNumberController.js | 121 + .../Controllers/CodeMirrorEditingController.js | 200 + .../CodeMirrorGradientEditingController.js | 83 + .../CodeMirrorSpringEditingController.js | 63 + .../Controllers/CodeMirrorTextKillController.js | 138 + .../CodeMirrorTokenTrackingController.css | 31 + .../CodeMirrorTokenTrackingController.js | 618 + .../UserInterface/Controllers/DOMTreeManager.js | 795 + .../UserInterface/Controllers/DashboardManager.js | 42 + .../UserInterface/Controllers/DebuggerManager.js | 1217 ++ .../Controllers/DragToAdjustController.js | 238 + .../UserInterface/Controllers/Formatter.js | 167 + .../Controllers/FormatterSourceMap.js | 97 + .../Controllers/FrameResourceManager.js | 640 + .../UserInterface/Controllers/HeapManager.js | 53 + .../UserInterface/Controllers/IssueManager.js | 101 + .../Controllers/JavaScriptLogViewController.js | 350 + .../JavaScriptRuntimeCompletionProvider.js | 307 + .../UserInterface/Controllers/LayerTreeManager.js | 154 + .../UserInterface/Controllers/LogManager.js | 129 + .../UserInterface/Controllers/MemoryManager.js | 49 + .../UserInterface/Controllers/ProbeManager.js | 177 + .../UserInterface/Controllers/ReplayManager.js | 678 + .../Controllers/ResourceQueryController.js | 203 + .../UserInterface/Controllers/RuntimeManager.js | 262 + .../UserInterface/Controllers/SourceMapManager.js | 186 + .../UserInterface/Controllers/StorageManager.js | 336 + .../UserInterface/Controllers/TargetManager.js | 75 + .../UserInterface/Controllers/TimelineManager.js | 1091 ++ .../Controllers/TypeTokenAnnotator.js | 199 + .../VisualStyleCompletionsController.js | 132 + .../UserInterface/Controllers/WorkerManager.js | 69 + Source/WebInspectorUI/UserInterface/CookieIcon.css | 28 - .../UserInterface/CookieStorageContentView.css | 33 - .../UserInterface/CookieStorageContentView.js | 262 - .../UserInterface/CookieStorageObject.js | 47 - .../UserInterface/CookieStorageTreeElement.js | 51 - .../UserInterface/DOMDetailsSidebarPanel.js | 114 - Source/WebInspectorUI/UserInterface/DOMNode.js | 690 - .../UserInterface/DOMNodeDetailsSidebarPanel.js | 281 - .../WebInspectorUI/UserInterface/DOMNodeStyles.js | 1050 -- Source/WebInspectorUI/UserInterface/DOMObserver.js | 92 - .../UserInterface/DOMSearchMatchObject.js | 150 - .../UserInterface/DOMStorageContentView.css | 34 - .../UserInterface/DOMStorageContentView.js | 230 - .../UserInterface/DOMStorageIcons.css | 32 - .../UserInterface/DOMStorageObject.js | 79 - .../UserInterface/DOMStorageObserver.js | 70 - .../UserInterface/DOMStorageTreeElement.js | 59 - Source/WebInspectorUI/UserInterface/DOMTree.js | 334 - .../UserInterface/DOMTreeContentView.css | 28 - .../UserInterface/DOMTreeContentView.js | 426 - .../UserInterface/DOMTreeDataGrid.css | 101 - .../UserInterface/DOMTreeDataGrid.js | 59 - .../UserInterface/DOMTreeDataGridNode.js | 89 - .../WebInspectorUI/UserInterface/DOMTreeElement.js | 1319 -- .../UserInterface/DOMTreeElementPathComponent.js | 132 - .../WebInspectorUI/UserInterface/DOMTreeManager.js | 833 - .../UserInterface/DOMTreeOutline.css | 148 - .../WebInspectorUI/UserInterface/DOMTreeOutline.js | 588 - .../WebInspectorUI/UserInterface/DOMTreeUpdater.js | 143 - .../WebInspectorUI/UserInterface/DOMUtilities.js | 76 - .../UserInterface/DashboardManager.js | 187 - .../WebInspectorUI/UserInterface/DashboardView.css | 243 - .../WebInspectorUI/UserInterface/DashboardView.js | 245 - Source/WebInspectorUI/UserInterface/DataGrid.css | 337 - Source/WebInspectorUI/UserInterface/DataGrid.js | 1872 -- .../UserInterface/DatabaseContentView.css | 108 - .../UserInterface/DatabaseContentView.js | 190 - .../UserInterface/DatabaseHostTreeElement.js | 51 - .../WebInspectorUI/UserInterface/DatabaseIcon.css | 28 - .../WebInspectorUI/UserInterface/DatabaseObject.js | 135 - .../UserInterface/DatabaseObserver.js | 70 - .../UserInterface/DatabaseTableContentView.css | 33 - .../UserInterface/DatabaseTableContentView.js | 102 - .../UserInterface/DatabaseTableIcon.css | 28 - .../UserInterface/DatabaseTableObject.js | 56 - .../UserInterface/DatabaseTableTreeElement.js | 41 - .../UserInterface/DatabaseTreeElement.js | 75 - .../UserInterface/Debug/Bootstrap.js | 61 + .../UserInterface/Debug/CapturingProtocolTracer.js | 89 + .../UserInterface/Debug/ProtocolTrace.js | 56 + .../Debug/UncaughtExceptionReporter.css | 114 + .../Debug/UncaughtExceptionReporter.js | 275 + .../UserInterface/DebuggerManager.js | 702 - .../UserInterface/DebuggerObserver.js | 67 - .../UserInterface/DebuggerSidebarPanel.css | 35 - .../UserInterface/DebuggerSidebarPanel.js | 558 - .../UserInterface/DetailsSection.css | 260 - .../WebInspectorUI/UserInterface/DetailsSection.js | 175 - .../UserInterface/DetailsSectionDataGridRow.js | 63 - .../UserInterface/DetailsSectionGroup.js | 63 - .../UserInterface/DetailsSectionPropertiesRow.js | 62 - .../UserInterface/DetailsSectionRow.js | 79 - .../UserInterface/DetailsSectionSimpleRow.js | 120 - .../UserInterface/DetailsSidebarPanel.css | 29 - .../UserInterface/DetailsSidebarPanel.js | 80 - .../UserInterface/DividerNavigationItem.css | 33 - .../UserInterface/DividerNavigationItem.js | 40 - Source/WebInspectorUI/UserInterface/Editing.css | 53 - .../WebInspectorUI/UserInterface/EditingSupport.js | 271 - .../WebInspectorUI/UserInterface/EventHandler.js | 79 - .../UserInterface/EventListenerSection.js | 46 - .../UserInterface/EventListenerSectionGroup.css | 30 - .../UserInterface/EventListenerSectionGroup.js | 101 - .../UserInterface/ExecutionContext.js | 73 - .../UserInterface/ExecutionContextList.js | 75 - .../UserInterface/External/.eslintrc | 30 + .../UserInterface/External/CodeMirror/LICENSE | 19 + .../UserInterface/External/CodeMirror/clojure.js | 108 +- .../External/CodeMirror/closebrackets.js | 258 +- .../External/CodeMirror/codemirror.css | 188 +- .../External/CodeMirror/codemirror.js | 14601 +++++++++------ .../External/CodeMirror/coffeescript.js | 81 +- .../UserInterface/External/CodeMirror/comment.js | 89 +- .../UserInterface/External/CodeMirror/css.js | 920 +- .../UserInterface/External/CodeMirror/htmlmixed.js | 232 +- .../External/CodeMirror/javascript.js | 384 +- .../UserInterface/External/CodeMirror/less.js | 346 - .../External/CodeMirror/livescript.js | 57 +- .../External/CodeMirror/mark-selection.js | 118 + .../External/CodeMirror/matchbrackets.js | 133 +- .../UserInterface/External/CodeMirror/overlay.js | 49 +- .../External/CodeMirror/placeholder.js | 20 +- .../UserInterface/External/CodeMirror/runmode.js | 20 +- .../UserInterface/External/CodeMirror/sass.js | 428 +- .../External/CodeMirror/searchcursor.js | 102 +- .../UserInterface/External/CodeMirror/sql.js | 90 +- .../UserInterface/External/CodeMirror/sublime.js | 588 + .../UserInterface/External/CodeMirror/xml.js | 391 +- .../UserInterface/External/ESLint/LICENSE | 19 + .../UserInterface/External/ESLint/eslint.js | 18223 +++++++++++++++++++ .../UserInterface/External/Esprima/LICENSE | 21 + .../UserInterface/External/Esprima/esprima.js | 6768 +++++++ Source/WebInspectorUI/UserInterface/FilterBar.css | 75 - Source/WebInspectorUI/UserInterface/FilterBar.js | 103 - Source/WebInspectorUI/UserInterface/FindBanner.css | 196 - Source/WebInspectorUI/UserInterface/FindBanner.js | 334 - .../UserInterface/FlexibleSpaceNavigationItem.css | 29 - .../UserInterface/FlexibleSpaceNavigationItem.js | 40 - Source/WebInspectorUI/UserInterface/FolderIcon.css | 28 - .../UserInterface/FolderTreeElement.js | 41 - .../UserInterface/FontResourceContentView.css | 100 - .../UserInterface/FontResourceContentView.js | 151 - Source/WebInspectorUI/UserInterface/Formatter.js | 164 - .../UserInterface/FormatterContentBuilder.js | 229 - .../UserInterface/FormatterSourceMap.js | 87 - Source/WebInspectorUI/UserInterface/Frame.js | 501 - .../UserInterface/FrameContentView.js | 195 - .../UserInterface/FrameDOMTreeContentView.js | 87 - .../UserInterface/FrameResourceManager.js | 586 - .../UserInterface/FrameTreeElement.js | 631 - .../UserInterface/GeneralTreeElement.js | 395 - .../GeneralTreeElementPathComponent.js | 75 - .../UserInterface/GenericResourceContentView.js | 37 - Source/WebInspectorUI/UserInterface/Geometry.js | 255 - .../UserInterface/GoToLineDialog.css | 85 - .../WebInspectorUI/UserInterface/GoToLineDialog.js | 159 - .../UserInterface/HierarchicalPathComponent.css | 132 - .../UserInterface/HierarchicalPathComponent.js | 339 - .../HierarchicalPathNavigationItem.js | 237 - Source/WebInspectorUI/UserInterface/HoverMenu.css | 68 - Source/WebInspectorUI/UserInterface/HoverMenu.js | 107 - .../UserInterface/ImageResourceContentView.css | 49 - .../UserInterface/ImageResourceContentView.js | 56 - .../WebInspectorUI/UserInterface/ImageUtilities.js | 730 - .../UserInterface/Images/gtk/AUTHORS | 47 + .../UserInterface/Images/gtk/Assertion.svg | 27 + .../UserInterface/Images/gtk/BackArrow.svg | 156 - .../UserInterface/Images/gtk/BackForwardArrows.svg | 34 + .../UserInterface/Images/gtk/BottomUpTree.svg | 73 - .../Images/gtk/BreakpointActionAdd.svg | 52 - .../Images/gtk/BreakpointActionRemove.svg | 55 - .../UserInterface/Images/gtk/BreakpointButton.svg | 164 +- .../Images/gtk/BreakpointInactiveButton.svg | 209 +- .../UserInterface/Images/gtk/Breakpoints.svg | 55 +- .../UserInterface/Images/gtk/COPYING | 18 + .../UserInterface/Images/gtk/COPYING_CCBYSA3 | 4 + .../UserInterface/Images/gtk/COPYING_LGPL2 | 481 + .../UserInterface/Images/gtk/Checkers.svg | 6 + .../UserInterface/Images/gtk/Circle.svg | 5 + .../UserInterface/Images/gtk/ClearBoth.svg | 39 + .../UserInterface/Images/gtk/ClearLeft.svg | 22 + .../UserInterface/Images/gtk/ClearRight.svg | 22 + .../UserInterface/Images/gtk/Close.svg | 56 +- .../UserInterface/Images/gtk/CloseLarge.svg | 5 + .../UserInterface/Images/gtk/CloseTimeline.png | Bin 505 -> 0 bytes .../UserInterface/Images/gtk/CloseTimeline@2x.png | Bin 1648 -> 0 bytes .../UserInterface/Images/gtk/CloseWhite.svg | 56 +- .../UserInterface/Images/gtk/Colors.png | Bin 917 -> 0 bytes .../UserInterface/Images/gtk/Colors@2x.png | Bin 1958 -> 0 bytes .../UserInterface/Images/gtk/ColorsLarge.png | Bin 1958 -> 0 bytes .../UserInterface/Images/gtk/ColorsLarge@2x.png | Bin 6924 -> 0 bytes .../UserInterface/Images/gtk/Console.svg | 7 + .../UserInterface/Images/gtk/ContentFlow.svg | 76 +- .../UserInterface/Images/gtk/Crosshair.svg | 70 +- .../UserInterface/Images/gtk/CubicBezier.svg | 9 + .../UserInterface/Images/gtk/DOMCharacterData.svg | 370 +- .../UserInterface/Images/gtk/DOMComment.svg | 373 +- .../UserInterface/Images/gtk/DOMDocument.svg | 432 +- .../UserInterface/Images/gtk/DOMDocumentType.svg | 432 +- .../UserInterface/Images/gtk/DOMElement.svg | 406 +- .../UserInterface/Images/gtk/DOMNode.svg | 414 +- .../UserInterface/Images/gtk/DOMTextNode.svg | 388 +- .../UserInterface/Images/gtk/DOMTree.svg | 359 - .../UserInterface/Images/gtk/Debug.svg | 5 + .../UserInterface/Images/gtk/Debugger.svg | 5 + .../Images/gtk/DisclosureTriangleSmallClosed.svg | 53 - .../Images/gtk/DisclosureTriangleSmallOpen.svg | 57 - .../Images/gtk/DisclosureTriangleTinyClosed.svg | 57 - .../Images/gtk/DisclosureTriangleTinyOpen.svg | 57 - .../Images/gtk/DisclosureTriangles.svg | 42 + .../UserInterface/Images/gtk/DockBottom.svg | 57 +- .../UserInterface/Images/gtk/DockRight.svg | 40 +- .../UserInterface/Images/gtk/DownloadArrow.svg | 132 +- .../UserInterface/Images/gtk/Elements.svg | 5 + .../UserInterface/Images/gtk/Error.svg | 131 +- .../UserInterface/Images/gtk/Errors.svg | 130 +- .../UserInterface/Images/gtk/ErrorsEnabled.svg | 78 +- .../UserInterface/Images/gtk/EventListener.svg | 414 +- .../UserInterface/Images/gtk/Exception.svg | 374 +- .../UserInterface/Images/gtk/Eye.svg | 6 + .../UserInterface/Images/gtk/FilterFieldGlyph.svg | 56 +- .../UserInterface/Images/gtk/FloatLeft.svg | 13 + .../UserInterface/Images/gtk/FloatRight.svg | 13 + .../UserInterface/Images/gtk/FontStyleItalic.svg | 5 + .../UserInterface/Images/gtk/FontStyleNormal.svg | 5 + .../UserInterface/Images/gtk/ForwardArrow.svg | 156 - .../UserInterface/Images/gtk/Function.svg | 458 +- .../UserInterface/Images/gtk/Gear.svg | 5 + .../UserInterface/Images/gtk/GoToArrow.svg | 240 +- .../UserInterface/Images/gtk/GradientStop.png | Bin 0 -> 1051 bytes .../UserInterface/Images/gtk/GradientStop@2x.png | Bin 0 -> 2375 bytes .../Images/gtk/GradientStopSelected.png | Bin 0 -> 1007 bytes .../Images/gtk/GradientStopSelected@2x.png | Bin 0 -> 2322 bytes .../Images/gtk/HeapAllocationsInstrument.svg | 16 + .../Images/gtk/HeapSnapshotObjectGraph.svg | 27 + .../gtk/HierarchicalNavigationItemChevron.svg | 159 +- .../Images/gtk/IndeterminateProgressSpinner1.svg | 293 +- .../Images/gtk/IndeterminateProgressSpinner10.svg | 297 +- .../Images/gtk/IndeterminateProgressSpinner11.svg | 297 +- .../Images/gtk/IndeterminateProgressSpinner12.svg | 297 +- .../Images/gtk/IndeterminateProgressSpinner2.svg | 317 +- .../Images/gtk/IndeterminateProgressSpinner3.svg | 297 +- .../Images/gtk/IndeterminateProgressSpinner4.svg | 297 +- .../Images/gtk/IndeterminateProgressSpinner5.svg | 297 +- .../Images/gtk/IndeterminateProgressSpinner6.svg | 297 +- .../Images/gtk/IndeterminateProgressSpinner7.svg | 297 +- .../Images/gtk/IndeterminateProgressSpinner8.svg | 297 +- .../Images/gtk/IndeterminateProgressSpinner9.svg | 297 +- .../UserInterface/Images/gtk/Info.svg | 8 + .../UserInterface/Images/gtk/Issues.svg | 55 +- .../UserInterface/Images/gtk/IssuesEnabled.svg | 55 +- .../UserInterface/Images/gtk/LayerBorders.svg | 70 +- .../UserInterface/Images/gtk/LayoutInstrument.svg | 10 + .../UserInterface/Images/gtk/LessColumns.svg | 53 - .../UserInterface/Images/gtk/Locked.svg | 56 +- .../UserInterface/Images/gtk/Log.png | Bin 714 -> 0 bytes .../UserInterface/Images/gtk/Log.svg | 5 + .../UserInterface/Images/gtk/Log@2x.png | Bin 1944 -> 0 bytes .../UserInterface/Images/gtk/Logs.svg | 55 +- .../UserInterface/Images/gtk/Memory.svg | 204 - .../UserInterface/Images/gtk/MemoryInstrument.svg | 21 + .../UserInterface/Images/gtk/Minus.svg | 5 + .../UserInterface/Images/gtk/MoreColumns.svg | 53 - .../UserInterface/Images/gtk/Native.svg | 414 +- .../Images/gtk/NavigationItemAngleBrackets.svg | 62 - .../Images/gtk/NavigationItemBrushAndRuler.svg | 229 - .../UserInterface/Images/gtk/NavigationItemBug.svg | 52 - .../Images/gtk/NavigationItemClear.svg | 5 + .../Images/gtk/NavigationItemCodeCoverage.svg | 6 + .../Images/gtk/NavigationItemCurleyBraces.svg | 45 +- .../Images/gtk/NavigationItemFile.svg | 52 - .../Images/gtk/NavigationItemLayers.svg | 57 - .../UserInterface/Images/gtk/NavigationItemLog.svg | 63 - .../Images/gtk/NavigationItemMagnifyingGlass.svg | 57 - .../Images/gtk/NavigationItemStopwatch.svg | 56 - .../Images/gtk/NavigationItemStorage.svg | 52 - .../Images/gtk/NavigationItemTrash.svg | 55 +- .../Images/gtk/NavigationItemTypes.svg | 6 + .../Images/gtk/NavigationItemVariable.svg | 57 - .../UserInterface/Images/gtk/Network.png | Bin 1120 -> 0 bytes .../UserInterface/Images/gtk/Network.svg | 6 + .../UserInterface/Images/gtk/Network@2x.png | Bin 2740 -> 0 bytes .../UserInterface/Images/gtk/NetworkInstrument.svg | 6 + .../UserInterface/Images/gtk/NetworkLarge.png | Bin 2740 -> 0 bytes .../UserInterface/Images/gtk/NetworkLarge@2x.png | Bin 8914 -> 0 bytes .../UserInterface/Images/gtk/NewTab.svg | 5 + .../UserInterface/Images/gtk/NewTabPlus.svg | 5 + .../UserInterface/Images/gtk/PaintFlashing.svg | 5 + .../UserInterface/Images/gtk/Pause.svg | 60 +- .../UserInterface/Images/gtk/PausedBreakpoint.svg | 27 + .../UserInterface/Images/gtk/Pencil.svg | 12 + .../UserInterface/Images/gtk/Percent.svg | 55 - .../UserInterface/Images/gtk/Plus.svg | 59 - .../UserInterface/Images/gtk/Plus13.svg | 5 + .../UserInterface/Images/gtk/Plus15.svg | 5 + .../UserInterface/Images/gtk/Printer.svg | 7 + .../UserInterface/Images/gtk/Profile.png | Bin 1102 -> 0 bytes .../UserInterface/Images/gtk/Profile@2x.png | Bin 2982 -> 0 bytes .../UserInterface/Images/gtk/Program.svg | 27 + .../UserInterface/Images/gtk/PseudoElement.svg | 470 +- .../UserInterface/Images/gtk/Record.svg | 5 + .../UserInterface/Images/gtk/Recording.png | Bin 1293 -> 0 bytes .../UserInterface/Images/gtk/Recording@2x.png | Bin 3250 -> 0 bytes .../UserInterface/Images/gtk/RecordingHovered.png | Bin 1011 -> 0 bytes .../Images/gtk/RecordingHovered@2x.png | Bin 2471 -> 0 bytes .../UserInterface/Images/gtk/RecordingStopped.png | Bin 1016 -> 0 bytes .../Images/gtk/RecordingStopped@2x.png | Bin 2262 -> 0 bytes .../UserInterface/Images/gtk/Reflection.svg | 447 +- .../UserInterface/Images/gtk/Reload.svg | 52 - .../UserInterface/Images/gtk/ReloadFull.svg | 5 + .../UserInterface/Images/gtk/ReloadToolbar.svg | 5 + .../Images/gtk/RenderingFramesInstrument.svg | 7 + .../UserInterface/Images/gtk/ReplayPauseButton.svg | 6 + .../UserInterface/Images/gtk/ReplayPlayButton.svg | 5 + .../Images/gtk/ReplayRecordingButton.svg | 5 + .../UserInterface/Images/gtk/Request.svg | 659 +- .../UserInterface/Images/gtk/Resources.svg | 55 +- .../UserInterface/Images/gtk/Response.svg | 460 +- .../UserInterface/Images/gtk/ResultLine.svg | 617 +- .../UserInterface/Images/gtk/Resume.svg | 60 +- .../UserInterface/Images/gtk/Script.png | Bin 913 -> 0 bytes .../UserInterface/Images/gtk/Script@2x.png | Bin 1865 -> 0 bytes .../UserInterface/Images/gtk/ScriptLarge.png | Bin 1865 -> 0 bytes .../UserInterface/Images/gtk/ScriptLarge@2x.png | Bin 5432 -> 0 bytes .../UserInterface/Images/gtk/ScriptsInstrument.svg | 9 + .../UserInterface/Images/gtk/SearchResults.svg | 6 + .../UserInterface/Images/gtk/ShadowDOM.svg | 85 +- .../Images/gtk/SortIndicatorArrows.svg | 41 + .../Images/gtk/SortIndicatorDownArrow.svg | 216 - .../Images/gtk/SortIndicatorUpArrow.svg | 216 - .../UserInterface/Images/gtk/SourceCode.svg | 636 - .../UserInterface/Images/gtk/SplitToggleDown.svg | 56 - .../UserInterface/Images/gtk/SplitToggleUp.svg | 60 +- .../UserInterface/Images/gtk/StepInto.svg | 66 +- .../UserInterface/Images/gtk/StepOut.svg | 66 +- .../UserInterface/Images/gtk/StepOver.svg | 63 +- .../UserInterface/Images/gtk/Stop.svg | 5 + .../UserInterface/Images/gtk/Stopwatch.png | Bin 943 -> 0 bytes .../UserInterface/Images/gtk/Stopwatch.svg | 19 + .../UserInterface/Images/gtk/Stopwatch@2x.png | Bin 2770 -> 0 bytes .../UserInterface/Images/gtk/Storage.svg | 7 + .../UserInterface/Images/gtk/StyleRule.svg | 123 + .../UserInterface/Images/gtk/StyleRuleAuthor.svg | 404 - .../Images/gtk/StyleRuleInherited.svg | 641 - .../Images/gtk/StyleRuleInheritedElement.svg | 657 +- .../Images/gtk/StyleRuleInspector.svg | 481 - .../Images/gtk/StyleRulePseudoElement.svg | 103 + .../UserInterface/Images/gtk/StyleRuleUser.svg | 657 - .../Images/gtk/StyleRuleUserAgent.svg | 517 - .../Images/gtk/TailDeletedFunction.svg | 27 + .../UserInterface/Images/gtk/TextAlignCenter.svg | 7 + .../UserInterface/Images/gtk/TextAlignJustify.svg | 7 + .../UserInterface/Images/gtk/TextAlignLeft.svg | 7 + .../UserInterface/Images/gtk/TextAlignRight.svg | 7 + .../Images/gtk/TextDecorationLineThrough.svg | 6 + .../Images/gtk/TextDecorationOverline.svg | 6 + .../Images/gtk/TextDecorationUnderline.svg | 6 + .../Images/gtk/TextTransformCapitalize.svg | 6 + .../Images/gtk/TextTransformLowercase.svg | 6 + .../Images/gtk/TextTransformUppercase.svg | 6 + .../UserInterface/Images/gtk/Thread.svg | 22 + .../UserInterface/Images/gtk/Time.svg | 60 +- .../UserInterface/Images/gtk/Timeline.svg | 6 + .../UserInterface/Images/gtk/TimelineRecordAPI.svg | 27 + .../Images/gtk/TimelineRecordAnimation.svg | 497 +- .../Images/gtk/TimelineRecordComposite.svg | 27 + .../Images/gtk/TimelineRecordConsoleProfile.svg | 27 + .../Images/gtk/TimelineRecordEvent.svg | 425 +- .../Images/gtk/TimelineRecordLayout.svg | 577 +- .../Images/gtk/TimelineRecordPaint.svg | 470 +- .../Images/gtk/TimelineRecordProbeSampled.svg | 27 + .../Images/gtk/TimelineRecordRenderingFrame.svg | 27 + .../Images/gtk/TimelineRecordScriptEvaluated.svg | 455 +- .../Images/gtk/TimelineRecordStyle.svg | 620 +- .../Images/gtk/TimelineRecordTimer.svg | 472 +- .../UserInterface/Images/gtk/ToggleLeftSidebar.svg | 5 + .../Images/gtk/ToggleRightSidebar.svg | 5 + .../UserInterface/Images/gtk/TypeBoolean.svg | 27 + .../UserInterface/Images/gtk/TypeNull.svg | 27 + .../UserInterface/Images/gtk/TypeNumber.svg | 27 + .../UserInterface/Images/gtk/TypeObject.svg | 27 + .../UserInterface/Images/gtk/TypeRegex.svg | 27 + .../UserInterface/Images/gtk/TypeString.svg | 27 + .../UserInterface/Images/gtk/TypeSymbol.svg | 27 + .../UserInterface/Images/gtk/TypeUndefined.svg | 27 + .../UserInterface/Images/gtk/Undock.svg | 56 +- .../UserInterface/Images/gtk/UpDownArrows.svg | 375 +- .../UserInterface/Images/gtk/UserInputPrompt.svg | 56 +- .../Images/gtk/UserInputPromptPrevious.svg | 56 +- .../UserInterface/Images/gtk/UserInputResult.svg | 62 +- .../UserInterface/Images/gtk/VisualStyleNone.svg | 7 + .../Images/gtk/VisualStylePropertyLinked.svg | 7 + .../Images/gtk/VisualStylePropertyUnlinked.svg | 8 + .../UserInterface/Images/gtk/Warning.svg | 57 +- .../UserInterface/Images/gtk/Weight.svg | 63 +- .../UserInterface/IndeterminateProgressSpinner.css | 93 - .../UserInterface/IndeterminateProgressSpinner.js | 47 - .../UserInterface/InspectorBackend.js | 294 - .../UserInterface/InspectorFrontendAPI.js | 168 - .../UserInterface/InspectorFrontendHostStub.js | 174 - .../UserInterface/InspectorJSBackendCommands.js | 64 - .../UserInterface/InspectorObserver.js | 66 - .../UserInterface/InspectorWebBackendCommands.js | 324 - .../WebInspectorUI/UserInterface/IssueManager.js | 99 - .../WebInspectorUI/UserInterface/IssueMessage.js | 242 - .../UserInterface/JavaScriptLogViewController.js | 292 - .../UserInterface/JavaScriptProfileObject.js | 35 - .../UserInterface/JavaScriptProfileType.js | 95 - .../UserInterface/JavaScriptProfileView.css | 76 - .../UserInterface/JavaScriptProfileView.js | 468 - .../JavaScriptRuntimeCompletionProvider.js | 244 - .../UserInterface/KeyboardShortcut.js | 254 - .../UserInterface/LayerTreeDataGrid.js | 120 - .../UserInterface/LayerTreeDataGridNode.js | 168 - .../UserInterface/LayerTreeManager.js | 160 - .../UserInterface/LayerTreeObserver.js | 43 - .../UserInterface/LayerTreeSidebarPanel.css | 230 - .../UserInterface/LayerTreeSidebarPanel.js | 436 - .../UserInterface/LayoutTimelineDataGrid.js | 97 - .../UserInterface/LayoutTimelineDataGridNode.js | 85 - .../UserInterface/LayoutTimelineOverviewGraph.css | 33 - .../UserInterface/LayoutTimelineOverviewGraph.js | 94 - .../UserInterface/LayoutTimelineRecord.js | 125 - .../UserInterface/LayoutTimelineView.css | 40 - .../UserInterface/LayoutTimelineView.js | 194 - .../UserInterface/LoadInspectorBackendCommands.js | 43 - .../UserInterface/LoadLocalizedStrings.js | 34 - .../UserInterface/LogContentView.css | 435 - .../WebInspectorUI/UserInterface/LogContentView.js | 947 - Source/WebInspectorUI/UserInterface/LogIcon.css | 28 - Source/WebInspectorUI/UserInterface/LogManager.js | 104 - Source/WebInspectorUI/UserInterface/LogObject.js | 44 - .../WebInspectorUI/UserInterface/LogTreeElement.js | 50 - .../UserInterface/MIMETypeUtilities.js | 80 - Source/WebInspectorUI/UserInterface/Main.css | 257 - Source/WebInspectorUI/UserInterface/Main.html | 1112 +- Source/WebInspectorUI/UserInterface/Main.js | 1787 -- .../UserInterface/MessageDispatcher.js | 49 - .../UserInterface/MetricsStyleDetailsPanel.js | 51 - .../UserInterface/Models/AnalyzerMessage.js | 46 + .../UserInterface/Models/ApplicationCacheFrame.js | 56 + .../Models/ApplicationCacheManifest.js | 38 + .../UserInterface/Models/BackForwardEntry.js | 157 + .../WebInspectorUI/UserInterface/Models/Branch.js | 146 + .../UserInterface/Models/Breakpoint.js | 364 + .../UserInterface/Models/BreakpointAction.js | 85 + .../UserInterface/Models/CSSCompletions.js | 298 + .../UserInterface/Models/CSSKeywordCompletions.js | 1035 ++ .../UserInterface/Models/CSSMedia.js | 51 + .../UserInterface/Models/CSSProperty.js | 259 + .../WebInspectorUI/UserInterface/Models/CSSRule.js | 257 + .../UserInterface/Models/CSSSelector.js | 64 + .../UserInterface/Models/CSSStyleDeclaration.js | 362 + .../UserInterface/Models/CSSStyleSheet.js | 226 + .../UserInterface/Models/CallFrame.js | 260 + .../UserInterface/Models/CallingContextTree.js | 176 + .../UserInterface/Models/CallingContextTreeNode.js | 244 + .../UserInterface/Models/Collection.js | 119 + .../UserInterface/Models/CollectionEntry.js | 56 + .../UserInterface/Models/CollectionEntryPreview.js | 56 + .../WebInspectorUI/UserInterface/Models/Color.js | 762 + .../Models/ConsoleCommandResultMessage.js | 67 + .../UserInterface/Models/ConsoleMessage.js | 138 + .../UserInterface/Models/ContentFlow.js | 105 + .../UserInterface/Models/CookieStorageObject.js | 68 + .../WebInspectorUI/UserInterface/Models/DOMNode.js | 833 + .../UserInterface/Models/DOMNodeStyles.js | 985 + .../UserInterface/Models/DOMSearchMatchObject.js | 172 + .../UserInterface/Models/DOMStorageObject.js | 119 + .../WebInspectorUI/UserInterface/Models/DOMTree.js | 309 + .../UserInterface/Models/DatabaseObject.js | 95 + .../UserInterface/Models/DatabaseTableObject.js | 50 + .../UserInterface/Models/DebuggerDashboard.js | 28 + .../UserInterface/Models/DebuggerData.js | 155 + .../UserInterface/Models/DefaultDashboard.js | 269 + .../UserInterface/Models/ExecutionContext.js | 50 + .../UserInterface/Models/ExecutionContextList.js | 72 + .../UserInterface/Models/FPSInstrument.js | 49 + .../WebInspectorUI/UserInterface/Models/Frame.js | 509 + .../UserInterface/Models/GarbageCollection.js | 65 + .../UserInterface/Models/Geometry.js | 571 + .../UserInterface/Models/Gradient.js | 392 + .../Models/HeapAllocationsInstrument.js | 86 + .../Models/HeapAllocationsTimelineRecord.js | 43 + .../UserInterface/Models/HeapSnapshotRootPath.js | 178 + .../UserInterface/Models/IndexedDatabase.js | 59 + .../Models/IndexedDatabaseObjectStore.js | 66 + .../Models/IndexedDatabaseObjectStoreIndex.js | 63 + .../UserInterface/Models/Instrument.js | 104 + .../UserInterface/Models/IssueMessage.js | 235 + .../UserInterface/Models/KeyboardShortcut.js | 269 + .../UserInterface/Models/LayoutInstrument.js | 34 + .../UserInterface/Models/LayoutTimelineRecord.js | 110 + .../UserInterface/Models/LazySourceCodeLocation.js | 112 + .../UserInterface/Models/LineWidget.js | 61 + .../UserInterface/Models/LogObject.js | 41 + .../UserInterface/Models/MemoryCategory.js | 46 + .../UserInterface/Models/MemoryInstrument.js | 61 + .../UserInterface/Models/MemoryPressureEvent.js | 66 + .../UserInterface/Models/MemoryTimeline.js | 53 + .../UserInterface/Models/MemoryTimelineRecord.js | 87 + .../Models/NativeFunctionParameters.js | 2232 +++ .../UserInterface/Models/NetworkInstrument.js | 44 + .../UserInterface/Models/NetworkTimeline.js | 56 + .../UserInterface/Models/ObjectPreview.js | 86 + .../WebInspectorUI/UserInterface/Models/Probe.js | 108 + .../UserInterface/Models/ProbeSet.js | 148 + .../UserInterface/Models/ProbeSetDataFrame.js | 101 + .../UserInterface/Models/ProbeSetDataTable.js | 132 + .../WebInspectorUI/UserInterface/Models/Profile.js | 52 + .../UserInterface/Models/ProfileNode.js | 278 + .../UserInterface/Models/ProfileNodeCall.js | 66 + .../UserInterface/Models/PropertyDescriptor.js | 119 + .../UserInterface/Models/PropertyPath.js | 268 + .../UserInterface/Models/PropertyPreview.js | 64 + .../Models/RenderingFrameTimelineRecord.js | 148 + .../UserInterface/Models/ReplayDashboard.js | 28 + .../UserInterface/Models/ReplaySession.js | 90 + .../UserInterface/Models/ReplaySessionSegment.js | 67 + .../UserInterface/Models/Resource.js | 804 + .../UserInterface/Models/ResourceCollection.js | 199 + .../UserInterface/Models/ResourceQueryMatch.js | 48 + .../UserInterface/Models/ResourceQueryResult.js | 149 + .../UserInterface/Models/ResourceTimelineRecord.js | 74 + .../UserInterface/Models/ResourceTimingData.js | 107 + .../UserInterface/Models/Revision.js | 47 + .../UserInterface/Models/ScopeChainNode.js | 79 + .../WebInspectorUI/UserInterface/Models/Script.js | 303 + .../UserInterface/Models/ScriptInstrument.js | 61 + .../UserInterface/Models/ScriptSyntaxTree.js | 1146 ++ .../UserInterface/Models/ScriptTimelineRecord.js | 418 + .../UserInterface/Models/SourceCode.js | 226 + .../UserInterface/Models/SourceCodeLocation.js | 464 + .../UserInterface/Models/SourceCodePosition.js | 40 + .../UserInterface/Models/SourceCodeRevision.js | 76 + .../Models/SourceCodeSearchMatchObject.js | 66 + .../UserInterface/Models/SourceCodeTextRange.js | 123 + .../UserInterface/Models/SourceCodeTimeline.js | 65 + .../UserInterface/Models/SourceMap.js | 286 + .../UserInterface/Models/SourceMapResource.js | 178 + .../UserInterface/Models/StackTrace.js | 175 + .../UserInterface/Models/StructureDescription.js | 62 + .../UserInterface/Models/TextMarker.js | 89 + .../UserInterface/Models/TextRange.js | 113 + .../UserInterface/Models/Timeline.js | 136 + .../UserInterface/Models/TimelineMarker.js | 80 + .../UserInterface/Models/TimelineRange.js | 41 + .../UserInterface/Models/TimelineRecord.js | 169 + .../UserInterface/Models/TimelineRecording.js | 375 + .../UserInterface/Models/TypeDescription.js | 66 + .../WebInspectorUI/UserInterface/Models/TypeSet.js | 132 + .../UserInterface/Models/WrappedPromise.js | 71 + .../WebInspectorUI/UserInterface/NavigationBar.css | 49 - .../WebInspectorUI/UserInterface/NavigationBar.js | 451 - .../WebInspectorUI/UserInterface/NavigationItem.js | 103 - .../UserInterface/NavigationSidebarPanel.css | 356 - .../UserInterface/NavigationSidebarPanel.js | 692 - .../UserInterface/NetworkObserver.js | 92 - .../UserInterface/NetworkTimeline.js | 63 - .../UserInterface/NetworkTimelineOverviewGraph.css | 45 - .../UserInterface/NetworkTimelineOverviewGraph.js | 163 - .../UserInterface/NetworkTimelineView.css | 37 - .../UserInterface/NetworkTimelineView.js | 211 - Source/WebInspectorUI/UserInterface/Object.js | 236 - .../UserInterface/ObjectPropertiesSection.js | 347 - .../UserInterface/OverviewTimelineView.css | 95 - .../UserInterface/OverviewTimelineView.js | 352 - .../WebInspectorUI/UserInterface/PageObserver.js | 92 - .../UserInterface/PathComponentIcons.css | 68 - Source/WebInspectorUI/UserInterface/Popover.css | 91 - Source/WebInspectorUI/UserInterface/Popover.js | 482 - .../UserInterface/ProfileDataGridTree.js | 400 - .../WebInspectorUI/UserInterface/ProfileManager.js | 226 - .../WebInspectorUI/UserInterface/ProfileObject.js | 93 - Source/WebInspectorUI/UserInterface/ProfileType.js | 87 - .../WebInspectorUI/UserInterface/ProfileView.css | 59 - Source/WebInspectorUI/UserInterface/ProfileView.js | 109 - .../UserInterface/ProfilerObserver.js | 68 - .../UserInterface/PropertiesSection.js | 39 - .../Protocol/ApplicationCacheObserver.js | 39 + .../UserInterface/Protocol/CSSObserver.js | 80 + .../UserInterface/Protocol/Connection.js | 315 + .../UserInterface/Protocol/ConsoleObserver.js | 59 + .../UserInterface/Protocol/DOMObserver.js | 99 + .../UserInterface/Protocol/DOMStorageObserver.js | 50 + .../UserInterface/Protocol/DatabaseObserver.js | 34 + .../UserInterface/Protocol/DebuggerObserver.js | 85 + .../UserInterface/Protocol/HeapObserver.js | 52 + .../UserInterface/Protocol/InspectorBackend.js | 432 + .../UserInterface/Protocol/InspectorFrontendAPI.js | 163 + .../UserInterface/Protocol/InspectorObserver.js | 65 + .../UserInterface/Protocol/LayerTreeObserver.js | 35 + .../Legacy/10.0/InspectorBackendCommands.js | 397 + .../Legacy/10.3/InspectorBackendCommands.js | 412 + .../Legacy/7.0/InspectorBackendCommands.js | 317 + .../Legacy/8.0/InspectorBackendCommands.js | 342 + .../Legacy/9.0/InspectorBackendCommands.js | 339 + .../Legacy/9.3/InspectorBackendCommands.js | 366 + .../Protocol/LoadInspectorBackendCommands.js | 29 + .../Protocol/LoggingProtocolTracer.js | 120 + .../UserInterface/Protocol/MainTarget.js | 56 + .../UserInterface/Protocol/MemoryObserver.js | 49 + .../UserInterface/Protocol/MessageDispatcher.js | 78 + .../UserInterface/Protocol/NetworkObserver.js | 99 + .../UserInterface/Protocol/PageObserver.js | 84 + .../UserInterface/Protocol/ProtocolTracer.js | 74 + .../UserInterface/Protocol/RemoteObject.js | 679 + .../UserInterface/Protocol/ReplayObserver.js | 120 + .../UserInterface/Protocol/RuntimeObserver.js | 34 + .../Protocol/ScriptProfilerObserver.js | 54 + .../UserInterface/Protocol/Target.js | 95 + .../UserInterface/Protocol/TimelineObserver.js | 59 + .../UserInterface/Protocol/WorkerObserver.js | 44 + .../UserInterface/Protocol/WorkerTarget.js | 59 + .../UserInterface/Proxies/FormatterWorkerProxy.js | 91 + .../UserInterface/Proxies/HeapSnapshotDiffProxy.js | 107 + .../UserInterface/Proxies/HeapSnapshotEdgeProxy.js | 67 + .../UserInterface/Proxies/HeapSnapshotNodeProxy.js | 99 + .../UserInterface/Proxies/HeapSnapshotProxy.js | 135 + .../Proxies/HeapSnapshotWorkerProxy.js | 140 + .../WebInspectorUI/UserInterface/QuickConsole.css | 82 - .../WebInspectorUI/UserInterface/QuickConsole.js | 352 - .../UserInterface/QuickConsoleNavigationBar.js | 46 - .../UserInterface/RadioButtonNavigationItem.css | 42 - .../UserInterface/RadioButtonNavigationItem.js | 111 - .../WebInspectorUI/UserInterface/RemoteObject.js | 492 - Source/WebInspectorUI/UserInterface/Resource.js | 707 - .../UserInterface/ResourceClusterContentView.js | 272 - .../UserInterface/ResourceCollection.js | 164 - .../UserInterface/ResourceContentView.js | 125 - .../UserInterface/ResourceDetailsSidebarPanel.js | 484 - .../WebInspectorUI/UserInterface/ResourceIcons.css | 64 - .../UserInterface/ResourceSearchMatchObject.js | 69 - .../UserInterface/ResourceSidebarPanel.css | 52 - .../UserInterface/ResourceSidebarPanel.js | 813 - .../UserInterface/ResourceTimelineDataGridNode.js | 192 - .../ResourceTimelineDataGridNodePathComponent.js | 60 - .../UserInterface/ResourceTimelineRecord.js | 77 - .../UserInterface/ResourceTreeElement.css | 32 - .../UserInterface/ResourceTreeElement.js | 198 - Source/WebInspectorUI/UserInterface/Revision.js | 55 - .../UserInterface/RulesStyleDetailsPanel.css | 77 - .../UserInterface/RulesStyleDetailsPanel.js | 273 - .../WebInspectorUI/UserInterface/RuntimeManager.js | 89 - .../UserInterface/RuntimeObserver.js | 42 - Source/WebInspectorUI/UserInterface/ScopeBar.css | 66 - Source/WebInspectorUI/UserInterface/ScopeBar.js | 134 - .../WebInspectorUI/UserInterface/ScopeBarItem.js | 97 - .../UserInterface/ScopeChainDetailsSidebarPanel.js | 170 - .../WebInspectorUI/UserInterface/ScopeChainNode.js | 64 - .../UserInterface/ScopeVariableTreeElement.js | 91 - Source/WebInspectorUI/UserInterface/Script.js | 180 - .../UserInterface/ScriptContentView.css | 32 - .../UserInterface/ScriptContentView.js | 225 - .../UserInterface/ScriptTimelineDataGrid.js | 42 - .../UserInterface/ScriptTimelineDataGridNode.js | 81 - .../UserInterface/ScriptTimelineOverviewGraph.css | 33 - .../UserInterface/ScriptTimelineOverviewGraph.js | 94 - .../UserInterface/ScriptTimelineRecord.js | 264 - .../UserInterface/ScriptTimelineView.css | 40 - .../UserInterface/ScriptTimelineView.js | 188 - .../UserInterface/ScriptTreeElement.js | 63 - Source/WebInspectorUI/UserInterface/SearchBar.css | 49 - Source/WebInspectorUI/UserInterface/SearchBar.js | 98 - .../WebInspectorUI/UserInterface/SearchIcons.css | 52 - .../UserInterface/SearchResultTreeElement.js | 89 - Source/WebInspectorUI/UserInterface/Section.css | 195 - Source/WebInspectorUI/UserInterface/Section.js | 227 - Source/WebInspectorUI/UserInterface/Setting.js | 96 - Source/WebInspectorUI/UserInterface/Sidebar.css | 93 - Source/WebInspectorUI/UserInterface/Sidebar.js | 319 - .../WebInspectorUI/UserInterface/SidebarPanel.js | 156 - Source/WebInspectorUI/UserInterface/Slider.css | 44 - Source/WebInspectorUI/UserInterface/Slider.js | 137 - Source/WebInspectorUI/UserInterface/SourceCode.js | 262 - .../UserInterface/SourceCodeLocation.js | 455 - .../UserInterface/SourceCodePosition.js | 50 - .../UserInterface/SourceCodeRevision.js | 90 - .../UserInterface/SourceCodeTextEditor.css | 76 - .../UserInterface/SourceCodeTextEditor.js | 1369 -- .../UserInterface/SourceCodeTextRange.js | 126 - .../UserInterface/SourceCodeTimeline.js | 82 - .../SourceCodeTimelineTimelineDataGridNode.js | 64 - .../UserInterface/SourceCodeTimelineTreeElement.js | 49 - .../UserInterface/SourceCodeTreeElement.js | 208 - Source/WebInspectorUI/UserInterface/SourceMap.js | 333 - .../UserInterface/SourceMapManager.js | 143 - .../UserInterface/SourceMapResource.js | 153 - .../UserInterface/SourceMapResourceTreeElement.js | 70 - .../WebInspectorUI/UserInterface/StorageManager.js | 234 - .../UserInterface/StorageTreeElement.js | 73 - .../UserInterface/StyleDetailsPanel.js | 163 - .../UserInterface/StyleRuleIcons.css | 48 - .../SyntaxHighlightingDefaultTheme.css | 117 - .../UserInterface/SyntaxHighlightingSupport.js | 51 - Source/WebInspectorUI/UserInterface/Test.html | 221 + .../UserInterface/Test/FrontendTestHarness.js | 256 + .../UserInterface/Test/InspectorProtocol.js | 182 + .../UserInterface/Test/ProtocolTestHarness.js | 78 + Source/WebInspectorUI/UserInterface/Test/Test.js | 120 + .../UserInterface/Test/TestHarness.js | 374 + .../WebInspectorUI/UserInterface/Test/TestStub.js | 40 + .../WebInspectorUI/UserInterface/Test/TestSuite.js | 251 + Source/WebInspectorUI/UserInterface/TestStub.html | 60 + .../UserInterface/TextContentView.css | 32 - .../UserInterface/TextContentView.js | 172 - Source/WebInspectorUI/UserInterface/TextEditor.css | 168 - Source/WebInspectorUI/UserInterface/TextEditor.js | 1326 -- Source/WebInspectorUI/UserInterface/TextMarker.js | 85 - Source/WebInspectorUI/UserInterface/TextRange.js | 161 - .../UserInterface/TextResourceContentView.css | 32 - .../UserInterface/TextResourceContentView.js | 229 - Source/WebInspectorUI/UserInterface/Timeline.js | 108 - .../UserInterface/TimelineContentView.css | 51 - .../UserInterface/TimelineContentView.js | 417 - .../UserInterface/TimelineDataGrid.css | 273 - .../UserInterface/TimelineDataGrid.js | 459 - .../UserInterface/TimelineDataGridNode.js | 346 - .../WebInspectorUI/UserInterface/TimelineIcons.css | 84 - .../UserInterface/TimelineManager.js | 445 - .../WebInspectorUI/UserInterface/TimelineMarker.js | 72 - .../UserInterface/TimelineObserver.js | 42 - .../UserInterface/TimelineOverview.css | 81 - .../UserInterface/TimelineOverview.js | 346 - .../UserInterface/TimelineOverviewGraph.js | 141 - .../WebInspectorUI/UserInterface/TimelineRecord.js | 151 - .../UserInterface/TimelineRecordBar.css | 93 - .../UserInterface/TimelineRecordBar.js | 346 - .../UserInterface/TimelineRecordTreeElement.js | 146 - .../UserInterface/TimelineRecording.js | 163 - .../WebInspectorUI/UserInterface/TimelineRuler.css | 176 - .../WebInspectorUI/UserInterface/TimelineRuler.js | 753 - .../UserInterface/TimelineSidebarPanel.css | 207 - .../UserInterface/TimelineSidebarPanel.js | 354 - .../WebInspectorUI/UserInterface/TimelineView.css | 32 - .../WebInspectorUI/UserInterface/TimelineView.js | 208 - .../UserInterface/ToggleButtonNavigationItem.js | 112 - .../UserInterface/ToggleControlToolbarItem.js | 40 - Source/WebInspectorUI/UserInterface/Toolbar.css | 121 - Source/WebInspectorUI/UserInterface/Toolbar.js | 240 - .../UserInterface/TopDownProfileDataGridTree.js | 121 - .../UserInterface/TreeElementStatusButton.css | 50 - .../UserInterface/TreeElementStatusButton.js | 92 - Source/WebInspectorUI/UserInterface/TreeOutline.js | 1094 -- .../TreeOutlineDataGridSynchronizer.js | 282 - .../WebInspectorUI/UserInterface/URLUtilities.js | 196 - Source/WebInspectorUI/UserInterface/Utilities.js | 951 - .../Views/ActivateButtonNavigationItem.js | 77 + .../Views/ActivateButtonToolbarItem.js | 56 + .../Views/ApplicationCacheDetailsSidebarPanel.js | 150 + .../Views/ApplicationCacheFrameContentView.css | 32 + .../Views/ApplicationCacheFrameContentView.js | 229 + .../Views/ApplicationCacheFrameTreeElement.js | 62 + .../UserInterface/Views/ApplicationCacheIcons.css | 32 + .../Views/ApplicationCacheManifestTreeElement.js | 72 + .../UserInterface/Views/BezierEditor.css | 119 + .../UserInterface/Views/BezierEditor.js | 390 + .../Views/BoxModelDetailsSectionRow.css | 104 + .../Views/BoxModelDetailsSectionRow.js | 434 + .../UserInterface/Views/BreakpointActionView.css | 91 + .../UserInterface/Views/BreakpointActionView.js | 215 + .../Views/BreakpointPopoverController.css | 85 + .../UserInterface/Views/BreakpointTreeElement.css | 86 + .../UserInterface/Views/BreakpointTreeElement.js | 274 + .../UserInterface/Views/ButtonNavigationItem.css | 61 + .../UserInterface/Views/ButtonNavigationItem.js | 140 + .../UserInterface/Views/ButtonToolbarItem.css | 97 + .../UserInterface/Views/ButtonToolbarItem.js | 58 + .../Views/CSSStyleDeclarationSection.css | 168 + .../Views/CSSStyleDeclarationSection.js | 740 + .../Views/CSSStyleDeclarationTextEditor.css | 132 + .../Views/CSSStyleDeclarationTextEditor.js | 1728 ++ .../Views/CSSStyleDetailsSidebarPanel.css | 200 + .../Views/CSSStyleDetailsSidebarPanel.js | 454 + .../UserInterface/Views/CallFrameIcons.css | 44 + .../UserInterface/Views/CallFrameTreeElement.css | 85 + .../UserInterface/Views/CallFrameTreeElement.js | 108 + .../UserInterface/Views/CallFrameView.css | 69 + .../UserInterface/Views/CallFrameView.js | 98 + .../UserInterface/Views/ChartDetailsSectionRow.css | 105 + .../UserInterface/Views/ChartDetailsSectionRow.js | 392 + .../UserInterface/Views/CircleChart.css | 41 + .../UserInterface/Views/CircleChart.js | 216 + .../UserInterface/Views/ClusterContentView.css | 32 + .../UserInterface/Views/ClusterContentView.js | 257 + .../UserInterface/Views/CodeMirrorAdditions.js | 682 + .../UserInterface/Views/CodeMirrorEditor.js | 54 + .../UserInterface/Views/CodeMirrorFormatters.js | 543 + .../UserInterface/Views/CodeMirrorOverrides.css | 183 + .../UserInterface/Views/CodeMirrorTextMarkers.js | 209 + .../UserInterface/Views/CollectionContentView.css | 34 + .../UserInterface/Views/CollectionContentView.js | 192 + .../UserInterface/Views/ColorPicker.css | 83 + .../UserInterface/Views/ColorPicker.js | 337 + .../UserInterface/Views/ColorWheel.css | 40 + .../UserInterface/Views/ColorWheel.js | 282 + .../Views/CompletionSuggestionsView.css | 78 + .../Views/CompletionSuggestionsView.js | 226 + .../Views/ComputedStyleDetailsPanel.css | 57 + .../Views/ComputedStyleDetailsPanel.js | 290 + .../UserInterface/Views/ConsoleCommandView.js | 73 + .../UserInterface/Views/ConsoleGroup.js | 103 + .../UserInterface/Views/ConsoleMessageView.css | 285 + .../UserInterface/Views/ConsoleMessageView.js | 871 + .../UserInterface/Views/ConsolePrompt.css | 37 + .../UserInterface/Views/ConsolePrompt.js | 330 + .../UserInterface/Views/ConsoleSession.js | 92 + .../UserInterface/Views/ConsoleTabContentView.js | 89 + .../UserInterface/Views/ContentBrowser.css | 38 + .../UserInterface/Views/ContentBrowser.js | 513 + .../Views/ContentBrowserTabContentView.css | 32 + .../Views/ContentBrowserTabContentView.js | 270 + .../Views/ContentFlowDOMTreeContentView.js | 96 + .../UserInterface/Views/ContentFlowIcon.css | 32 + .../UserInterface/Views/ContentFlowTreeElement.js | 39 + .../UserInterface/Views/ContentView.css | 36 + .../UserInterface/Views/ContentView.js | 431 + .../UserInterface/Views/ContentViewContainer.css | 39 + .../UserInterface/Views/ContentViewContainer.js | 498 + .../UserInterface/Views/ContextMenu.js | 237 + .../UserInterface/Views/ContextMenuUtilities.js | 66 + .../UserInterface/Views/ControlToolbarItem.css | 69 + .../UserInterface/Views/ControlToolbarItem.js | 39 + .../UserInterface/Views/CookieIcon.css | 28 + .../Views/CookieStorageContentView.css | 32 + .../Views/CookieStorageContentView.js | 237 + .../Views/CookieStorageTreeElement.js | 46 + .../UserInterface/Views/DOMDetailsSidebarPanel.js | 112 + .../Views/DOMNodeDetailsSidebarPanel.js | 706 + .../UserInterface/Views/DOMStorageContentView.css | 42 + .../UserInterface/Views/DOMStorageContentView.js | 260 + .../UserInterface/Views/DOMStorageIcons.css | 32 + .../UserInterface/Views/DOMStorageTreeElement.js | 56 + .../UserInterface/Views/DOMTreeContentView.css | 28 + .../UserInterface/Views/DOMTreeContentView.js | 549 + .../UserInterface/Views/DOMTreeDataGrid.css | 35 + .../UserInterface/Views/DOMTreeDataGrid.js | 62 + .../UserInterface/Views/DOMTreeDataGridNode.js | 69 + .../UserInterface/Views/DOMTreeElement.js | 1669 ++ .../Views/DOMTreeElementPathComponent.js | 143 + .../UserInterface/Views/DOMTreeOutline.css | 217 + .../UserInterface/Views/DOMTreeOutline.js | 567 + .../UserInterface/Views/DOMTreeUpdater.js | 159 + .../UserInterface/Views/DashboardContainerView.css | 171 + .../UserInterface/Views/DashboardContainerView.js | 283 + .../UserInterface/Views/DashboardView.js | 85 + .../UserInterface/Views/DataGrid.css | 356 + .../WebInspectorUI/UserInterface/Views/DataGrid.js | 1951 ++ .../UserInterface/Views/DataGridNode.js | 755 + .../UserInterface/Views/DatabaseContentView.css | 115 + .../UserInterface/Views/DatabaseContentView.js | 129 + .../UserInterface/Views/DatabaseHostTreeElement.js | 49 + .../UserInterface/Views/DatabaseIcon.css | 28 + .../Views/DatabaseTableContentView.css | 32 + .../Views/DatabaseTableContentView.js | 120 + .../UserInterface/Views/DatabaseTableIcon.css | 28 + .../Views/DatabaseTableTreeElement.js | 34 + .../UserInterface/Views/DatabaseTreeElement.js | 69 + .../Views/DatabaseUserQueryErrorView.js | 35 + .../Views/DatabaseUserQuerySuccessView.js | 60 + .../Views/DatabaseUserQueryViewBase.js | 51 + .../UserInterface/Views/DebuggerDashboardView.css | 159 + .../UserInterface/Views/DebuggerDashboardView.js | 104 + .../UserInterface/Views/DebuggerSidebarPanel.css | 96 + .../UserInterface/Views/DebuggerSidebarPanel.js | 1018 ++ .../UserInterface/Views/DebuggerTabContentView.js | 95 + .../UserInterface/Views/DebuggerTreeElement.js | 39 + .../UserInterface/Views/DefaultDashboardView.css | 196 + .../UserInterface/Views/DefaultDashboardView.js | 200 + .../UserInterface/Views/DetailsSection.css | 284 + .../UserInterface/Views/DetailsSection.js | 155 + .../Views/DetailsSectionDataGridRow.js | 62 + .../UserInterface/Views/DetailsSectionGroup.js | 59 + .../UserInterface/Views/DetailsSectionRow.js | 76 + .../UserInterface/Views/DetailsSectionSimpleRow.js | 115 + .../UserInterface/Views/DetailsSectionTextRow.js | 48 + .../UserInterface/Views/DetailsSidebarPanel.js | 50 + .../WebInspectorUI/UserInterface/Views/Dialog.js | 102 + .../UserInterface/Views/DividerNavigationItem.css | 39 + .../UserInterface/Views/DividerNavigationItem.js | 39 + .../WebInspectorUI/UserInterface/Views/Editing.css | 54 + .../UserInterface/Views/EditingSupport.js | 329 + .../UserInterface/Views/ElementsTabContentView.js | 132 + .../UserInterface/Views/ErrorObjectView.css | 62 + .../UserInterface/Views/ErrorObjectView.js | 144 + .../UserInterface/Views/EventListenerSection.js | 45 + .../Views/EventListenerSectionGroup.css | 30 + .../Views/EventListenerSectionGroup.js | 95 + .../UserInterface/Views/FilterBar.css | 83 + .../UserInterface/Views/FilterBar.js | 148 + .../UserInterface/Views/FilterBarButton.js | 56 + .../UserInterface/Views/FilterBarNavigationItem.js | 41 + .../UserInterface/Views/FindBanner.css | 240 + .../UserInterface/Views/FindBanner.js | 327 + .../Views/FlexibleSpaceNavigationItem.css | 28 + .../Views/FlexibleSpaceNavigationItem.js | 39 + .../UserInterface/Views/FolderIcon.css | 28 + .../UserInterface/Views/FolderTreeElement.js | 39 + .../UserInterface/Views/FolderizedTreeElement.js | 393 + .../Views/FontResourceContentView.css | 100 + .../UserInterface/Views/FontResourceContentView.js | 152 + .../UserInterface/Views/FormattedValue.css | 79 + .../UserInterface/Views/FormattedValue.js | 260 + .../UserInterface/Views/FrameDOMTreeContentView.js | 84 + .../UserInterface/Views/FrameTreeElement.js | 251 + .../UserInterface/Views/GeneralTabBarItem.js | 91 + .../UserInterface/Views/GeneralTreeElement.js | 350 + .../Views/GeneralTreeElementPathComponent.js | 73 + .../Views/GenericResourceContentView.js | 32 + .../UserInterface/Views/GoToLineDialog.css | 95 + .../UserInterface/Views/GoToLineDialog.js | 137 + .../UserInterface/Views/GradientEditor.css | 111 + .../UserInterface/Views/GradientEditor.js | 250 + .../UserInterface/Views/GradientSlider.css | 105 + .../UserInterface/Views/GradientSlider.js | 450 + .../Views/HeapAllocationsTimelineDataGridNode.js | 129 + ...AllocationsTimelineDataGridNodePathComponent.js | 53 + .../Views/HeapAllocationsTimelineOverviewGraph.css | 51 + .../Views/HeapAllocationsTimelineOverviewGraph.js | 135 + .../Views/HeapAllocationsTimelineView.css | 56 + .../Views/HeapAllocationsTimelineView.js | 478 + .../Views/HeapSnapshotClassDataGridNode.js | 219 + .../Views/HeapSnapshotClusterContentView.js | 242 + .../UserInterface/Views/HeapSnapshotContentView.js | 158 + .../Views/HeapSnapshotDataGridTree.js | 274 + .../Views/HeapSnapshotInstanceDataGridNode.js | 479 + .../HeapSnapshotInstanceFetchMoreDataGridNode.js | 70 + .../Views/HeapSnapshotInstancesContentView.css | 199 + .../Views/HierarchicalPathComponent.css | 133 + .../Views/HierarchicalPathComponent.js | 314 + .../Views/HierarchicalPathNavigationItem.js | 249 + .../UserInterface/Views/HoverMenu.css | 67 + .../UserInterface/Views/HoverMenu.js | 275 + .../UserInterface/Views/IdleTreeElement.css | 28 + .../UserInterface/Views/IdleTreeElement.js | 32 + .../Views/ImageResourceContentView.css | 49 + .../Views/ImageResourceContentView.js | 53 + .../Views/IndeterminateProgressSpinner.css | 93 + .../Views/IndeterminateProgressSpinner.js | 42 + .../Views/IndexedDatabaseDetailsSidebarPanel.js | 140 + .../Views/IndexedDatabaseEntryDataGridNode.js | 50 + .../Views/IndexedDatabaseHostTreeElement.js | 49 + .../IndexedDatabaseObjectStoreContentView.css | 45 + .../Views/IndexedDatabaseObjectStoreContentView.js | 174 + .../IndexedDatabaseObjectStoreIndexTreeElement.js | 43 + .../Views/IndexedDatabaseObjectStoreTreeElement.js | 63 + .../Views/IndexedDatabaseTreeElement.js | 63 + .../UserInterface/Views/InlineSwatch.css | 113 + .../UserInterface/Views/InlineSwatch.js | 340 + .../UserInterface/Views/IssueTreeElement.css | 36 + .../UserInterface/Views/IssueTreeElement.js | 73 + .../UserInterface/Views/LayerTreeDataGridNode.js | 165 + .../Views/LayerTreeDetailsSidebarPanel.css | 99 + .../Views/LayerTreeDetailsSidebarPanel.js | 431 + .../UserInterface/Views/LayoutTimelineDataGrid.js | 34 + .../Views/LayoutTimelineDataGridNode.js | 86 + .../Views/LayoutTimelineOverviewGraph.css | 37 + .../Views/LayoutTimelineOverviewGraph.js | 115 + .../UserInterface/Views/LayoutTimelineView.css | 36 + .../UserInterface/Views/LayoutTimelineView.js | 322 + .../UserInterface/Views/LineChart.js | 111 + .../UserInterface/Views/LogContentView.css | 230 + .../UserInterface/Views/LogContentView.js | 1032 ++ .../WebInspectorUI/UserInterface/Views/LogIcon.css | 28 + .../UserInterface/Views/LogTreeElement.js | 43 + Source/WebInspectorUI/UserInterface/Views/Main.css | 397 + .../UserInterface/Views/MemoryCategoryView.css | 48 + .../UserInterface/Views/MemoryCategoryView.js | 124 + .../Views/MemoryTimelineOverviewGraph.css | 76 + .../Views/MemoryTimelineOverviewGraph.js | 262 + .../UserInterface/Views/MemoryTimelineView.css | 182 + .../UserInterface/Views/MemoryTimelineView.js | 408 + .../UserInterface/Views/MultipleScopeBarItem.js | 187 + .../UserInterface/Views/NavigationBar.css | 48 + .../UserInterface/Views/NavigationBar.js | 398 + .../UserInterface/Views/NavigationItem.js | 102 + .../UserInterface/Views/NavigationSidebarPanel.css | 87 + .../UserInterface/Views/NavigationSidebarPanel.js | 754 + .../UserInterface/Views/NetworkGridContentView.css | 44 + .../UserInterface/Views/NetworkGridContentView.js | 392 + .../UserInterface/Views/NetworkSidebarPanel.css | 105 + .../UserInterface/Views/NetworkSidebarPanel.js | 232 + .../UserInterface/Views/NetworkTabContentView.js | 70 + .../Views/NetworkTimelineOverviewGraph.css | 45 + .../Views/NetworkTimelineOverviewGraph.js | 160 + .../UserInterface/Views/NetworkTimelineView.css | 40 + .../UserInterface/Views/NetworkTimelineView.js | 264 + .../UserInterface/Views/NewTabContentView.css | 89 + .../UserInterface/Views/NewTabContentView.js | 163 + .../UserInterface/Views/ObjectPreviewView.css | 45 + .../UserInterface/Views/ObjectPreviewView.js | 290 + .../Views/ObjectPropertiesDetailSectionRow.js | 61 + .../Views/ObjectTreeArrayIndexTreeElement.css | 65 + .../Views/ObjectTreeArrayIndexTreeElement.js | 86 + .../Views/ObjectTreeBaseTreeElement.js | 260 + .../Views/ObjectTreeMapEntryTreeElement.css | 42 + .../Views/ObjectTreeMapEntryTreeElement.js | 132 + .../Views/ObjectTreePropertyTreeElement.css | 152 + .../Views/ObjectTreePropertyTreeElement.js | 398 + .../Views/ObjectTreeSetIndexTreeElement.js | 84 + .../UserInterface/Views/ObjectTreeView.css | 130 + .../UserInterface/Views/ObjectTreeView.js | 383 + .../UserInterface/Views/OpenResourceDialog.css | 132 + .../UserInterface/Views/OpenResourceDialog.js | 335 + .../UserInterface/Views/OverviewTimelineView.css | 84 + .../UserInterface/Views/OverviewTimelineView.js | 305 + .../UserInterface/Views/PathComponentIcons.css | 116 + .../UserInterface/Views/PinnedTabBarItem.js | 51 + .../WebInspectorUI/UserInterface/Views/Popover.css | 92 + .../WebInspectorUI/UserInterface/Views/Popover.js | 603 + .../Views/ProbeDetailsSidebarPanel.css | 59 + .../Views/ProbeDetailsSidebarPanel.js | 126 + .../UserInterface/Views/ProbeSetDataGrid.css | 92 + .../UserInterface/Views/ProbeSetDataGrid.js | 190 + .../UserInterface/Views/ProbeSetDataGridNode.js | 97 + .../UserInterface/Views/ProbeSetDetailsSection.js | 163 + .../UserInterface/Views/ProfileDataGridNode.js | 269 + .../UserInterface/Views/ProfileDataGridTree.js | 291 + .../UserInterface/Views/ProfileNodeDataGridNode.js | 191 + .../UserInterface/Views/ProfileNodeTreeElement.js | 135 + .../UserInterface/Views/ProfileView.css | 105 + .../UserInterface/Views/ProfileView.js | 308 + .../UserInterface/Views/QuickConsole.css | 89 + .../UserInterface/Views/QuickConsole.js | 361 + .../Views/QuickConsoleNavigationBar.js | 38 + .../Views/RadioButtonNavigationItem.css | 51 + .../Views/RadioButtonNavigationItem.js | 99 + .../Views/RenderingFrameTimelineDataGridNode.js | 87 + .../Views/RenderingFrameTimelineOverviewGraph.css | 63 + .../Views/RenderingFrameTimelineOverviewGraph.js | 276 + .../Views/RenderingFrameTimelineView.css | 36 + .../Views/RenderingFrameTimelineView.js | 307 + .../UserInterface/Views/ReplayDashboardView.css | 55 + .../UserInterface/Views/ReplayDashboardView.js | 116 + .../WebInspectorUI/UserInterface/Views/Resizer.css | 56 + .../WebInspectorUI/UserInterface/Views/Resizer.js | 158 + .../Views/ResourceClusterContentView.js | 275 + .../UserInterface/Views/ResourceContentView.js | 140 + .../Views/ResourceDetailsSidebarPanel.js | 508 + .../UserInterface/Views/ResourceIcons.css | 114 + .../UserInterface/Views/ResourceSidebarPanel.css | 35 + .../UserInterface/Views/ResourceSidebarPanel.js | 458 + .../Views/ResourceTimelineDataGridNode.css | 49 + .../Views/ResourceTimelineDataGridNode.js | 387 + .../Views/ResourceTimingPopoverDataGridNode.js | 59 + .../UserInterface/Views/ResourceTreeElement.css | 33 + .../UserInterface/Views/ResourceTreeElement.js | 205 + .../UserInterface/Views/ResourcesTabContentView.js | 72 + .../UserInterface/Views/RulesStyleDetailsPanel.css | 96 + .../UserInterface/Views/RulesStyleDetailsPanel.js | 474 + .../UserInterface/Views/ScopeBar.css | 99 + .../WebInspectorUI/UserInterface/Views/ScopeBar.js | 163 + .../UserInterface/Views/ScopeBarItem.js | 101 + .../Views/ScopeChainDetailsSidebarPanel.css | 60 + .../Views/ScopeChainDetailsSidebarPanel.js | 500 + .../Views/ScopeRadioButtonNavigationItem.css | 63 + .../Views/ScopeRadioButtonNavigationItem.js | 94 + .../Views/ScriptClusterTimelineView.js | 215 + .../UserInterface/Views/ScriptContentView.css | 32 + .../UserInterface/Views/ScriptContentView.js | 272 + .../Views/ScriptDetailsTimelineView.css | 52 + .../Views/ScriptDetailsTimelineView.js | 239 + .../Views/ScriptProfileTimelineView.js | 215 + .../UserInterface/Views/ScriptTimelineDataGrid.js | 34 + .../Views/ScriptTimelineDataGridNode.js | 185 + .../Views/ScriptTimelineOverviewGraph.css | 33 + .../Views/ScriptTimelineOverviewGraph.js | 95 + .../UserInterface/Views/ScriptTreeElement.js | 64 + .../UserInterface/Views/SearchBar.css | 54 + .../UserInterface/Views/SearchBar.js | 98 + .../UserInterface/Views/SearchIcons.css | 52 + .../UserInterface/Views/SearchResultTreeElement.js | 86 + .../UserInterface/Views/SearchSidebarPanel.css | 53 + .../UserInterface/Views/SearchSidebarPanel.js | 385 + .../UserInterface/Views/SearchTabContentView.js | 98 + .../UserInterface/Views/SettingsTabContentView.css | 83 + .../UserInterface/Views/SettingsTabContentView.js | 221 + .../WebInspectorUI/UserInterface/Views/Sidebar.css | 83 + .../WebInspectorUI/UserInterface/Views/Sidebar.js | 297 + .../UserInterface/Views/SidebarPanel.css | 35 + .../UserInterface/Views/SidebarPanel.js | 148 + .../WebInspectorUI/UserInterface/Views/Slider.css | 49 + .../WebInspectorUI/UserInterface/Views/Slider.js | 147 + .../UserInterface/Views/SourceCodeTextEditor.css | 218 + .../UserInterface/Views/SourceCodeTextEditor.js | 2251 +++ .../SourceCodeTimelineTimelineDataGridNode.js | 106 + .../Views/SourceCodeTimelineTreeElement.js | 50 + .../UserInterface/Views/SourceCodeTreeElement.js | 207 + .../Views/SourceMapResourceTreeElement.js | 55 + .../UserInterface/Views/SpringEditor.css | 109 + .../UserInterface/Views/SpringEditor.js | 242 + .../UserInterface/Views/StackTraceView.css | 28 + .../UserInterface/Views/StackTraceView.js | 48 + .../UserInterface/Views/StackedLineChart.js | 147 + .../UserInterface/Views/StorageSidebarPanel.css | 35 + .../UserInterface/Views/StorageSidebarPanel.js | 381 + .../UserInterface/Views/StorageTabContentView.js | 71 + .../UserInterface/Views/StorageTreeElement.js | 69 + .../UserInterface/Views/StyleDetailsPanel.js | 162 + .../UserInterface/Views/StyleRuleIcons.css | 65 + .../Views/SyntaxHighlightingDefaultTheme.css | 126 + .../Views/SyntaxHighlightingSupport.js | 51 + .../WebInspectorUI/UserInterface/Views/TabBar.css | 377 + .../WebInspectorUI/UserInterface/Views/TabBar.js | 764 + .../UserInterface/Views/TabBarItem.js | 108 + .../UserInterface/Views/TabBrowser.css | 48 + .../UserInterface/Views/TabBrowser.js | 474 + .../UserInterface/Views/TabContentView.js | 184 + .../UserInterface/Views/TextContentView.css | 32 + .../UserInterface/Views/TextContentView.js | 172 + .../UserInterface/Views/TextEditor.css | 130 + .../UserInterface/Views/TextEditor.js | 1663 ++ .../UserInterface/Views/TextNavigationItem.css | 34 + .../UserInterface/Views/TextNavigationItem.js | 49 + .../Views/TextResourceContentView.css | 32 + .../UserInterface/Views/TextResourceContentView.js | 282 + .../Views/TextToggleButtonNavigationItem.css | 51 + .../Views/TextToggleButtonNavigationItem.js | 62 + .../UserInterface/Views/ThreadTreeElement.css | 67 + .../UserInterface/Views/ThreadTreeElement.js | 153 + .../UserInterface/Views/TimelineDataGrid.css | 60 + .../UserInterface/Views/TimelineDataGrid.js | 534 + .../UserInterface/Views/TimelineDataGridNode.js | 401 + .../Views/TimelineDataGridNodePathComponent.js | 65 + .../UserInterface/Views/TimelineIcons.css | 118 + .../UserInterface/Views/TimelineOverview.css | 218 + .../UserInterface/Views/TimelineOverview.js | 1011 + .../UserInterface/Views/TimelineOverviewGraph.js | 258 + .../UserInterface/Views/TimelineRecordBar.css | 106 + .../UserInterface/Views/TimelineRecordBar.js | 380 + .../UserInterface/Views/TimelineRecordFrame.css | 95 + .../UserInterface/Views/TimelineRecordFrame.js | 285 + .../Views/TimelineRecordTreeElement.js | 116 + .../Views/TimelineRecordingContentView.css | 88 + .../Views/TimelineRecordingContentView.js | 817 + .../Views/TimelineRecordingProgressView.js | 61 + .../UserInterface/Views/TimelineRuler.css | 233 + .../UserInterface/Views/TimelineRuler.js | 943 + .../UserInterface/Views/TimelineTabContentView.css | 46 + .../UserInterface/Views/TimelineTabContentView.js | 571 + .../UserInterface/Views/TimelineTreeElement.js | 120 + .../UserInterface/Views/TimelineView.css | 47 + .../UserInterface/Views/TimelineView.js | 344 + .../UserInterface/Views/TitleView.css | 37 + .../UserInterface/Views/TitleView.js | 35 + .../Views/ToggleButtonNavigationItem.js | 106 + .../Views/ToggleControlToolbarItem.js | 39 + .../WebInspectorUI/UserInterface/Views/Toolbar.css | 215 + .../WebInspectorUI/UserInterface/Views/Toolbar.js | 259 + .../UserInterface/Views/TreeElement.js | 635 + .../Views/TreeElementStatusButton.css | 47 + .../UserInterface/Views/TreeElementStatusButton.js | 86 + .../UserInterface/Views/TreeOutline.css | 225 + .../UserInterface/Views/TreeOutline.js | 687 + .../Views/TreeOutlineDataGridSynchronizer.js | 284 + .../UserInterface/Views/TreeOutlineGroup.js | 96 + .../UserInterface/Views/TypeTokenView.css | 72 + .../UserInterface/Views/TypeTokenView.js | 207 + .../UserInterface/Views/TypeTreeElement.css | 89 + .../UserInterface/Views/TypeTreeElement.js | 130 + .../UserInterface/Views/TypeTreeView.css | 66 + .../UserInterface/Views/TypeTreeView.js | 92 + .../UserInterface/Views/Variables.css | 102 + Source/WebInspectorUI/UserInterface/Views/View.js | 342 + .../Views/VisualStyleBackgroundPicker.css | 78 + .../Views/VisualStyleBackgroundPicker.js | 226 + .../UserInterface/Views/VisualStyleBasicInput.js | 77 + .../UserInterface/Views/VisualStyleColorPicker.css | 71 + .../UserInterface/Views/VisualStyleColorPicker.js | 189 + .../VisualStyleCommaSeparatedKeywordEditor.css | 117 + .../VisualStyleCommaSeparatedKeywordEditor.js | 291 + .../Views/VisualStyleDetailsPanel.css | 121 + .../UserInterface/Views/VisualStyleDetailsPanel.js | 1611 ++ .../Views/VisualStyleFontFamilyListEditor.js | 158 + .../Views/VisualStyleFontFamilyTreeElement.js | 175 + .../Views/VisualStyleKeywordCheckbox.css | 33 + .../Views/VisualStyleKeywordCheckbox.js | 63 + .../Views/VisualStyleKeywordIconList.css | 82 + .../Views/VisualStyleKeywordIconList.js | 110 + .../Views/VisualStyleKeywordPicker.js | 157 + .../Views/VisualStyleNumberInputBox.css | 82 + .../Views/VisualStyleNumberInputBox.js | 408 + .../Views/VisualStylePropertyCombiner.js | 204 + .../Views/VisualStylePropertyEditor.css | 147 + .../Views/VisualStylePropertyEditor.js | 617 + .../Views/VisualStylePropertyEditorLink.css | 150 + .../Views/VisualStylePropertyEditorLink.js | 147 + .../Views/VisualStylePropertyNameInput.js | 141 + .../Views/VisualStyleRelativeNumberSlider.css | 48 + .../Views/VisualStyleRelativeNumberSlider.js | 89 + .../Views/VisualStyleSelectorSection.css | 120 + .../Views/VisualStyleSelectorSection.js | 329 + .../Views/VisualStyleSelectorTreeItem.css | 139 + .../Views/VisualStyleSelectorTreeItem.js | 295 + .../Views/VisualStyleTabbedPropertiesRow.css | 51 + .../Views/VisualStyleTabbedPropertiesRow.js | 69 + .../Views/VisualStyleTimingEditor.css | 48 + .../UserInterface/Views/VisualStyleTimingEditor.js | 161 + .../UserInterface/Views/VisualStyleURLInput.js | 75 + .../UserInterface/Views/VisualStyleUnitSlider.css | 34 + .../UserInterface/Views/VisualStyleUnitSlider.js | 67 + .../UserInterface/Views/WorkerTreeElement.js | 166 + .../WebInspectorUI/UserInterface/WebInspector.js | 26 - .../Workers/Formatter/ESTreeWalker.js | 309 + .../Workers/Formatter/EsprimaFormatter.js | 934 + .../Workers/Formatter/FormatterContentBuilder.js | 244 + .../Workers/Formatter/FormatterUtilities.js | 64 + .../Workers/Formatter/FormatterWorker.js | 108 + .../Workers/HeapSnapshot/HeapSnapshot.js | 838 + .../Workers/HeapSnapshot/HeapSnapshotWorker.js | 120 + 1339 files changed, 179315 insertions(+), 107164 deletions(-) delete mode 100644 Source/WebInspectorUI/UserInterface/ActivateButtonNavigationItem.js delete mode 100644 Source/WebInspectorUI/UserInterface/ActivateButtonToolbarItem.js delete mode 100644 Source/WebInspectorUI/UserInterface/ApplicationCacheDetailsSidebarPanel.js delete mode 100644 Source/WebInspectorUI/UserInterface/ApplicationCacheFrame.js delete mode 100644 Source/WebInspectorUI/UserInterface/ApplicationCacheFrameContentView.css delete mode 100644 Source/WebInspectorUI/UserInterface/ApplicationCacheFrameContentView.js delete mode 100644 Source/WebInspectorUI/UserInterface/ApplicationCacheFrameTreeElement.js delete mode 100644 Source/WebInspectorUI/UserInterface/ApplicationCacheIcons.css delete mode 100644 Source/WebInspectorUI/UserInterface/ApplicationCacheManager.js delete mode 100644 Source/WebInspectorUI/UserInterface/ApplicationCacheManifest.js delete mode 100644 Source/WebInspectorUI/UserInterface/ApplicationCacheManifestTreeElement.js delete mode 100644 Source/WebInspectorUI/UserInterface/ApplicationCacheObserver.js delete mode 100644 Source/WebInspectorUI/UserInterface/BackForwardEntry.js create mode 100644 Source/WebInspectorUI/UserInterface/Base/DOMUtilities.js create mode 100644 Source/WebInspectorUI/UserInterface/Base/EventListener.js create mode 100644 Source/WebInspectorUI/UserInterface/Base/EventListenerSet.js create mode 100644 Source/WebInspectorUI/UserInterface/Base/ImageUtilities.js create mode 100644 Source/WebInspectorUI/UserInterface/Base/InspectorFrontendHostStub.js create mode 100644 Source/WebInspectorUI/UserInterface/Base/LinkedList.js create mode 100644 Source/WebInspectorUI/UserInterface/Base/ListMultimap.js create mode 100644 Source/WebInspectorUI/UserInterface/Base/LoadLocalizedStrings.js create mode 100644 Source/WebInspectorUI/UserInterface/Base/MIMETypeUtilities.js create mode 100644 Source/WebInspectorUI/UserInterface/Base/Main.js create mode 100644 Source/WebInspectorUI/UserInterface/Base/Object.js create mode 100644 Source/WebInspectorUI/UserInterface/Base/Platform.js create mode 100644 Source/WebInspectorUI/UserInterface/Base/Setting.js create mode 100644 Source/WebInspectorUI/UserInterface/Base/URLUtilities.js create mode 100644 Source/WebInspectorUI/UserInterface/Base/Utilities.js create mode 100644 Source/WebInspectorUI/UserInterface/Base/WebInspector.js create mode 100644 Source/WebInspectorUI/UserInterface/Base/YieldableTask.js delete mode 100644 Source/WebInspectorUI/UserInterface/BinarySearch.js delete mode 100644 Source/WebInspectorUI/UserInterface/BlankStylePropertiesSection.js delete mode 100644 Source/WebInspectorUI/UserInterface/BottomUpProfileDataGridTree.js delete mode 100644 Source/WebInspectorUI/UserInterface/BoxModelDetailsSectionRow.css delete mode 100644 Source/WebInspectorUI/UserInterface/BoxModelDetailsSectionRow.js delete mode 100644 Source/WebInspectorUI/UserInterface/Branch.js delete mode 100644 Source/WebInspectorUI/UserInterface/BranchManager.js delete mode 100644 Source/WebInspectorUI/UserInterface/Breakpoint.css delete mode 100644 Source/WebInspectorUI/UserInterface/Breakpoint.js delete mode 100644 Source/WebInspectorUI/UserInterface/BreakpointAction.js delete mode 100644 Source/WebInspectorUI/UserInterface/BreakpointActionView.css delete mode 100644 Source/WebInspectorUI/UserInterface/BreakpointActionView.js delete mode 100644 Source/WebInspectorUI/UserInterface/BreakpointIcons.css delete mode 100644 Source/WebInspectorUI/UserInterface/BreakpointTreeElement.css delete mode 100644 Source/WebInspectorUI/UserInterface/BreakpointTreeElement.js delete mode 100644 Source/WebInspectorUI/UserInterface/ButtonNavigationItem.css delete mode 100644 Source/WebInspectorUI/UserInterface/ButtonNavigationItem.js delete mode 100644 Source/WebInspectorUI/UserInterface/ButtonToolbarItem.css delete mode 100644 Source/WebInspectorUI/UserInterface/ButtonToolbarItem.js delete mode 100644 Source/WebInspectorUI/UserInterface/CSSCompletions.js delete mode 100644 Source/WebInspectorUI/UserInterface/CSSKeywordCompletions.js delete mode 100644 Source/WebInspectorUI/UserInterface/CSSMedia.js delete mode 100644 Source/WebInspectorUI/UserInterface/CSSObserver.js delete mode 100644 Source/WebInspectorUI/UserInterface/CSSProperty.js delete mode 100644 Source/WebInspectorUI/UserInterface/CSSRule.js delete mode 100644 Source/WebInspectorUI/UserInterface/CSSStyleDeclaration.js delete mode 100644 Source/WebInspectorUI/UserInterface/CSSStyleDeclarationSection.css delete mode 100644 Source/WebInspectorUI/UserInterface/CSSStyleDeclarationSection.js delete mode 100644 Source/WebInspectorUI/UserInterface/CSSStyleDeclarationTextEditor.css delete mode 100644 Source/WebInspectorUI/UserInterface/CSSStyleDeclarationTextEditor.js delete mode 100644 Source/WebInspectorUI/UserInterface/CSSStyleDetailsSidebarPanel.css delete mode 100644 Source/WebInspectorUI/UserInterface/CSSStyleDetailsSidebarPanel.js delete mode 100644 Source/WebInspectorUI/UserInterface/CSSStyleManager.js delete mode 100644 Source/WebInspectorUI/UserInterface/CSSStyleSheet.js delete mode 100644 Source/WebInspectorUI/UserInterface/CallFrame.js delete mode 100644 Source/WebInspectorUI/UserInterface/CallFrameIcons.css delete mode 100644 Source/WebInspectorUI/UserInterface/CallFrameTreeElement.js delete mode 100644 Source/WebInspectorUI/UserInterface/CanvasDataGridNode.js delete mode 100644 Source/WebInspectorUI/UserInterface/CanvasObserver.js delete mode 100644 Source/WebInspectorUI/UserInterface/CanvasProfileObject.js delete mode 100644 Source/WebInspectorUI/UserInterface/CanvasProfileType.js delete mode 100644 Source/WebInspectorUI/UserInterface/CanvasProfileView.js delete mode 100644 Source/WebInspectorUI/UserInterface/ClusterContentView.css delete mode 100644 Source/WebInspectorUI/UserInterface/ClusterContentView.js delete mode 100644 Source/WebInspectorUI/UserInterface/CodeMirrorAdditions.js delete mode 100644 Source/WebInspectorUI/UserInterface/CodeMirrorColorEditingController.js delete mode 100644 Source/WebInspectorUI/UserInterface/CodeMirrorCompletionController.css delete mode 100644 Source/WebInspectorUI/UserInterface/CodeMirrorCompletionController.js delete mode 100644 Source/WebInspectorUI/UserInterface/CodeMirrorDragToAlterNumberController.css delete mode 100644 Source/WebInspectorUI/UserInterface/CodeMirrorDragToAlterNumberController.js delete mode 100644 Source/WebInspectorUI/UserInterface/CodeMirrorFormatters.js delete mode 100644 Source/WebInspectorUI/UserInterface/CodeMirrorOverrides.css delete mode 100644 Source/WebInspectorUI/UserInterface/CodeMirrorTokenTrackingController.css delete mode 100644 Source/WebInspectorUI/UserInterface/CodeMirrorTokenTrackingController.js delete mode 100644 Source/WebInspectorUI/UserInterface/Color.js delete mode 100644 Source/WebInspectorUI/UserInterface/ColorPicker.css delete mode 100644 Source/WebInspectorUI/UserInterface/ColorPicker.js delete mode 100644 Source/WebInspectorUI/UserInterface/ColorWheel.css delete mode 100644 Source/WebInspectorUI/UserInterface/ColorWheel.js delete mode 100644 Source/WebInspectorUI/UserInterface/CompletionSuggestionsView.css delete mode 100644 Source/WebInspectorUI/UserInterface/CompletionSuggestionsView.js delete mode 100644 Source/WebInspectorUI/UserInterface/ComputedStyleDetailsPanel.css delete mode 100644 Source/WebInspectorUI/UserInterface/ComputedStyleDetailsPanel.js delete mode 100644 Source/WebInspectorUI/UserInterface/ConsoleCommand.js delete mode 100644 Source/WebInspectorUI/UserInterface/ConsoleCommandResult.js delete mode 100644 Source/WebInspectorUI/UserInterface/ConsoleGroup.js delete mode 100644 Source/WebInspectorUI/UserInterface/ConsoleMessage.js delete mode 100644 Source/WebInspectorUI/UserInterface/ConsoleMessageImpl.js delete mode 100644 Source/WebInspectorUI/UserInterface/ConsoleObserver.js delete mode 100644 Source/WebInspectorUI/UserInterface/ConsolePrompt.css delete mode 100644 Source/WebInspectorUI/UserInterface/ConsolePrompt.js delete mode 100644 Source/WebInspectorUI/UserInterface/ContentBrowser.css delete mode 100644 Source/WebInspectorUI/UserInterface/ContentBrowser.js delete mode 100644 Source/WebInspectorUI/UserInterface/ContentFlow.js delete mode 100644 Source/WebInspectorUI/UserInterface/ContentFlowDOMTreeContentView.js delete mode 100644 Source/WebInspectorUI/UserInterface/ContentFlowIcon.css delete mode 100644 Source/WebInspectorUI/UserInterface/ContentFlowTreeElement.js delete mode 100644 Source/WebInspectorUI/UserInterface/ContentView.css delete mode 100644 Source/WebInspectorUI/UserInterface/ContentView.js delete mode 100644 Source/WebInspectorUI/UserInterface/ContentViewContainer.css delete mode 100644 Source/WebInspectorUI/UserInterface/ContentViewContainer.js delete mode 100644 Source/WebInspectorUI/UserInterface/ContextMenu.js delete mode 100644 Source/WebInspectorUI/UserInterface/ControlToolbarItem.css delete mode 100644 Source/WebInspectorUI/UserInterface/ControlToolbarItem.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/AnalyzerManager.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/Annotator.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/ApplicationCacheManager.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/BasicBlockAnnotator.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/BranchManager.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/BreakpointLogMessageLexer.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/BreakpointPopoverController.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/CSSStyleManager.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorBezierEditingController.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorColorEditingController.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorCompletionController.css create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorCompletionController.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorDragToAdjustNumberController.css create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorDragToAdjustNumberController.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorEditingController.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorGradientEditingController.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorSpringEditingController.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorTextKillController.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorTokenTrackingController.css create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorTokenTrackingController.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/DOMTreeManager.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/DashboardManager.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/DebuggerManager.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/DragToAdjustController.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/Formatter.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/FormatterSourceMap.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/FrameResourceManager.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/HeapManager.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/IssueManager.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/JavaScriptLogViewController.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/JavaScriptRuntimeCompletionProvider.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/LayerTreeManager.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/LogManager.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/MemoryManager.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/ProbeManager.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/ReplayManager.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/ResourceQueryController.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/RuntimeManager.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/SourceMapManager.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/StorageManager.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/TargetManager.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/TimelineManager.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/TypeTokenAnnotator.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/VisualStyleCompletionsController.js create mode 100644 Source/WebInspectorUI/UserInterface/Controllers/WorkerManager.js delete mode 100644 Source/WebInspectorUI/UserInterface/CookieIcon.css delete mode 100644 Source/WebInspectorUI/UserInterface/CookieStorageContentView.css delete mode 100644 Source/WebInspectorUI/UserInterface/CookieStorageContentView.js delete mode 100644 Source/WebInspectorUI/UserInterface/CookieStorageObject.js delete mode 100644 Source/WebInspectorUI/UserInterface/CookieStorageTreeElement.js delete mode 100644 Source/WebInspectorUI/UserInterface/DOMDetailsSidebarPanel.js delete mode 100644 Source/WebInspectorUI/UserInterface/DOMNode.js delete mode 100644 Source/WebInspectorUI/UserInterface/DOMNodeDetailsSidebarPanel.js delete mode 100644 Source/WebInspectorUI/UserInterface/DOMNodeStyles.js delete mode 100644 Source/WebInspectorUI/UserInterface/DOMObserver.js delete mode 100644 Source/WebInspectorUI/UserInterface/DOMSearchMatchObject.js delete mode 100644 Source/WebInspectorUI/UserInterface/DOMStorageContentView.css delete mode 100644 Source/WebInspectorUI/UserInterface/DOMStorageContentView.js delete mode 100644 Source/WebInspectorUI/UserInterface/DOMStorageIcons.css delete mode 100644 Source/WebInspectorUI/UserInterface/DOMStorageObject.js delete mode 100644 Source/WebInspectorUI/UserInterface/DOMStorageObserver.js delete mode 100644 Source/WebInspectorUI/UserInterface/DOMStorageTreeElement.js delete mode 100644 Source/WebInspectorUI/UserInterface/DOMTree.js delete mode 100644 Source/WebInspectorUI/UserInterface/DOMTreeContentView.css delete mode 100644 Source/WebInspectorUI/UserInterface/DOMTreeContentView.js delete mode 100644 Source/WebInspectorUI/UserInterface/DOMTreeDataGrid.css delete mode 100644 Source/WebInspectorUI/UserInterface/DOMTreeDataGrid.js delete mode 100644 Source/WebInspectorUI/UserInterface/DOMTreeDataGridNode.js delete mode 100644 Source/WebInspectorUI/UserInterface/DOMTreeElement.js delete mode 100644 Source/WebInspectorUI/UserInterface/DOMTreeElementPathComponent.js delete mode 100644 Source/WebInspectorUI/UserInterface/DOMTreeManager.js delete mode 100644 Source/WebInspectorUI/UserInterface/DOMTreeOutline.css delete mode 100644 Source/WebInspectorUI/UserInterface/DOMTreeOutline.js delete mode 100644 Source/WebInspectorUI/UserInterface/DOMTreeUpdater.js delete mode 100644 Source/WebInspectorUI/UserInterface/DOMUtilities.js delete mode 100644 Source/WebInspectorUI/UserInterface/DashboardManager.js delete mode 100644 Source/WebInspectorUI/UserInterface/DashboardView.css delete mode 100644 Source/WebInspectorUI/UserInterface/DashboardView.js delete mode 100644 Source/WebInspectorUI/UserInterface/DataGrid.css delete mode 100644 Source/WebInspectorUI/UserInterface/DataGrid.js delete mode 100644 Source/WebInspectorUI/UserInterface/DatabaseContentView.css delete mode 100644 Source/WebInspectorUI/UserInterface/DatabaseContentView.js delete mode 100644 Source/WebInspectorUI/UserInterface/DatabaseHostTreeElement.js delete mode 100644 Source/WebInspectorUI/UserInterface/DatabaseIcon.css delete mode 100644 Source/WebInspectorUI/UserInterface/DatabaseObject.js delete mode 100644 Source/WebInspectorUI/UserInterface/DatabaseObserver.js delete mode 100644 Source/WebInspectorUI/UserInterface/DatabaseTableContentView.css delete mode 100644 Source/WebInspectorUI/UserInterface/DatabaseTableContentView.js delete mode 100644 Source/WebInspectorUI/UserInterface/DatabaseTableIcon.css delete mode 100644 Source/WebInspectorUI/UserInterface/DatabaseTableObject.js delete mode 100644 Source/WebInspectorUI/UserInterface/DatabaseTableTreeElement.js delete mode 100644 Source/WebInspectorUI/UserInterface/DatabaseTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Debug/Bootstrap.js create mode 100644 Source/WebInspectorUI/UserInterface/Debug/CapturingProtocolTracer.js create mode 100644 Source/WebInspectorUI/UserInterface/Debug/ProtocolTrace.js create mode 100644 Source/WebInspectorUI/UserInterface/Debug/UncaughtExceptionReporter.css create mode 100644 Source/WebInspectorUI/UserInterface/Debug/UncaughtExceptionReporter.js delete mode 100644 Source/WebInspectorUI/UserInterface/DebuggerManager.js delete mode 100644 Source/WebInspectorUI/UserInterface/DebuggerObserver.js delete mode 100644 Source/WebInspectorUI/UserInterface/DebuggerSidebarPanel.css delete mode 100644 Source/WebInspectorUI/UserInterface/DebuggerSidebarPanel.js delete mode 100644 Source/WebInspectorUI/UserInterface/DetailsSection.css delete mode 100644 Source/WebInspectorUI/UserInterface/DetailsSection.js delete mode 100644 Source/WebInspectorUI/UserInterface/DetailsSectionDataGridRow.js delete mode 100644 Source/WebInspectorUI/UserInterface/DetailsSectionGroup.js delete mode 100644 Source/WebInspectorUI/UserInterface/DetailsSectionPropertiesRow.js delete mode 100644 Source/WebInspectorUI/UserInterface/DetailsSectionRow.js delete mode 100644 Source/WebInspectorUI/UserInterface/DetailsSectionSimpleRow.js delete mode 100644 Source/WebInspectorUI/UserInterface/DetailsSidebarPanel.css delete mode 100644 Source/WebInspectorUI/UserInterface/DetailsSidebarPanel.js delete mode 100644 Source/WebInspectorUI/UserInterface/DividerNavigationItem.css delete mode 100644 Source/WebInspectorUI/UserInterface/DividerNavigationItem.js delete mode 100644 Source/WebInspectorUI/UserInterface/Editing.css delete mode 100644 Source/WebInspectorUI/UserInterface/EditingSupport.js delete mode 100644 Source/WebInspectorUI/UserInterface/EventHandler.js delete mode 100644 Source/WebInspectorUI/UserInterface/EventListenerSection.js delete mode 100644 Source/WebInspectorUI/UserInterface/EventListenerSectionGroup.css delete mode 100644 Source/WebInspectorUI/UserInterface/EventListenerSectionGroup.js delete mode 100644 Source/WebInspectorUI/UserInterface/ExecutionContext.js delete mode 100644 Source/WebInspectorUI/UserInterface/ExecutionContextList.js create mode 100644 Source/WebInspectorUI/UserInterface/External/.eslintrc create mode 100644 Source/WebInspectorUI/UserInterface/External/CodeMirror/LICENSE delete mode 100644 Source/WebInspectorUI/UserInterface/External/CodeMirror/less.js create mode 100644 Source/WebInspectorUI/UserInterface/External/CodeMirror/mark-selection.js create mode 100644 Source/WebInspectorUI/UserInterface/External/CodeMirror/sublime.js create mode 100644 Source/WebInspectorUI/UserInterface/External/ESLint/LICENSE create mode 100644 Source/WebInspectorUI/UserInterface/External/ESLint/eslint.js create mode 100644 Source/WebInspectorUI/UserInterface/External/Esprima/LICENSE create mode 100644 Source/WebInspectorUI/UserInterface/External/Esprima/esprima.js delete mode 100644 Source/WebInspectorUI/UserInterface/FilterBar.css delete mode 100644 Source/WebInspectorUI/UserInterface/FilterBar.js delete mode 100644 Source/WebInspectorUI/UserInterface/FindBanner.css delete mode 100644 Source/WebInspectorUI/UserInterface/FindBanner.js delete mode 100644 Source/WebInspectorUI/UserInterface/FlexibleSpaceNavigationItem.css delete mode 100644 Source/WebInspectorUI/UserInterface/FlexibleSpaceNavigationItem.js delete mode 100644 Source/WebInspectorUI/UserInterface/FolderIcon.css delete mode 100644 Source/WebInspectorUI/UserInterface/FolderTreeElement.js delete mode 100644 Source/WebInspectorUI/UserInterface/FontResourceContentView.css delete mode 100644 Source/WebInspectorUI/UserInterface/FontResourceContentView.js delete mode 100644 Source/WebInspectorUI/UserInterface/Formatter.js delete mode 100644 Source/WebInspectorUI/UserInterface/FormatterContentBuilder.js delete mode 100644 Source/WebInspectorUI/UserInterface/FormatterSourceMap.js delete mode 100644 Source/WebInspectorUI/UserInterface/Frame.js delete mode 100644 Source/WebInspectorUI/UserInterface/FrameContentView.js delete mode 100644 Source/WebInspectorUI/UserInterface/FrameDOMTreeContentView.js delete mode 100644 Source/WebInspectorUI/UserInterface/FrameResourceManager.js delete mode 100644 Source/WebInspectorUI/UserInterface/FrameTreeElement.js delete mode 100644 Source/WebInspectorUI/UserInterface/GeneralTreeElement.js delete mode 100644 Source/WebInspectorUI/UserInterface/GeneralTreeElementPathComponent.js delete mode 100644 Source/WebInspectorUI/UserInterface/GenericResourceContentView.js delete mode 100644 Source/WebInspectorUI/UserInterface/Geometry.js delete mode 100644 Source/WebInspectorUI/UserInterface/GoToLineDialog.css delete mode 100644 Source/WebInspectorUI/UserInterface/GoToLineDialog.js delete mode 100644 Source/WebInspectorUI/UserInterface/HierarchicalPathComponent.css delete mode 100644 Source/WebInspectorUI/UserInterface/HierarchicalPathComponent.js delete mode 100644 Source/WebInspectorUI/UserInterface/HierarchicalPathNavigationItem.js delete mode 100644 Source/WebInspectorUI/UserInterface/HoverMenu.css delete mode 100644 Source/WebInspectorUI/UserInterface/HoverMenu.js delete mode 100644 Source/WebInspectorUI/UserInterface/ImageResourceContentView.css delete mode 100644 Source/WebInspectorUI/UserInterface/ImageResourceContentView.js delete mode 100644 Source/WebInspectorUI/UserInterface/ImageUtilities.js create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/AUTHORS create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Assertion.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/BackArrow.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/BackForwardArrows.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/BottomUpTree.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/BreakpointActionAdd.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/BreakpointActionRemove.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/COPYING create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/COPYING_CCBYSA3 create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/COPYING_LGPL2 create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Checkers.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Circle.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/ClearBoth.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/ClearLeft.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/ClearRight.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/CloseLarge.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/CloseTimeline.png delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/CloseTimeline@2x.png delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Colors.png delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Colors@2x.png delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/ColorsLarge.png delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/ColorsLarge@2x.png create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Console.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/CubicBezier.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/DOMTree.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Debug.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Debugger.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/DisclosureTriangleSmallClosed.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/DisclosureTriangleSmallOpen.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/DisclosureTriangleTinyClosed.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/DisclosureTriangleTinyOpen.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/DisclosureTriangles.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Elements.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Eye.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/FloatLeft.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/FloatRight.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/FontStyleItalic.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/FontStyleNormal.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/ForwardArrow.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Gear.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/GradientStop.png create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/GradientStop@2x.png create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/GradientStopSelected.png create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/GradientStopSelected@2x.png create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/HeapAllocationsInstrument.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/HeapSnapshotObjectGraph.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Info.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/LayoutInstrument.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/LessColumns.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Log.png create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Log.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Log@2x.png delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Memory.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/MemoryInstrument.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Minus.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/MoreColumns.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemAngleBrackets.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemBrushAndRuler.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemBug.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemClear.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemCodeCoverage.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemFile.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemLayers.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemLog.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemMagnifyingGlass.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemStopwatch.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemStorage.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemTypes.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemVariable.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Network.png create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Network.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Network@2x.png create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/NetworkInstrument.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/NetworkLarge.png delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/NetworkLarge@2x.png create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/NewTab.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/NewTabPlus.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/PaintFlashing.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/PausedBreakpoint.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Pencil.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Percent.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Plus.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Plus13.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Plus15.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Printer.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Profile.png delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Profile@2x.png create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Program.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Record.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Recording.png delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Recording@2x.png delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/RecordingHovered.png delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/RecordingHovered@2x.png delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/RecordingStopped.png delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/RecordingStopped@2x.png delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Reload.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/ReloadFull.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/ReloadToolbar.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/RenderingFramesInstrument.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/ReplayPauseButton.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/ReplayPlayButton.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/ReplayRecordingButton.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Script.png delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Script@2x.png delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/ScriptLarge.png delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/ScriptLarge@2x.png create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/ScriptsInstrument.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/SearchResults.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/SortIndicatorArrows.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/SortIndicatorDownArrow.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/SortIndicatorUpArrow.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/SourceCode.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/SplitToggleDown.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Stop.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Stopwatch.png create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Stopwatch.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Stopwatch@2x.png create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Storage.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/StyleRule.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/StyleRuleAuthor.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/StyleRuleInherited.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/StyleRuleInspector.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/StyleRulePseudoElement.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/StyleRuleUser.svg delete mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/StyleRuleUserAgent.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/TailDeletedFunction.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/TextAlignCenter.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/TextAlignJustify.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/TextAlignLeft.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/TextAlignRight.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/TextDecorationLineThrough.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/TextDecorationOverline.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/TextDecorationUnderline.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/TextTransformCapitalize.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/TextTransformLowercase.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/TextTransformUppercase.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Thread.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/Timeline.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordAPI.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordComposite.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordConsoleProfile.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordProbeSampled.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordRenderingFrame.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/ToggleLeftSidebar.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/ToggleRightSidebar.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/TypeBoolean.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/TypeNull.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/TypeNumber.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/TypeObject.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/TypeRegex.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/TypeString.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/TypeSymbol.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/TypeUndefined.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/VisualStyleNone.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/VisualStylePropertyLinked.svg create mode 100644 Source/WebInspectorUI/UserInterface/Images/gtk/VisualStylePropertyUnlinked.svg delete mode 100644 Source/WebInspectorUI/UserInterface/IndeterminateProgressSpinner.css delete mode 100644 Source/WebInspectorUI/UserInterface/IndeterminateProgressSpinner.js delete mode 100644 Source/WebInspectorUI/UserInterface/InspectorBackend.js delete mode 100644 Source/WebInspectorUI/UserInterface/InspectorFrontendAPI.js delete mode 100644 Source/WebInspectorUI/UserInterface/InspectorFrontendHostStub.js delete mode 100644 Source/WebInspectorUI/UserInterface/InspectorJSBackendCommands.js delete mode 100644 Source/WebInspectorUI/UserInterface/InspectorObserver.js delete mode 100644 Source/WebInspectorUI/UserInterface/InspectorWebBackendCommands.js delete mode 100644 Source/WebInspectorUI/UserInterface/IssueManager.js delete mode 100644 Source/WebInspectorUI/UserInterface/IssueMessage.js delete mode 100644 Source/WebInspectorUI/UserInterface/JavaScriptLogViewController.js delete mode 100644 Source/WebInspectorUI/UserInterface/JavaScriptProfileObject.js delete mode 100644 Source/WebInspectorUI/UserInterface/JavaScriptProfileType.js delete mode 100644 Source/WebInspectorUI/UserInterface/JavaScriptProfileView.css delete mode 100644 Source/WebInspectorUI/UserInterface/JavaScriptProfileView.js delete mode 100644 Source/WebInspectorUI/UserInterface/JavaScriptRuntimeCompletionProvider.js delete mode 100644 Source/WebInspectorUI/UserInterface/KeyboardShortcut.js delete mode 100644 Source/WebInspectorUI/UserInterface/LayerTreeDataGrid.js delete mode 100644 Source/WebInspectorUI/UserInterface/LayerTreeDataGridNode.js delete mode 100644 Source/WebInspectorUI/UserInterface/LayerTreeManager.js delete mode 100644 Source/WebInspectorUI/UserInterface/LayerTreeObserver.js delete mode 100644 Source/WebInspectorUI/UserInterface/LayerTreeSidebarPanel.css delete mode 100644 Source/WebInspectorUI/UserInterface/LayerTreeSidebarPanel.js delete mode 100644 Source/WebInspectorUI/UserInterface/LayoutTimelineDataGrid.js delete mode 100644 Source/WebInspectorUI/UserInterface/LayoutTimelineDataGridNode.js delete mode 100644 Source/WebInspectorUI/UserInterface/LayoutTimelineOverviewGraph.css delete mode 100644 Source/WebInspectorUI/UserInterface/LayoutTimelineOverviewGraph.js delete mode 100644 Source/WebInspectorUI/UserInterface/LayoutTimelineRecord.js delete mode 100644 Source/WebInspectorUI/UserInterface/LayoutTimelineView.css delete mode 100644 Source/WebInspectorUI/UserInterface/LayoutTimelineView.js delete mode 100644 Source/WebInspectorUI/UserInterface/LoadInspectorBackendCommands.js delete mode 100644 Source/WebInspectorUI/UserInterface/LoadLocalizedStrings.js delete mode 100644 Source/WebInspectorUI/UserInterface/LogContentView.css delete mode 100644 Source/WebInspectorUI/UserInterface/LogContentView.js delete mode 100644 Source/WebInspectorUI/UserInterface/LogIcon.css delete mode 100644 Source/WebInspectorUI/UserInterface/LogManager.js delete mode 100644 Source/WebInspectorUI/UserInterface/LogObject.js delete mode 100644 Source/WebInspectorUI/UserInterface/LogTreeElement.js delete mode 100644 Source/WebInspectorUI/UserInterface/MIMETypeUtilities.js delete mode 100644 Source/WebInspectorUI/UserInterface/Main.css delete mode 100644 Source/WebInspectorUI/UserInterface/Main.js delete mode 100644 Source/WebInspectorUI/UserInterface/MessageDispatcher.js delete mode 100644 Source/WebInspectorUI/UserInterface/MetricsStyleDetailsPanel.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/AnalyzerMessage.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/ApplicationCacheFrame.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/ApplicationCacheManifest.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/BackForwardEntry.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/Branch.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/Breakpoint.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/BreakpointAction.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/CSSCompletions.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/CSSKeywordCompletions.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/CSSMedia.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/CSSProperty.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/CSSRule.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/CSSSelector.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/CSSStyleDeclaration.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/CSSStyleSheet.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/CallFrame.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/CallingContextTree.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/CallingContextTreeNode.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/Collection.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/CollectionEntry.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/CollectionEntryPreview.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/Color.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/ConsoleCommandResultMessage.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/ConsoleMessage.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/ContentFlow.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/CookieStorageObject.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/DOMNode.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/DOMNodeStyles.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/DOMSearchMatchObject.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/DOMStorageObject.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/DOMTree.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/DatabaseObject.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/DatabaseTableObject.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/DebuggerDashboard.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/DebuggerData.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/DefaultDashboard.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/ExecutionContext.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/ExecutionContextList.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/FPSInstrument.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/Frame.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/GarbageCollection.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/Geometry.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/Gradient.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/HeapAllocationsInstrument.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/HeapAllocationsTimelineRecord.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/HeapSnapshotRootPath.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/IndexedDatabase.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/IndexedDatabaseObjectStore.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/IndexedDatabaseObjectStoreIndex.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/Instrument.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/IssueMessage.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/KeyboardShortcut.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/LayoutInstrument.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/LayoutTimelineRecord.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/LazySourceCodeLocation.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/LineWidget.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/LogObject.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/MemoryCategory.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/MemoryInstrument.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/MemoryPressureEvent.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/MemoryTimeline.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/MemoryTimelineRecord.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/NativeFunctionParameters.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/NetworkInstrument.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/NetworkTimeline.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/ObjectPreview.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/Probe.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/ProbeSet.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/ProbeSetDataFrame.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/ProbeSetDataTable.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/Profile.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/ProfileNode.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/ProfileNodeCall.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/PropertyDescriptor.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/PropertyPath.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/PropertyPreview.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/RenderingFrameTimelineRecord.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/ReplayDashboard.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/ReplaySession.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/ReplaySessionSegment.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/Resource.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/ResourceCollection.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/ResourceQueryMatch.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/ResourceQueryResult.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/ResourceTimelineRecord.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/ResourceTimingData.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/Revision.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/ScopeChainNode.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/Script.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/ScriptInstrument.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/ScriptSyntaxTree.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/ScriptTimelineRecord.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/SourceCode.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/SourceCodeLocation.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/SourceCodePosition.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/SourceCodeRevision.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/SourceCodeSearchMatchObject.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/SourceCodeTextRange.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/SourceCodeTimeline.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/SourceMap.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/SourceMapResource.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/StackTrace.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/StructureDescription.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/TextMarker.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/TextRange.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/Timeline.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/TimelineMarker.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/TimelineRange.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/TimelineRecord.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/TimelineRecording.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/TypeDescription.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/TypeSet.js create mode 100644 Source/WebInspectorUI/UserInterface/Models/WrappedPromise.js delete mode 100644 Source/WebInspectorUI/UserInterface/NavigationBar.css delete mode 100644 Source/WebInspectorUI/UserInterface/NavigationBar.js delete mode 100644 Source/WebInspectorUI/UserInterface/NavigationItem.js delete mode 100644 Source/WebInspectorUI/UserInterface/NavigationSidebarPanel.css delete mode 100644 Source/WebInspectorUI/UserInterface/NavigationSidebarPanel.js delete mode 100644 Source/WebInspectorUI/UserInterface/NetworkObserver.js delete mode 100644 Source/WebInspectorUI/UserInterface/NetworkTimeline.js delete mode 100644 Source/WebInspectorUI/UserInterface/NetworkTimelineOverviewGraph.css delete mode 100644 Source/WebInspectorUI/UserInterface/NetworkTimelineOverviewGraph.js delete mode 100644 Source/WebInspectorUI/UserInterface/NetworkTimelineView.css delete mode 100644 Source/WebInspectorUI/UserInterface/NetworkTimelineView.js delete mode 100644 Source/WebInspectorUI/UserInterface/Object.js delete mode 100644 Source/WebInspectorUI/UserInterface/ObjectPropertiesSection.js delete mode 100644 Source/WebInspectorUI/UserInterface/OverviewTimelineView.css delete mode 100644 Source/WebInspectorUI/UserInterface/OverviewTimelineView.js delete mode 100644 Source/WebInspectorUI/UserInterface/PageObserver.js delete mode 100644 Source/WebInspectorUI/UserInterface/PathComponentIcons.css delete mode 100644 Source/WebInspectorUI/UserInterface/Popover.css delete mode 100644 Source/WebInspectorUI/UserInterface/Popover.js delete mode 100644 Source/WebInspectorUI/UserInterface/ProfileDataGridTree.js delete mode 100644 Source/WebInspectorUI/UserInterface/ProfileManager.js delete mode 100644 Source/WebInspectorUI/UserInterface/ProfileObject.js delete mode 100644 Source/WebInspectorUI/UserInterface/ProfileType.js delete mode 100644 Source/WebInspectorUI/UserInterface/ProfileView.css delete mode 100644 Source/WebInspectorUI/UserInterface/ProfileView.js delete mode 100644 Source/WebInspectorUI/UserInterface/ProfilerObserver.js delete mode 100644 Source/WebInspectorUI/UserInterface/PropertiesSection.js create mode 100644 Source/WebInspectorUI/UserInterface/Protocol/ApplicationCacheObserver.js create mode 100644 Source/WebInspectorUI/UserInterface/Protocol/CSSObserver.js create mode 100644 Source/WebInspectorUI/UserInterface/Protocol/Connection.js create mode 100644 Source/WebInspectorUI/UserInterface/Protocol/ConsoleObserver.js create mode 100644 Source/WebInspectorUI/UserInterface/Protocol/DOMObserver.js create mode 100644 Source/WebInspectorUI/UserInterface/Protocol/DOMStorageObserver.js create mode 100644 Source/WebInspectorUI/UserInterface/Protocol/DatabaseObserver.js create mode 100644 Source/WebInspectorUI/UserInterface/Protocol/DebuggerObserver.js create mode 100644 Source/WebInspectorUI/UserInterface/Protocol/HeapObserver.js create mode 100644 Source/WebInspectorUI/UserInterface/Protocol/InspectorBackend.js create mode 100644 Source/WebInspectorUI/UserInterface/Protocol/InspectorFrontendAPI.js create mode 100644 Source/WebInspectorUI/UserInterface/Protocol/InspectorObserver.js create mode 100644 Source/WebInspectorUI/UserInterface/Protocol/LayerTreeObserver.js create mode 100644 Source/WebInspectorUI/UserInterface/Protocol/Legacy/10.0/InspectorBackendCommands.js create mode 100644 Source/WebInspectorUI/UserInterface/Protocol/Legacy/10.3/InspectorBackendCommands.js create mode 100644 Source/WebInspectorUI/UserInterface/Protocol/Legacy/7.0/InspectorBackendCommands.js create mode 100644 Source/WebInspectorUI/UserInterface/Protocol/Legacy/8.0/InspectorBackendCommands.js create mode 100644 Source/WebInspectorUI/UserInterface/Protocol/Legacy/9.0/InspectorBackendCommands.js create mode 100644 Source/WebInspectorUI/UserInterface/Protocol/Legacy/9.3/InspectorBackendCommands.js create mode 100644 Source/WebInspectorUI/UserInterface/Protocol/LoadInspectorBackendCommands.js create mode 100644 Source/WebInspectorUI/UserInterface/Protocol/LoggingProtocolTracer.js create mode 100644 Source/WebInspectorUI/UserInterface/Protocol/MainTarget.js create mode 100644 Source/WebInspectorUI/UserInterface/Protocol/MemoryObserver.js create mode 100644 Source/WebInspectorUI/UserInterface/Protocol/MessageDispatcher.js create mode 100644 Source/WebInspectorUI/UserInterface/Protocol/NetworkObserver.js create mode 100644 Source/WebInspectorUI/UserInterface/Protocol/PageObserver.js create mode 100644 Source/WebInspectorUI/UserInterface/Protocol/ProtocolTracer.js create mode 100644 Source/WebInspectorUI/UserInterface/Protocol/RemoteObject.js create mode 100644 Source/WebInspectorUI/UserInterface/Protocol/ReplayObserver.js create mode 100644 Source/WebInspectorUI/UserInterface/Protocol/RuntimeObserver.js create mode 100644 Source/WebInspectorUI/UserInterface/Protocol/ScriptProfilerObserver.js create mode 100644 Source/WebInspectorUI/UserInterface/Protocol/Target.js create mode 100644 Source/WebInspectorUI/UserInterface/Protocol/TimelineObserver.js create mode 100644 Source/WebInspectorUI/UserInterface/Protocol/WorkerObserver.js create mode 100644 Source/WebInspectorUI/UserInterface/Protocol/WorkerTarget.js create mode 100644 Source/WebInspectorUI/UserInterface/Proxies/FormatterWorkerProxy.js create mode 100644 Source/WebInspectorUI/UserInterface/Proxies/HeapSnapshotDiffProxy.js create mode 100644 Source/WebInspectorUI/UserInterface/Proxies/HeapSnapshotEdgeProxy.js create mode 100644 Source/WebInspectorUI/UserInterface/Proxies/HeapSnapshotNodeProxy.js create mode 100644 Source/WebInspectorUI/UserInterface/Proxies/HeapSnapshotProxy.js create mode 100644 Source/WebInspectorUI/UserInterface/Proxies/HeapSnapshotWorkerProxy.js delete mode 100644 Source/WebInspectorUI/UserInterface/QuickConsole.css delete mode 100644 Source/WebInspectorUI/UserInterface/QuickConsole.js delete mode 100644 Source/WebInspectorUI/UserInterface/QuickConsoleNavigationBar.js delete mode 100644 Source/WebInspectorUI/UserInterface/RadioButtonNavigationItem.css delete mode 100644 Source/WebInspectorUI/UserInterface/RadioButtonNavigationItem.js delete mode 100644 Source/WebInspectorUI/UserInterface/RemoteObject.js delete mode 100644 Source/WebInspectorUI/UserInterface/Resource.js delete mode 100644 Source/WebInspectorUI/UserInterface/ResourceClusterContentView.js delete mode 100644 Source/WebInspectorUI/UserInterface/ResourceCollection.js delete mode 100644 Source/WebInspectorUI/UserInterface/ResourceContentView.js delete mode 100644 Source/WebInspectorUI/UserInterface/ResourceDetailsSidebarPanel.js delete mode 100644 Source/WebInspectorUI/UserInterface/ResourceIcons.css delete mode 100644 Source/WebInspectorUI/UserInterface/ResourceSearchMatchObject.js delete mode 100644 Source/WebInspectorUI/UserInterface/ResourceSidebarPanel.css delete mode 100644 Source/WebInspectorUI/UserInterface/ResourceSidebarPanel.js delete mode 100644 Source/WebInspectorUI/UserInterface/ResourceTimelineDataGridNode.js delete mode 100644 Source/WebInspectorUI/UserInterface/ResourceTimelineDataGridNodePathComponent.js delete mode 100644 Source/WebInspectorUI/UserInterface/ResourceTimelineRecord.js delete mode 100644 Source/WebInspectorUI/UserInterface/ResourceTreeElement.css delete mode 100644 Source/WebInspectorUI/UserInterface/ResourceTreeElement.js delete mode 100644 Source/WebInspectorUI/UserInterface/Revision.js delete mode 100644 Source/WebInspectorUI/UserInterface/RulesStyleDetailsPanel.css delete mode 100644 Source/WebInspectorUI/UserInterface/RulesStyleDetailsPanel.js delete mode 100644 Source/WebInspectorUI/UserInterface/RuntimeManager.js delete mode 100644 Source/WebInspectorUI/UserInterface/RuntimeObserver.js delete mode 100644 Source/WebInspectorUI/UserInterface/ScopeBar.css delete mode 100644 Source/WebInspectorUI/UserInterface/ScopeBar.js delete mode 100644 Source/WebInspectorUI/UserInterface/ScopeBarItem.js delete mode 100644 Source/WebInspectorUI/UserInterface/ScopeChainDetailsSidebarPanel.js delete mode 100644 Source/WebInspectorUI/UserInterface/ScopeChainNode.js delete mode 100644 Source/WebInspectorUI/UserInterface/ScopeVariableTreeElement.js delete mode 100644 Source/WebInspectorUI/UserInterface/Script.js delete mode 100644 Source/WebInspectorUI/UserInterface/ScriptContentView.css delete mode 100644 Source/WebInspectorUI/UserInterface/ScriptContentView.js delete mode 100644 Source/WebInspectorUI/UserInterface/ScriptTimelineDataGrid.js delete mode 100644 Source/WebInspectorUI/UserInterface/ScriptTimelineDataGridNode.js delete mode 100644 Source/WebInspectorUI/UserInterface/ScriptTimelineOverviewGraph.css delete mode 100644 Source/WebInspectorUI/UserInterface/ScriptTimelineOverviewGraph.js delete mode 100644 Source/WebInspectorUI/UserInterface/ScriptTimelineRecord.js delete mode 100644 Source/WebInspectorUI/UserInterface/ScriptTimelineView.css delete mode 100644 Source/WebInspectorUI/UserInterface/ScriptTimelineView.js delete mode 100644 Source/WebInspectorUI/UserInterface/ScriptTreeElement.js delete mode 100644 Source/WebInspectorUI/UserInterface/SearchBar.css delete mode 100644 Source/WebInspectorUI/UserInterface/SearchBar.js delete mode 100644 Source/WebInspectorUI/UserInterface/SearchIcons.css delete mode 100644 Source/WebInspectorUI/UserInterface/SearchResultTreeElement.js delete mode 100644 Source/WebInspectorUI/UserInterface/Section.css delete mode 100644 Source/WebInspectorUI/UserInterface/Section.js delete mode 100644 Source/WebInspectorUI/UserInterface/Setting.js delete mode 100644 Source/WebInspectorUI/UserInterface/Sidebar.css delete mode 100644 Source/WebInspectorUI/UserInterface/Sidebar.js delete mode 100644 Source/WebInspectorUI/UserInterface/SidebarPanel.js delete mode 100644 Source/WebInspectorUI/UserInterface/Slider.css delete mode 100644 Source/WebInspectorUI/UserInterface/Slider.js delete mode 100644 Source/WebInspectorUI/UserInterface/SourceCode.js delete mode 100644 Source/WebInspectorUI/UserInterface/SourceCodeLocation.js delete mode 100644 Source/WebInspectorUI/UserInterface/SourceCodePosition.js delete mode 100644 Source/WebInspectorUI/UserInterface/SourceCodeRevision.js delete mode 100644 Source/WebInspectorUI/UserInterface/SourceCodeTextEditor.css delete mode 100644 Source/WebInspectorUI/UserInterface/SourceCodeTextEditor.js delete mode 100644 Source/WebInspectorUI/UserInterface/SourceCodeTextRange.js delete mode 100644 Source/WebInspectorUI/UserInterface/SourceCodeTimeline.js delete mode 100644 Source/WebInspectorUI/UserInterface/SourceCodeTimelineTimelineDataGridNode.js delete mode 100644 Source/WebInspectorUI/UserInterface/SourceCodeTimelineTreeElement.js delete mode 100644 Source/WebInspectorUI/UserInterface/SourceCodeTreeElement.js delete mode 100644 Source/WebInspectorUI/UserInterface/SourceMap.js delete mode 100644 Source/WebInspectorUI/UserInterface/SourceMapManager.js delete mode 100644 Source/WebInspectorUI/UserInterface/SourceMapResource.js delete mode 100644 Source/WebInspectorUI/UserInterface/SourceMapResourceTreeElement.js delete mode 100644 Source/WebInspectorUI/UserInterface/StorageManager.js delete mode 100644 Source/WebInspectorUI/UserInterface/StorageTreeElement.js delete mode 100644 Source/WebInspectorUI/UserInterface/StyleDetailsPanel.js delete mode 100644 Source/WebInspectorUI/UserInterface/StyleRuleIcons.css delete mode 100644 Source/WebInspectorUI/UserInterface/SyntaxHighlightingDefaultTheme.css delete mode 100644 Source/WebInspectorUI/UserInterface/SyntaxHighlightingSupport.js create mode 100644 Source/WebInspectorUI/UserInterface/Test.html create mode 100644 Source/WebInspectorUI/UserInterface/Test/FrontendTestHarness.js create mode 100644 Source/WebInspectorUI/UserInterface/Test/InspectorProtocol.js create mode 100644 Source/WebInspectorUI/UserInterface/Test/ProtocolTestHarness.js create mode 100644 Source/WebInspectorUI/UserInterface/Test/Test.js create mode 100644 Source/WebInspectorUI/UserInterface/Test/TestHarness.js create mode 100644 Source/WebInspectorUI/UserInterface/Test/TestStub.js create mode 100644 Source/WebInspectorUI/UserInterface/Test/TestSuite.js create mode 100644 Source/WebInspectorUI/UserInterface/TestStub.html delete mode 100644 Source/WebInspectorUI/UserInterface/TextContentView.css delete mode 100644 Source/WebInspectorUI/UserInterface/TextContentView.js delete mode 100644 Source/WebInspectorUI/UserInterface/TextEditor.css delete mode 100644 Source/WebInspectorUI/UserInterface/TextEditor.js delete mode 100644 Source/WebInspectorUI/UserInterface/TextMarker.js delete mode 100644 Source/WebInspectorUI/UserInterface/TextRange.js delete mode 100644 Source/WebInspectorUI/UserInterface/TextResourceContentView.css delete mode 100644 Source/WebInspectorUI/UserInterface/TextResourceContentView.js delete mode 100644 Source/WebInspectorUI/UserInterface/Timeline.js delete mode 100644 Source/WebInspectorUI/UserInterface/TimelineContentView.css delete mode 100644 Source/WebInspectorUI/UserInterface/TimelineContentView.js delete mode 100644 Source/WebInspectorUI/UserInterface/TimelineDataGrid.css delete mode 100644 Source/WebInspectorUI/UserInterface/TimelineDataGrid.js delete mode 100644 Source/WebInspectorUI/UserInterface/TimelineDataGridNode.js delete mode 100644 Source/WebInspectorUI/UserInterface/TimelineIcons.css delete mode 100644 Source/WebInspectorUI/UserInterface/TimelineManager.js delete mode 100644 Source/WebInspectorUI/UserInterface/TimelineMarker.js delete mode 100644 Source/WebInspectorUI/UserInterface/TimelineObserver.js delete mode 100644 Source/WebInspectorUI/UserInterface/TimelineOverview.css delete mode 100644 Source/WebInspectorUI/UserInterface/TimelineOverview.js delete mode 100644 Source/WebInspectorUI/UserInterface/TimelineOverviewGraph.js delete mode 100644 Source/WebInspectorUI/UserInterface/TimelineRecord.js delete mode 100644 Source/WebInspectorUI/UserInterface/TimelineRecordBar.css delete mode 100644 Source/WebInspectorUI/UserInterface/TimelineRecordBar.js delete mode 100644 Source/WebInspectorUI/UserInterface/TimelineRecordTreeElement.js delete mode 100644 Source/WebInspectorUI/UserInterface/TimelineRecording.js delete mode 100644 Source/WebInspectorUI/UserInterface/TimelineRuler.css delete mode 100644 Source/WebInspectorUI/UserInterface/TimelineRuler.js delete mode 100644 Source/WebInspectorUI/UserInterface/TimelineSidebarPanel.css delete mode 100644 Source/WebInspectorUI/UserInterface/TimelineSidebarPanel.js delete mode 100644 Source/WebInspectorUI/UserInterface/TimelineView.css delete mode 100644 Source/WebInspectorUI/UserInterface/TimelineView.js delete mode 100644 Source/WebInspectorUI/UserInterface/ToggleButtonNavigationItem.js delete mode 100644 Source/WebInspectorUI/UserInterface/ToggleControlToolbarItem.js delete mode 100644 Source/WebInspectorUI/UserInterface/Toolbar.css delete mode 100644 Source/WebInspectorUI/UserInterface/Toolbar.js delete mode 100644 Source/WebInspectorUI/UserInterface/TopDownProfileDataGridTree.js delete mode 100644 Source/WebInspectorUI/UserInterface/TreeElementStatusButton.css delete mode 100644 Source/WebInspectorUI/UserInterface/TreeElementStatusButton.js delete mode 100644 Source/WebInspectorUI/UserInterface/TreeOutline.js delete mode 100644 Source/WebInspectorUI/UserInterface/TreeOutlineDataGridSynchronizer.js delete mode 100644 Source/WebInspectorUI/UserInterface/URLUtilities.js delete mode 100644 Source/WebInspectorUI/UserInterface/Utilities.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ActivateButtonNavigationItem.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ActivateButtonToolbarItem.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ApplicationCacheDetailsSidebarPanel.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ApplicationCacheFrameContentView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/ApplicationCacheFrameContentView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ApplicationCacheFrameTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ApplicationCacheIcons.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/ApplicationCacheManifestTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/BezierEditor.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/BezierEditor.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/BoxModelDetailsSectionRow.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/BoxModelDetailsSectionRow.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/BreakpointActionView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/BreakpointActionView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/BreakpointPopoverController.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/BreakpointTreeElement.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/BreakpointTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ButtonNavigationItem.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/ButtonNavigationItem.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ButtonToolbarItem.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/ButtonToolbarItem.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/CSSStyleDeclarationSection.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/CSSStyleDeclarationSection.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/CSSStyleDeclarationTextEditor.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/CSSStyleDeclarationTextEditor.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/CSSStyleDetailsSidebarPanel.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/CSSStyleDetailsSidebarPanel.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/CallFrameIcons.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/CallFrameTreeElement.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/CallFrameTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/CallFrameView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/CallFrameView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ChartDetailsSectionRow.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/ChartDetailsSectionRow.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/CircleChart.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/CircleChart.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ClusterContentView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/ClusterContentView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/CodeMirrorAdditions.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/CodeMirrorEditor.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/CodeMirrorFormatters.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/CodeMirrorOverrides.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/CodeMirrorTextMarkers.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/CollectionContentView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/CollectionContentView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ColorPicker.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/ColorPicker.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ColorWheel.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/ColorWheel.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/CompletionSuggestionsView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/CompletionSuggestionsView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ComputedStyleDetailsPanel.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/ComputedStyleDetailsPanel.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ConsoleCommandView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ConsoleGroup.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ConsoleMessageView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/ConsoleMessageView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ConsolePrompt.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/ConsolePrompt.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ConsoleSession.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ConsoleTabContentView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ContentBrowser.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/ContentBrowser.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ContentBrowserTabContentView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/ContentBrowserTabContentView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ContentFlowDOMTreeContentView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ContentFlowIcon.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/ContentFlowTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ContentView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/ContentView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ContentViewContainer.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/ContentViewContainer.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ContextMenu.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ContextMenuUtilities.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ControlToolbarItem.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/ControlToolbarItem.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/CookieIcon.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/CookieStorageContentView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/CookieStorageContentView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/CookieStorageTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/DOMDetailsSidebarPanel.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/DOMNodeDetailsSidebarPanel.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/DOMStorageContentView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/DOMStorageContentView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/DOMStorageIcons.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/DOMStorageTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/DOMTreeContentView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/DOMTreeContentView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/DOMTreeDataGrid.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/DOMTreeDataGrid.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/DOMTreeDataGridNode.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/DOMTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/DOMTreeElementPathComponent.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/DOMTreeOutline.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/DOMTreeOutline.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/DOMTreeUpdater.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/DashboardContainerView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/DashboardContainerView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/DashboardView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/DataGrid.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/DataGrid.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/DataGridNode.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/DatabaseContentView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/DatabaseContentView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/DatabaseHostTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/DatabaseIcon.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/DatabaseTableContentView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/DatabaseTableContentView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/DatabaseTableIcon.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/DatabaseTableTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/DatabaseTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/DatabaseUserQueryErrorView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/DatabaseUserQuerySuccessView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/DatabaseUserQueryViewBase.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/DebuggerDashboardView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/DebuggerDashboardView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/DebuggerSidebarPanel.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/DebuggerSidebarPanel.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/DebuggerTabContentView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/DebuggerTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/DefaultDashboardView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/DefaultDashboardView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/DetailsSection.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/DetailsSection.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/DetailsSectionDataGridRow.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/DetailsSectionGroup.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/DetailsSectionRow.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/DetailsSectionSimpleRow.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/DetailsSectionTextRow.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/DetailsSidebarPanel.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/Dialog.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/DividerNavigationItem.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/DividerNavigationItem.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/Editing.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/EditingSupport.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ElementsTabContentView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ErrorObjectView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/ErrorObjectView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/EventListenerSection.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/EventListenerSectionGroup.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/EventListenerSectionGroup.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/FilterBar.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/FilterBar.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/FilterBarButton.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/FilterBarNavigationItem.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/FindBanner.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/FindBanner.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/FlexibleSpaceNavigationItem.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/FlexibleSpaceNavigationItem.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/FolderIcon.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/FolderTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/FolderizedTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/FontResourceContentView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/FontResourceContentView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/FormattedValue.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/FormattedValue.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/FrameDOMTreeContentView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/FrameTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/GeneralTabBarItem.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/GeneralTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/GeneralTreeElementPathComponent.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/GenericResourceContentView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/GoToLineDialog.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/GoToLineDialog.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/GradientEditor.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/GradientEditor.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/GradientSlider.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/GradientSlider.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/HeapAllocationsTimelineDataGridNode.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/HeapAllocationsTimelineDataGridNodePathComponent.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/HeapAllocationsTimelineOverviewGraph.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/HeapAllocationsTimelineOverviewGraph.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/HeapAllocationsTimelineView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/HeapAllocationsTimelineView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/HeapSnapshotClassDataGridNode.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/HeapSnapshotClusterContentView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/HeapSnapshotContentView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/HeapSnapshotDataGridTree.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/HeapSnapshotInstanceDataGridNode.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/HeapSnapshotInstanceFetchMoreDataGridNode.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/HeapSnapshotInstancesContentView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/HierarchicalPathComponent.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/HierarchicalPathComponent.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/HierarchicalPathNavigationItem.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/HoverMenu.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/HoverMenu.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/IdleTreeElement.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/IdleTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ImageResourceContentView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/ImageResourceContentView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/IndeterminateProgressSpinner.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/IndeterminateProgressSpinner.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/IndexedDatabaseDetailsSidebarPanel.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/IndexedDatabaseEntryDataGridNode.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/IndexedDatabaseHostTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/IndexedDatabaseObjectStoreContentView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/IndexedDatabaseObjectStoreContentView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/IndexedDatabaseObjectStoreIndexTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/IndexedDatabaseObjectStoreTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/IndexedDatabaseTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/InlineSwatch.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/InlineSwatch.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/IssueTreeElement.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/IssueTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/LayerTreeDataGridNode.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/LayerTreeDetailsSidebarPanel.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/LayerTreeDetailsSidebarPanel.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/LayoutTimelineDataGrid.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/LayoutTimelineDataGridNode.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/LayoutTimelineOverviewGraph.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/LayoutTimelineOverviewGraph.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/LayoutTimelineView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/LayoutTimelineView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/LineChart.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/LogContentView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/LogContentView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/LogIcon.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/LogTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/Main.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/MemoryCategoryView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/MemoryCategoryView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/MemoryTimelineOverviewGraph.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/MemoryTimelineOverviewGraph.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/MemoryTimelineView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/MemoryTimelineView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/MultipleScopeBarItem.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/NavigationBar.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/NavigationBar.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/NavigationItem.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/NavigationSidebarPanel.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/NavigationSidebarPanel.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/NetworkGridContentView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/NetworkGridContentView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/NetworkSidebarPanel.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/NetworkSidebarPanel.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/NetworkTabContentView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/NetworkTimelineOverviewGraph.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/NetworkTimelineOverviewGraph.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/NetworkTimelineView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/NetworkTimelineView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/NewTabContentView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/NewTabContentView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ObjectPreviewView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/ObjectPreviewView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ObjectPropertiesDetailSectionRow.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ObjectTreeArrayIndexTreeElement.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/ObjectTreeArrayIndexTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ObjectTreeBaseTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ObjectTreeMapEntryTreeElement.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/ObjectTreeMapEntryTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ObjectTreePropertyTreeElement.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/ObjectTreePropertyTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ObjectTreeSetIndexTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ObjectTreeView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/ObjectTreeView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/OpenResourceDialog.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/OpenResourceDialog.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/OverviewTimelineView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/OverviewTimelineView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/PathComponentIcons.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/PinnedTabBarItem.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/Popover.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/Popover.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ProbeDetailsSidebarPanel.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/ProbeDetailsSidebarPanel.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ProbeSetDataGrid.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/ProbeSetDataGrid.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ProbeSetDataGridNode.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ProbeSetDetailsSection.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ProfileDataGridNode.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ProfileDataGridTree.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ProfileNodeDataGridNode.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ProfileNodeTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ProfileView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/ProfileView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/QuickConsole.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/QuickConsole.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/QuickConsoleNavigationBar.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/RadioButtonNavigationItem.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/RadioButtonNavigationItem.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/RenderingFrameTimelineDataGridNode.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/RenderingFrameTimelineOverviewGraph.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/RenderingFrameTimelineOverviewGraph.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/RenderingFrameTimelineView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/RenderingFrameTimelineView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ReplayDashboardView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/ReplayDashboardView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/Resizer.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/Resizer.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ResourceClusterContentView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ResourceContentView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ResourceDetailsSidebarPanel.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ResourceIcons.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/ResourceSidebarPanel.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/ResourceSidebarPanel.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ResourceTimelineDataGridNode.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/ResourceTimelineDataGridNode.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ResourceTimingPopoverDataGridNode.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ResourceTreeElement.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/ResourceTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ResourcesTabContentView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/RulesStyleDetailsPanel.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/RulesStyleDetailsPanel.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ScopeBar.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/ScopeBar.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ScopeBarItem.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ScopeChainDetailsSidebarPanel.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/ScopeChainDetailsSidebarPanel.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ScopeRadioButtonNavigationItem.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/ScopeRadioButtonNavigationItem.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ScriptClusterTimelineView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ScriptContentView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/ScriptContentView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ScriptDetailsTimelineView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/ScriptDetailsTimelineView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ScriptProfileTimelineView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ScriptTimelineDataGrid.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ScriptTimelineDataGridNode.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ScriptTimelineOverviewGraph.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/ScriptTimelineOverviewGraph.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ScriptTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/SearchBar.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/SearchBar.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/SearchIcons.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/SearchResultTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/SearchSidebarPanel.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/SearchSidebarPanel.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/SearchTabContentView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/SettingsTabContentView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/SettingsTabContentView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/Sidebar.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/Sidebar.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/SidebarPanel.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/SidebarPanel.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/Slider.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/Slider.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/SourceCodeTextEditor.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/SourceCodeTextEditor.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/SourceCodeTimelineTimelineDataGridNode.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/SourceCodeTimelineTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/SourceCodeTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/SourceMapResourceTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/SpringEditor.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/SpringEditor.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/StackTraceView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/StackTraceView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/StackedLineChart.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/StorageSidebarPanel.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/StorageSidebarPanel.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/StorageTabContentView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/StorageTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/StyleDetailsPanel.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/StyleRuleIcons.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/SyntaxHighlightingDefaultTheme.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/SyntaxHighlightingSupport.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/TabBar.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/TabBar.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/TabBarItem.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/TabBrowser.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/TabBrowser.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/TabContentView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/TextContentView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/TextContentView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/TextEditor.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/TextEditor.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/TextNavigationItem.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/TextNavigationItem.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/TextResourceContentView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/TextResourceContentView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/TextToggleButtonNavigationItem.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/TextToggleButtonNavigationItem.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ThreadTreeElement.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/ThreadTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/TimelineDataGrid.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/TimelineDataGrid.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/TimelineDataGridNode.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/TimelineDataGridNodePathComponent.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/TimelineIcons.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/TimelineOverview.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/TimelineOverview.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/TimelineOverviewGraph.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/TimelineRecordBar.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/TimelineRecordBar.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/TimelineRecordFrame.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/TimelineRecordFrame.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/TimelineRecordTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/TimelineRecordingContentView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/TimelineRecordingContentView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/TimelineRecordingProgressView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/TimelineRuler.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/TimelineRuler.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/TimelineTabContentView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/TimelineTabContentView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/TimelineTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/TimelineView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/TimelineView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/TitleView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/TitleView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ToggleButtonNavigationItem.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/ToggleControlToolbarItem.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/Toolbar.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/Toolbar.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/TreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/TreeElementStatusButton.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/TreeElementStatusButton.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/TreeOutline.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/TreeOutline.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/TreeOutlineDataGridSynchronizer.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/TreeOutlineGroup.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/TypeTokenView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/TypeTokenView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/TypeTreeElement.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/TypeTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/TypeTreeView.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/TypeTreeView.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/Variables.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/View.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/VisualStyleBackgroundPicker.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/VisualStyleBackgroundPicker.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/VisualStyleBasicInput.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/VisualStyleColorPicker.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/VisualStyleColorPicker.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/VisualStyleCommaSeparatedKeywordEditor.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/VisualStyleCommaSeparatedKeywordEditor.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/VisualStyleDetailsPanel.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/VisualStyleDetailsPanel.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/VisualStyleFontFamilyListEditor.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/VisualStyleFontFamilyTreeElement.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/VisualStyleKeywordCheckbox.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/VisualStyleKeywordCheckbox.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/VisualStyleKeywordIconList.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/VisualStyleKeywordIconList.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/VisualStyleKeywordPicker.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/VisualStyleNumberInputBox.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/VisualStyleNumberInputBox.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/VisualStylePropertyCombiner.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/VisualStylePropertyEditor.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/VisualStylePropertyEditor.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/VisualStylePropertyEditorLink.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/VisualStylePropertyEditorLink.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/VisualStylePropertyNameInput.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/VisualStyleRelativeNumberSlider.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/VisualStyleRelativeNumberSlider.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/VisualStyleSelectorSection.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/VisualStyleSelectorSection.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/VisualStyleSelectorTreeItem.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/VisualStyleSelectorTreeItem.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/VisualStyleTabbedPropertiesRow.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/VisualStyleTabbedPropertiesRow.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/VisualStyleTimingEditor.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/VisualStyleTimingEditor.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/VisualStyleURLInput.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/VisualStyleUnitSlider.css create mode 100644 Source/WebInspectorUI/UserInterface/Views/VisualStyleUnitSlider.js create mode 100644 Source/WebInspectorUI/UserInterface/Views/WorkerTreeElement.js delete mode 100644 Source/WebInspectorUI/UserInterface/WebInspector.js create mode 100644 Source/WebInspectorUI/UserInterface/Workers/Formatter/ESTreeWalker.js create mode 100644 Source/WebInspectorUI/UserInterface/Workers/Formatter/EsprimaFormatter.js create mode 100644 Source/WebInspectorUI/UserInterface/Workers/Formatter/FormatterContentBuilder.js create mode 100644 Source/WebInspectorUI/UserInterface/Workers/Formatter/FormatterUtilities.js create mode 100644 Source/WebInspectorUI/UserInterface/Workers/Formatter/FormatterWorker.js create mode 100644 Source/WebInspectorUI/UserInterface/Workers/HeapSnapshot/HeapSnapshot.js create mode 100644 Source/WebInspectorUI/UserInterface/Workers/HeapSnapshot/HeapSnapshotWorker.js (limited to 'Source/WebInspectorUI/UserInterface') diff --git a/Source/WebInspectorUI/UserInterface/ActivateButtonNavigationItem.js b/Source/WebInspectorUI/UserInterface/ActivateButtonNavigationItem.js deleted file mode 100644 index e5d361f2f..000000000 --- a/Source/WebInspectorUI/UserInterface/ActivateButtonNavigationItem.js +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ActivateButtonNavigationItem = function(identifier, defaultToolTip, activatedToolTip, image, imageWidth, imageHeight, suppressEmboss, role) -{ - WebInspector.ButtonNavigationItem.call(this, identifier, defaultToolTip, image, imageWidth, imageHeight, suppressEmboss, role); - - this._defaultToolTip = defaultToolTip; - this._activatedToolTip = activatedToolTip || defaultToolTip; - this._role = role; -}; - -WebInspector.ActivateButtonNavigationItem.StyleClassName = "activate"; -WebInspector.ActivateButtonNavigationItem.ActivatedStyleClassName = "activated"; - -WebInspector.ActivateButtonNavigationItem.prototype = { - constructor: WebInspector.ActivateButtonNavigationItem, - - // Public - - get defaultToolTip() - { - return this._defaultToolTip; - }, - - get activatedToolTip() - { - return this._activatedToolTip; - }, - - get activated() - { - return this.element.classList.contains(WebInspector.ActivateButtonNavigationItem.ActivatedStyleClassName); - }, - - set activated(flag) - { - if (flag) { - this.toolTip = this._activatedToolTip; - this.element.classList.add(WebInspector.ActivateButtonNavigationItem.ActivatedStyleClassName); - if (this._role === "tab") - this.element.setAttribute("aria-selected", "true"); - } else { - this.toolTip = this._defaultToolTip; - this.element.classList.remove(WebInspector.ActivateButtonNavigationItem.ActivatedStyleClassName); - if (this._role === "tab") - this.element.removeAttribute("aria-selected"); - } - }, - - generateStyleText: function(parentSelector) - { - var classNames = this._classNames.join("."); - - if (this._suppressEmboss) - var styleText = parentSelector + " ." + classNames + " > .glyph { background-size: " + this._imageWidth + "px " + this._imageHeight + "px; }\n"; - else { - var activatedClassName = "." + WebInspector.ActivateButtonNavigationItem.ActivatedStyleClassName; - - // Default state. - var styleText = parentSelector + " ." + classNames + " > .glyph { background-image: -webkit-canvas(" + this._canvasIdentifier(WebInspector.ButtonNavigationItem.States.Normal) + "); background-size: " + this._imageWidth + "px " + this._imageHeight + "px; }\n"; - - // Pressed state. - styleText += parentSelector + " ." + classNames + ":not(.disabled):active > .glyph { background-image: -webkit-canvas(" + this._canvasIdentifier(WebInspector.ButtonNavigationItem.States.Active) + "); }\n"; - - // Activated state. - styleText += parentSelector + " ." + classNames + activatedClassName + ":not(.disabled) > .glyph { background-image: -webkit-canvas(" + this._canvasIdentifier(WebInspector.ButtonNavigationItem.States.Focus) + "); }\n"; - - // Activated and pressed state. - styleText += parentSelector + " ." + classNames + activatedClassName + ":not(.disabled):active > .glyph { background-image: -webkit-canvas(" + this._canvasIdentifier(WebInspector.ButtonNavigationItem.States.ActiveFocus) + "); }\n"; - } - - return styleText; - }, - - // Private - - _additionalClassNames: [WebInspector.ActivateButtonNavigationItem.StyleClassName, WebInspector.ButtonNavigationItem.StyleClassName] -}; - -WebInspector.ActivateButtonNavigationItem.prototype.__proto__ = WebInspector.ButtonNavigationItem.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ActivateButtonToolbarItem.js b/Source/WebInspectorUI/UserInterface/ActivateButtonToolbarItem.js deleted file mode 100644 index afa4327a4..000000000 --- a/Source/WebInspectorUI/UserInterface/ActivateButtonToolbarItem.js +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ActivateButtonToolbarItem = function(identifier, defaultToolTip, activatedToolTip, label, image, suppressEmboss, role) -{ - WebInspector.ActivateButtonNavigationItem.call(this, identifier, defaultToolTip, activatedToolTip, image, 32, 32, suppressEmboss, role); - - console.assert(label); - - this._labelElement = document.createElement("div"); - this._labelElement.className = WebInspector.ButtonToolbarItem.LabelStyleClassName; - this._element.appendChild(this._labelElement); - - this.label = label; -}; - -WebInspector.ActivateButtonToolbarItem.prototype = { - constructor: WebInspector.ActivateButtonToolbarItem, - - // Public - - get label() - { - return this._labelElement.textContent; - }, - - set label(newLabel) - { - console.assert(newLabel); - if (!newLabel) - return; - - this._labelElement.textContent = newLabel; - } -}; - -WebInspector.ActivateButtonToolbarItem.prototype.__proto__ = WebInspector.ActivateButtonNavigationItem.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ApplicationCacheDetailsSidebarPanel.js b/Source/WebInspectorUI/UserInterface/ApplicationCacheDetailsSidebarPanel.js deleted file mode 100644 index 40019b1f3..000000000 --- a/Source/WebInspectorUI/UserInterface/ApplicationCacheDetailsSidebarPanel.js +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ApplicationCacheDetailsSidebarPanel = function() { - WebInspector.DetailsSidebarPanel.call(this, "application-cache-details", WebInspector.UIString("Storage"), WebInspector.UIString("Storage"), "Images/NavigationItemStorage.svg"); - - this.element.classList.add(WebInspector.ApplicationCacheDetailsSidebarPanel.StyleClassName); - - this._applicationCacheFrame = null; - - this._locationManifestURLRow = new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("Manifest URL")); - this._locationFrameURLRow = new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("Frame URL")); - - this._locationGroup = new WebInspector.DetailsSectionGroup([this._locationManifestURLRow, this._locationFrameURLRow]); - - this._locationSection = new WebInspector.DetailsSection("application-cache-location", WebInspector.UIString("Location"), [this._locationGroup]); - - this._onlineRow = new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("Online")); - this._statusRow = new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("Status")); - - this._statusGroup = new WebInspector.DetailsSectionGroup([this._onlineRow, this._statusRow]); - - this._statusSection = new WebInspector.DetailsSection("application-cache-status", WebInspector.UIString("Status"), [this._statusGroup]); - - this.element.appendChild(this._locationSection.element); - this.element.appendChild(this._statusSection.element); - - WebInspector.applicationCacheManager.addEventListener(WebInspector.ApplicationCacheManager.Event.NetworkStateUpdated, this._networkStateUpdated, this); - WebInspector.applicationCacheManager.addEventListener(WebInspector.ApplicationCacheManager.Event.FrameManifestStatusChanged, this._frameManifestStatusChanged, this); -}; - -WebInspector.ApplicationCacheDetailsSidebarPanel.StyleClassName = "application-cache"; - -// This needs to be kept in sync with ApplicationCacheManager.js. -WebInspector.ApplicationCacheDetailsSidebarPanel.Status = { - 0: "Uncached", - 1: "Idle", - 2: "Checking", - 3: "Downloading", - 4: "UpdateReady", - 5: "Obsolete" -}; - -WebInspector.ApplicationCacheDetailsSidebarPanel.prototype = { - constructor: WebInspector.ApplicationCacheDetailsSidebarPanel, - - // Public - - inspect: function(objects) - { - // Convert to a single item array if needed. - if (!(objects instanceof Array)) - objects = [objects]; - - var applicationCacheFrameToInspect = null; - - // Iterate over the objects to find a WebInspector.ApplicationCacheFrame to inspect. - for (var i = 0; i < objects.length; ++i) { - if (objects[i] instanceof WebInspector.ApplicationCacheFrame) { - applicationCacheFrameToInspect = objects[i]; - break; - } - } - - this.applicationCacheFrame = applicationCacheFrameToInspect; - - return !!this.applicationCacheFrame; - }, - - get applicationCacheFrame() - { - return this._applicationCacheFrame; - }, - - set applicationCacheFrame(applicationCacheFrame) - { - if (this._applicationCacheFrame === applicationCacheFrame) - return; - - this._applicationCacheFrame = applicationCacheFrame; - - this.needsRefresh(); - }, - - refresh: function() - { - if (!this.applicationCacheFrame) - return; - - this._locationFrameURLRow.value = this.applicationCacheFrame.frame.url; - this._locationManifestURLRow.value = this.applicationCacheFrame.manifest.manifestURL; - - this._refreshOnlineRow(); - this._refreshStatusRow(); - }, - - // Private - - _networkStateUpdated: function(event) - { - if (!this.applicationCacheFrame) - return; - - this._refreshOnlineRow(); - }, - - _frameManifestStatusChanged: function(event) - { - if (!this.applicationCacheFrame) - return; - - console.assert(event.data.frameManifest instanceof WebInspector.ApplicationCacheFrame); - if (event.data.frameManifest !== this.applicationCacheFrame) - return; - - this._refreshStatusRow(); - }, - - _refreshOnlineRow: function() - { - this._onlineRow.value = WebInspector.applicationCacheManager.online ? WebInspector.UIString("Yes") : WebInspector.UIString("No"); - }, - - _refreshStatusRow: function() - { - this._statusRow.value = WebInspector.ApplicationCacheDetailsSidebarPanel.Status[this.applicationCacheFrame.status]; - } -}; - -WebInspector.ApplicationCacheDetailsSidebarPanel.prototype.__proto__ = WebInspector.DetailsSidebarPanel.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ApplicationCacheFrame.js b/Source/WebInspectorUI/UserInterface/ApplicationCacheFrame.js deleted file mode 100644 index 4d75875cd..000000000 --- a/Source/WebInspectorUI/UserInterface/ApplicationCacheFrame.js +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ApplicationCacheFrame = function(frame, manifest, status) -{ - console.assert(frame instanceof WebInspector.Frame); - console.assert(manifest instanceof WebInspector.ApplicationCacheManifest); - - WebInspector.Object.call(this); - - this._frame = frame; - this._manifest = manifest; - this._status = status; -}; - -WebInspector.ApplicationCacheFrame.TypeIdentifier = "application-cache-frame"; -WebInspector.ApplicationCacheFrame.FrameURLCookieKey = "application-cache-frame-url"; -WebInspector.ApplicationCacheFrame.ManifestURLCookieKey = "application-cache-frame-manifest-url"; - -WebInspector.ApplicationCacheFrame.prototype = { - constructor: WebInspector.ApplicationCacheFrame, - - // Public - - get frame() - { - return this._frame; - }, - - get manifest() - { - return this._manifest; - }, - - get status() - { - return this._status; - }, - - set status(status) - { - this._status = status; - }, - - saveIdentityToCookie: function(cookie) - { - cookie[WebInspector.ApplicationCacheFrame.FrameURLCookieKey] = this.frame.url; - cookie[WebInspector.ApplicationCacheFrame.ManifestURLCookieKey] = this.manifest.manifestURL; - } -}; - -WebInspector.ApplicationCacheFrame.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ApplicationCacheFrameContentView.css b/Source/WebInspectorUI/UserInterface/ApplicationCacheFrameContentView.css deleted file mode 100644 index e10b20b0b..000000000 --- a/Source/WebInspectorUI/UserInterface/ApplicationCacheFrameContentView.css +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.content-view.application-cache-frame > .data-grid { - position: absolute; - top: 0; - left: 0; - right: 0; - bottom: 0; - border: none; -} diff --git a/Source/WebInspectorUI/UserInterface/ApplicationCacheFrameContentView.js b/Source/WebInspectorUI/UserInterface/ApplicationCacheFrameContentView.js deleted file mode 100644 index d2d0e6c91..000000000 --- a/Source/WebInspectorUI/UserInterface/ApplicationCacheFrameContentView.js +++ /dev/null @@ -1,250 +0,0 @@ -/* - * Copyright (C) 2010, 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -/** - * @constructor - * @extends {WebInspector.View} - */ -WebInspector.ApplicationCacheFrameContentView = function(representedObject) -{ - console.assert(representedObject instanceof WebInspector.ApplicationCacheFrame); - - WebInspector.ContentView.call(this, representedObject); - - this.element.classList.add(WebInspector.ApplicationCacheFrameContentView.StyleClassName); - - this.element.classList.add("storage-view"); - this.element.classList.add("table"); - - this._frame = representedObject.frame; - - this._emptyView = WebInspector.createMessageTextView(WebInspector.UIString("No Application Cache information available"), false); - this._emptyView.classList.add("hidden"); - this.element.appendChild(this._emptyView); - - this._markDirty(); - - var status = representedObject.status; - this.updateStatus(status); - - WebInspector.applicationCacheManager.addEventListener(WebInspector.ApplicationCacheManager.Event.FrameManifestStatusChanged, this._updateStatus, this); -} - -WebInspector.ApplicationCacheFrameContentView.StyleClassName = "application-cache-frame"; - -WebInspector.ApplicationCacheFrameContentView.prototype = { - constructor: WebInspector.ApplicationCacheFrameContentView, - - shown: function() - { - this._maybeUpdate(); - }, - - closed: function() - { - WebInspector.applicationCacheManager.removeEventListener(WebInspector.ApplicationCacheManager.Event.FrameManifestStatusChanged, this._updateStatus, this); - }, - - updateLayout: function() - { - if (this.dataGrid) - this.dataGrid.updateLayout(); - }, - - saveToCookie: function(cookie) - { - cookie.type = WebInspector.ContentViewCookieType.ApplicationCache; - cookie.frame = this.representedObject.frame.url; - cookie.manifest = this.representedObject.manifest.manifestURL; - }, - - get scrollableElements() - { - if (!this._dataGrid) - return []; - return [this._dataGrid.scrollContainer]; - }, - - _maybeUpdate: function() - { - if (!this.visible || !this._viewDirty) - return; - - this._update(); - this._viewDirty = false; - }, - - _markDirty: function() - { - this._viewDirty = true; - }, - - _updateStatus: function(event) - { - var frameManifest = event.data.frameManifest; - if (frameManifest !== this.representedObject) - return; - - console.assert(frameManifest instanceof WebInspector.ApplicationCacheFrame); - - this.updateStatus(frameManifest.status); - }, - - /** - * @param {number} status - */ - updateStatus: function(status) - { - var oldStatus = this._status; - this._status = status; - - if (this.visible && this._status === WebInspector.ApplicationCacheManager.Status.Idle && (oldStatus === WebInspector.ApplicationCacheManager.Status.UpdateReady || !this._resources)) - this._markDirty(); - - this._maybeUpdate(); - }, - - _update: function() - { - WebInspector.applicationCacheManager.requestApplicationCache(this._frame, this._updateCallback.bind(this)); - }, - - /** - * @param {Object} applicationCache - */ - _updateCallback: function(applicationCache) - { - if (!applicationCache || !applicationCache.manifestURL) { - delete this._manifest; - delete this._creationTime; - delete this._updateTime; - delete this._size; - delete this._resources; - - this._emptyView.classList.remove("hidden"); - - if (this._dataGrid) - this._dataGrid.element.classList.add("hidden"); - return; - } - - // FIXME: are these variables needed anywhere else? - this._manifest = applicationCache.manifestURL; - this._creationTime = applicationCache.creationTime; - this._updateTime = applicationCache.updateTime; - this._size = applicationCache.size; - this._resources = applicationCache.resources; - - if (!this._dataGrid) - this._createDataGrid(); - - this._populateDataGrid(); - this._dataGrid.autoSizeColumns(20, 80); - this._dataGrid.element.classList.remove("hidden"); - - this._emptyView.classList.add("hidden"); - }, - - _createDataGrid: function() - { - var columns = { 0: {}, 1: {}, 2: {} }; - columns[0].title = WebInspector.UIString("Resource"); - columns[0].sort = "ascending"; - columns[0].sortable = true; - columns[1].title = WebInspector.UIString("Type"); - columns[1].sortable = true; - columns[2].title = WebInspector.UIString("Size"); - columns[2].aligned = "right"; - columns[2].sortable = true; - this._dataGrid = new WebInspector.DataGrid(columns); - this.element.appendChild(this._dataGrid.element); - this._dataGrid.updateLayout(); - this._dataGrid.addEventListener(WebInspector.DataGrid.Event.SortChanged, this._populateDataGrid, this); - }, - - _populateDataGrid: function() - { - var selectedResource = this._dataGrid.selectedNode ? this._dataGrid.selectedNode.resource : null; - var sortDirection = this._dataGrid.sortOrder === "ascending" ? 1 : -1; - - function numberCompare(field, resource1, resource2) - { - return sortDirection * (resource1[field] - resource2[field]); - } - function localeCompare(field, resource1, resource2) - { - return sortDirection * (resource1[field] + "").localeCompare(resource2[field] + ""); - } - - var comparator; - switch (parseInt(this._dataGrid.sortColumnIdentifier, 10)) { - case 0: comparator = localeCompare.bind(this, "url"); break; - case 1: comparator = localeCompare.bind(this, "type"); break; - case 2: comparator = numberCompare.bind(this, "size"); break; - default: localeCompare.bind(this, "resource"); // FIXME: comparator = ? - } - - this._resources.sort(comparator); - this._dataGrid.removeChildren(); - - var nodeToSelect; - for (var i = 0; i < this._resources.length; ++i) { - var data = {}; - var resource = this._resources[i]; - data[0] = resource.url; - data[1] = resource.type; - data[2] = Number.bytesToString(resource.size); - var node = new WebInspector.DataGridNode(data); - node.resource = resource; - node.selectable = true; - this._dataGrid.appendChild(node); - if (resource === selectedResource) { - nodeToSelect = node; - nodeToSelect.selected = true; - } - } - - if (!nodeToSelect && this._dataGrid.children.length) - this._dataGrid.children[0].selected = true; - }, - - _deleteButtonClicked: function(event) - { - if (!this._dataGrid || !this._dataGrid.selectedNode) - return; - - // FIXME: Delete Button semantics are not yet defined. (Delete a single, or all?) - this._deleteCallback(this._dataGrid.selectedNode); - }, - - _deleteCallback: function(node) - { - // FIXME: Should we delete a single (selected) resource or all resources? - // InspectorBackend.deleteCachedResource(...) - // this._update(); - } -} - -WebInspector.ApplicationCacheFrameContentView.prototype.__proto__ = WebInspector.ContentView.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ApplicationCacheFrameTreeElement.js b/Source/WebInspectorUI/UserInterface/ApplicationCacheFrameTreeElement.js deleted file mode 100644 index 5907508a7..000000000 --- a/Source/WebInspectorUI/UserInterface/ApplicationCacheFrameTreeElement.js +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ApplicationCacheFrameTreeElement = function(representedObject) -{ - console.assert(representedObject instanceof WebInspector.ApplicationCacheFrame); - - WebInspector.GeneralTreeElement.call(this, WebInspector.ApplicationCacheFrameTreeElement.StyleClassName, "", "", representedObject, false); - - this.small = true; - - this.updateTitles(); -}; - -WebInspector.ApplicationCacheFrameTreeElement.StyleClassName = "application-cache-frame"; - -WebInspector.ApplicationCacheFrameTreeElement.prototype = { - constructor: WebInspector.ApplicationCacheFrameTreeElement, - - updateTitles: function() - { - var url = this.representedObject.frame.url; - var parsedURL = parseURL(url); - - this.mainTitle = WebInspector.displayNameForURL(url, parsedURL); - - // Show the host as the subtitle only if it doesn't match the subtitle of the manifest tree element, - // and it doesn't match the mainTitle. - var subtitle = WebInspector.displayNameForHost(parsedURL.host); - - // FIXME: This is bad layering. We should not be calling a global object to get this. - var manifestTreeElement = WebInspector.resourceSidebarPanel.treeElementForRepresentedObject(this.representedObject.manifest); - - var subtitleIsDuplicate = subtitle === this._mainTitle || subtitle === manifestTreeElement.subtitle; - this.subtitle = subtitleIsDuplicate ? null : subtitle; - } -}; - -WebInspector.ApplicationCacheFrameTreeElement.prototype.__proto__ = WebInspector.GeneralTreeElement.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ApplicationCacheIcons.css b/Source/WebInspectorUI/UserInterface/ApplicationCacheIcons.css deleted file mode 100644 index a54973c89..000000000 --- a/Source/WebInspectorUI/UserInterface/ApplicationCacheIcons.css +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.application-cache-manifest .icon { - content: -webkit-image-set(url(Images/ApplicationCacheManifest.png) 1x, url(Images/ApplicationCacheManifest@2x.png) 2x); -} - -.application-cache-frame .icon { - content: -webkit-image-set(url(Images/ApplicationCache.png) 1x, url(Images/ApplicationCache@2x.png) 2x); -} diff --git a/Source/WebInspectorUI/UserInterface/ApplicationCacheManager.js b/Source/WebInspectorUI/UserInterface/ApplicationCacheManager.js deleted file mode 100644 index 523d8511f..000000000 --- a/Source/WebInspectorUI/UserInterface/ApplicationCacheManager.js +++ /dev/null @@ -1,198 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ApplicationCacheManager = function() -{ - WebInspector.Object.call(this); - - if (window.ApplicationCacheAgent) - ApplicationCacheAgent.enable(); - - WebInspector.Frame.addEventListener(WebInspector.Frame.Event.MainResourceDidChange, this._mainResourceDidChange, this); - WebInspector.Frame.addEventListener(WebInspector.Frame.Event.ChildFrameWasRemoved, this._childFrameWasRemoved, this); - - this._online = true; - - this.initialize(); -}; - -WebInspector.ApplicationCacheManager.Event = { - Cleared: "application-cache-manager-cleared", - FrameManifestAdded: "application-cache-manager-frame-manifest-added", - FrameManifestRemoved: "application-cache-manager-frame-manifest-removed", - FrameManifestStatusChanged: "application-cache-manager-frame-manifest-status-changed", - NetworkStateUpdated: "application-cache-manager-network-state-updated" -}; - -WebInspector.ApplicationCacheManager.Status = { - Uncached: 0, - Idle: 1, - Checking: 2, - Downloading: 3, - UpdateReady: 4, - Obsolete: 5 -}; - -WebInspector.ApplicationCacheManager.prototype = { - constructor: WebInspector.ApplicationCacheManager, - - // Public - - initialize: function() - { - this._applicationCacheObjects = []; - - if (window.ApplicationCacheAgent) - ApplicationCacheAgent.getFramesWithManifests(this._framesWithManifestsLoaded.bind(this)); - }, - - networkStateUpdated: function(isNowOnline) - { - this._online = isNowOnline; - - this.dispatchEventToListeners(WebInspector.ApplicationCacheManager.Event.NetworkStateUpdated, {online: this._online}); - }, - - get online() - { - return this._online; - }, - - applicationCacheStatusUpdated: function(frameId, manifestURL, status) - { - var frame = WebInspector.frameResourceManager.frameForIdentifier(frameId); - if (!frame) - return; - - this._frameManifestUpdated(frame, manifestURL, status); - }, - - requestApplicationCache: function(frame, callback) - { - function callbackWrapper(error, applicationCache) - { - if (error) { - callback(null); - return; - } - - callback(applicationCache); - } - - ApplicationCacheAgent.getApplicationCacheForFrame(frame.id, callbackWrapper); - }, - - // Private - - _mainResourceDidChange: function(event) - { - console.assert(event.target instanceof WebInspector.Frame); - - if (event.target.isMainFrame()) { - // If we are dealing with the main frame, we want to clear our list of objects, because we are navigating to a new page. - this.initialize(); - - this.dispatchEventToListeners(WebInspector.ApplicationCacheManager.Event.Cleared); - - return; - } - - ApplicationCacheAgent.getManifestForFrame(event.target.id, this._manifestForFrameLoaded.bind(this, event.target.id)); - }, - - _childFrameWasRemoved: function(event) - { - this._frameManifestRemoved(event.data.childFrame); - }, - - _manifestForFrameLoaded: function(frameId, error, manifestURL) - { - if (error) - return; - - var frame = WebInspector.frameResourceManager.frameForIdentifier(frameId); - if (!frame) - return; - - if (!manifestURL) - this._frameManifestRemoved(frame); - }, - - _framesWithManifestsLoaded: function(error, framesWithManifests) - { - if (error) - return; - - for (var i = 0; i < framesWithManifests.length; ++i) { - var frame = WebInspector.frameResourceManager.frameForIdentifier(framesWithManifests[i].frameId); - if (!frame) - continue; - - this._frameManifestUpdated(frame, framesWithManifests[i].manifestURL, framesWithManifests[i].status); - } - }, - - _frameManifestUpdated: function(frame, manifestURL, status) - { - if (status === WebInspector.ApplicationCacheManager.Status.Uncached) { - this._frameManifestRemoved(frame); - return; - } - - if (!manifestURL) - return; - - var manifestFrame = this._applicationCacheObjects[frame.id]; - if (manifestFrame && manifestURL !== manifestFrame.manifest.manifestURL) - this._frameManifestRemoved(frame); - - var oldStatus = manifestFrame ? manifestFrame.status : -1; - var statusChanged = manifestFrame && status !== oldStatus; - if (manifestFrame) - manifestFrame.status = status; - - if (!this._applicationCacheObjects[frame.id]) { - var cacheManifest = new WebInspector.ApplicationCacheManifest(manifestURL); - this._applicationCacheObjects[frame.id] = new WebInspector.ApplicationCacheFrame(frame, cacheManifest, status); - - this.dispatchEventToListeners(WebInspector.ApplicationCacheManager.Event.FrameManifestAdded, {frameManifest: this._applicationCacheObjects[frame.id]}); - } - - if (statusChanged) - this.dispatchEventToListeners(WebInspector.ApplicationCacheManager.Event.FrameManifestStatusChanged, {frameManifest: this._applicationCacheObjects[frame.id]}); - }, - - _frameManifestRemoved: function(frame) - { - if (!this._applicationCacheObjects[frame.id]) - return; - - delete this._applicationCacheObjects[frame.id]; - - this.dispatchEventToListeners(WebInspector.ApplicationCacheManager.Event.FrameManifestRemoved, {frame: frame}); - } -}; - -WebInspector.ApplicationCacheManager.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ApplicationCacheManifest.js b/Source/WebInspectorUI/UserInterface/ApplicationCacheManifest.js deleted file mode 100644 index 9145899f4..000000000 --- a/Source/WebInspectorUI/UserInterface/ApplicationCacheManifest.js +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ApplicationCacheManifest = function(manifestURL) -{ - WebInspector.Object.call(this); - - this._manifestURL = manifestURL; -}; - -WebInspector.ApplicationCacheManifest.prototype = { - constructor: WebInspector.ApplicationCacheManifest, - - get manifestURL() - { - return this._manifestURL; - } -}; - -WebInspector.ApplicationCacheManifest.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ApplicationCacheManifestTreeElement.js b/Source/WebInspectorUI/UserInterface/ApplicationCacheManifestTreeElement.js deleted file mode 100644 index 2d64b6dbe..000000000 --- a/Source/WebInspectorUI/UserInterface/ApplicationCacheManifestTreeElement.js +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ApplicationCacheManifestTreeElement = function(representedObject) -{ - console.assert(representedObject instanceof WebInspector.ApplicationCacheManifest); - - WebInspector.StorageTreeElement.call(this, WebInspector.ApplicationCacheManifestTreeElement.StyleClassName, "", representedObject); -}; - -WebInspector.ApplicationCacheManifestTreeElement.StyleClassName = "application-cache-manifest"; - -WebInspector.ApplicationCacheManifestTreeElement.prototype = { - constructor: WebInspector.ApplicationCacheManifestTreeElement, - - // Public - - get name() - { - if (!this._name) - this._generateTitles(); - - return this._name; - }, - - get secondaryName() - { - if (!this._secondaryName) - this._generateTitles(); - - return this._secondaryName; - }, - - get categoryName() - { - return WebInspector.UIString("Application Cache"); - }, - - _generateTitles: function() - { - var parsedURL = parseURL(this.representedObject.manifestURL); - - // Prefer the last path component, with a fallback for the host as the main title. - this._name = WebInspector.displayNameForURL(this.representedObject.manifestURL, parsedURL); - - // Show the host as the subtitle. - var secondaryName = WebInspector.displayNameForHost(parsedURL.host); - this._secondaryName = this._name !== secondaryName ? secondaryName : null; - } -}; - -WebInspector.ApplicationCacheManifestTreeElement.prototype.__proto__ = WebInspector.StorageTreeElement.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ApplicationCacheObserver.js b/Source/WebInspectorUI/UserInterface/ApplicationCacheObserver.js deleted file mode 100644 index e48df8bfb..000000000 --- a/Source/WebInspectorUI/UserInterface/ApplicationCacheObserver.js +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ApplicationCacheObserver = function() -{ - WebInspector.Object.call(this); -}; - -WebInspector.ApplicationCacheObserver.prototype = { - constructor: WebInspector.ApplicationCacheObserver, - - // Events defined by the "ApplicationCache" domain. - - applicationCacheStatusUpdated: function(frameId, manifestURL, status) - { - WebInspector.applicationCacheManager.applicationCacheStatusUpdated(frameId, manifestURL, status); - }, - - networkStateUpdated: function(isNowOnline) - { - WebInspector.applicationCacheManager.networkStateUpdated(isNowOnline); - } -}; - -WebInspector.ApplicationCacheObserver.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/BackForwardEntry.js b/Source/WebInspectorUI/UserInterface/BackForwardEntry.js deleted file mode 100644 index 94899bc44..000000000 --- a/Source/WebInspectorUI/UserInterface/BackForwardEntry.js +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright (C) 2013 University of Washington. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS - * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A - * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.BackForwardEntry = function(contentView, cookie) -{ - WebInspector.Object.call(this); - this._contentView = contentView; - // Cookies are compared with Object.shallowEqual, so should not store objects or arrays. - this._cookie = cookie || {}; - this._scrollPositions = []; - - contentView.saveToCookie(this._cookie); -}; - -WebInspector.BackForwardEntry.prototype = { - constructor: WebInspector.BackForwardEntry, - __proto__: WebInspector.Object.prototype, - - // Public - - get contentView() - { - return this._contentView; - }, - - get cookie() - { - // Cookies are immutable; they represent a specific navigation action. - return Object.shallowCopy(this._cookie); - }, - - prepareToShow: function() - { - this._restoreFromCookie(); - - this.contentView.visible = true; - this.contentView.shown(); - this.contentView.updateLayout(); - }, - - prepareToHide: function() - { - this.contentView.visible = false; - this.contentView.hidden(); - - this._saveScrollPositions(); - }, - - // Private - - _restoreFromCookie: function() - { - this._restoreScrollPositions(); - this.contentView.restoreFromCookie(this.cookie); - }, - - _restoreScrollPositions: function() - { - // If no scroll positions are saved, do nothing. - if (!this._scrollPositions.length) - return; - - var scrollableElements = this.contentView.scrollableElements || []; - console.assert(this._scrollPositions.length === scrollableElements.length); - - for (var i = 0; i < scrollableElements.length; ++i) { - var position = this._scrollPositions[i]; - var element = scrollableElements[i]; - if (!element) - continue; - - // Restore the top scroll position by either scrolling to the bottom or to the saved position. - element.scrollTop = position.isScrolledToBottom ? element.scrollHeight : position.scrollTop; - - // Don't restore the left scroll position when scrolled to the bottom. This way the when content changes - // the user won't be left in a weird horizontal position. - element.scrollLeft = position.isScrolledToBottom ? 0 : position.scrollLeft; - } - }, - - _saveScrollPositions: function() - { - var scrollableElements = this.contentView.scrollableElements || []; - var scrollPositions = []; - for (var i = 0; i < scrollableElements.length; ++i) { - var element = scrollableElements[i]; - if (!element) - continue; - - var position = { scrollTop: element.scrollTop, scrollLeft: element.scrollLeft }; - if (this.contentView.shouldKeepElementsScrolledToBottom) - position.isScrolledToBottom = element.isScrolledToBottom(); - - scrollPositions.push(position); - } - - this._scrollPositions = scrollPositions; - } -}; diff --git a/Source/WebInspectorUI/UserInterface/Base/DOMUtilities.js b/Source/WebInspectorUI/UserInterface/Base/DOMUtilities.js new file mode 100644 index 000000000..ba423aa31 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Base/DOMUtilities.js @@ -0,0 +1,314 @@ +/* + * Copyright (C) 2011 Google Inc. All rights reserved. + * Copyright (C) 2007, 2008, 2013 Apple Inc. All rights reserved. + * Copyright (C) 2008 Matt Lilek + * Copyright (C) 2009 Joseph Pecoraro + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Apple Inc. ("Apple") nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.roleSelectorForNode = function(node) +{ + // This is proposed syntax for CSS 4 computed role selector :role(foo) and subject to change. + // See http://lists.w3.org/Archives/Public/www-style/2013Jul/0104.html + var title = ""; + var role = node.computedRole(); + if (role) + title = ":role(" + role + ")"; + return title; +}; + +WebInspector.linkifyAccessibilityNodeReference = function(node) +{ + if (!node) + return null; + // Same as linkifyNodeReference except the link text has the classnames removed... + // ...for list brevity, and both text and title have roleSelectorForNode appended. + var link = WebInspector.linkifyNodeReference(node); + var tagIdSelector = link.title; + var classSelectorIndex = tagIdSelector.indexOf("."); + if (classSelectorIndex > -1) + tagIdSelector = tagIdSelector.substring(0, classSelectorIndex); + var roleSelector = WebInspector.roleSelectorForNode(node); + link.textContent = tagIdSelector + roleSelector; + link.title += roleSelector; + return link; +}; + +WebInspector.linkifyNodeReference = function(node, maxLength) +{ + let displayName = node.displayName; + if (!isNaN(maxLength)) + displayName = displayName.truncate(maxLength); + + let link = document.createElement("span"); + link.append(displayName); + link.setAttribute("role", "link"); + + link.title = displayName; + + let nodeType = node.nodeType(); + if ((nodeType !== Node.DOCUMENT_NODE || node.parentNode) && nodeType !== Node.TEXT_NODE) + link.className = "node-link"; + + link.addEventListener("click", WebInspector.domTreeManager.inspectElement.bind(WebInspector.domTreeManager, node.id)); + link.addEventListener("mouseover", WebInspector.domTreeManager.highlightDOMNode.bind(WebInspector.domTreeManager, node.id, "all")); + link.addEventListener("mouseout", WebInspector.domTreeManager.hideDOMNodeHighlight.bind(WebInspector.domTreeManager)); + + return link; +}; + +function createSVGElement(tagName) +{ + return document.createElementNS("http://www.w3.org/2000/svg", tagName); +} + +WebInspector.cssPath = function(node) +{ + console.assert(node instanceof WebInspector.DOMNode, "Expected a DOMNode."); + if (node.nodeType() !== Node.ELEMENT_NODE) + return ""; + + let suffix = ""; + if (node.isPseudoElement()) { + suffix = "::" + node.pseudoType(); + node = node.parentNode; + } + + let components = []; + while (node) { + let component = WebInspector.cssPathComponent(node); + if (!component) + break; + components.push(component); + if (component.done) + break; + node = node.parentNode; + } + + components.reverse(); + return components.map((x) => x.value).join(" > ") + suffix; +}; + +WebInspector.cssPathComponent = function(node) +{ + console.assert(node instanceof WebInspector.DOMNode, "Expected a DOMNode."); + console.assert(!node.isPseudoElement()); + if (node.nodeType() !== Node.ELEMENT_NODE) + return null; + + let nodeName = node.nodeNameInCorrectCase(); + let lowerNodeName = node.nodeName().toLowerCase(); + + // html, head, and body are unique nodes. + if (lowerNodeName === "body" || lowerNodeName === "head" || lowerNodeName === "html") + return {value: nodeName, done: true}; + + // #id is unique. + let id = node.getAttribute("id"); + if (id) + return {value: node.escapedIdSelector, done: true}; + + // Root node does not have siblings. + if (!node.parentNode || node.parentNode.nodeType() === Node.DOCUMENT_NODE) + return {value: nodeName, done: true}; + + // Find uniqueness among siblings. + // - look for a unique className + // - look for a unique tagName + // - fallback to nth-child() + + function classNames(node) { + let classAttribute = node.getAttribute("class"); + return classAttribute ? classAttribute.trim().split(/\s+/) : []; + } + + let nthChildIndex = -1; + let hasUniqueTagName = true; + let uniqueClasses = new Set(classNames(node)); + + let siblings = node.parentNode.children; + let elementIndex = 0; + for (let sibling of siblings) { + if (sibling.nodeType() !== Node.ELEMENT_NODE) + continue; + + elementIndex++; + if (sibling === node) { + nthChildIndex = elementIndex; + continue; + } + + if (sibling.nodeNameInCorrectCase() === nodeName) + hasUniqueTagName = false; + + if (uniqueClasses.size) { + let siblingClassNames = classNames(sibling); + for (let className of siblingClassNames) + uniqueClasses.delete(className); + } + } + + let selector = nodeName; + if (lowerNodeName === "input" && node.getAttribute("type") && !uniqueClasses.size) + selector += `[type="${node.getAttribute("type")}"]`; + if (!hasUniqueTagName) { + if (uniqueClasses.size) + selector += node.escapedClassSelector; + else + selector += `:nth-child(${nthChildIndex})`; + } + + return {value: selector, done: false}; +}; + +WebInspector.xpath = function(node) +{ + console.assert(node instanceof WebInspector.DOMNode, "Expected a DOMNode."); + + if (node.nodeType() === Node.DOCUMENT_NODE) + return "/"; + + let components = []; + while (node) { + let component = WebInspector.xpathComponent(node); + if (!component) + break; + components.push(component); + if (component.done) + break; + node = node.parentNode; + } + + components.reverse(); + + let prefix = components.length && components[0].done ? "" : "/"; + return prefix + components.map((x) => x.value).join("/"); +}; + +WebInspector.xpathComponent = function(node) +{ + console.assert(node instanceof WebInspector.DOMNode, "Expected a DOMNode."); + + let index = WebInspector.xpathIndex(node); + if (index === -1) + return null; + + let value; + + switch (node.nodeType()) { + case Node.DOCUMENT_NODE: + return {value: "", done: true}; + case Node.ELEMENT_NODE: + var id = node.getAttribute("id"); + if (id) + return {value: `//*[@id="${id}"]`, done: true}; + value = node.localName(); + break; + case Node.ATTRIBUTE_NODE: + value = `@${node.nodeName()}`; + break; + case Node.TEXT_NODE: + case Node.CDATA_SECTION_NODE: + value = "text()"; + break; + case Node.COMMENT_NODE: + value = "comment()"; + break; + case Node.PROCESSING_INSTRUCTION_NODE: + value = "processing-instruction()"; + break; + default: + value = ""; + break; + } + + if (index > 0) + value += `[${index}]`; + + return {value, done: false}; +}; + +WebInspector.xpathIndex = function(node) +{ + // Root node. + if (!node.parentNode) + return 0; + + // No siblings. + let siblings = node.parentNode.children; + if (siblings.length <= 1) + return 0; + + // Find uniqueness among siblings. + // - look for a unique localName + // - fallback to index + + function isSimiliarNode(a, b) { + if (a === b) + return true; + + let aType = a.nodeType(); + let bType = b.nodeType(); + + if (aType === Node.ELEMENT_NODE && bType === Node.ELEMENT_NODE) + return a.localName() === b.localName(); + + // XPath CDATA and text() are the same. + if (aType === Node.CDATA_SECTION_NODE) + return aType === Node.TEXT_NODE; + if (bType === Node.CDATA_SECTION_NODE) + return bType === Node.TEXT_NODE; + + return aType === bType; + } + + let unique = true; + let xPathIndex = -1; + + let xPathIndexCounter = 1; // XPath indices start at 1. + for (let sibling of siblings) { + if (!isSimiliarNode(node, sibling)) + continue; + + if (node === sibling) { + xPathIndex = xPathIndexCounter; + if (!unique) + return xPathIndex; + } else { + unique = false; + if (xPathIndex !== -1) + return xPathIndex; + } + + xPathIndexCounter++; + } + + if (unique) + return 0; + + console.assert(xPathIndex > 0, "Should have found the node."); + return xPathIndex; +}; diff --git a/Source/WebInspectorUI/UserInterface/Base/EventListener.js b/Source/WebInspectorUI/UserInterface/Base/EventListener.js new file mode 100644 index 000000000..b009f887d --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Base/EventListener.js @@ -0,0 +1,90 @@ +/* + * Copyright (C) 2014, 2015 Apple Inc. All rights reserved. + * Copyright (C) 2013, 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.EventListener = class EventListener +{ + constructor(thisObject, fireOnce) + { + this._thisObject = thisObject; + this._emitter = null; + this._callback = null; + this._fireOnce = fireOnce; + } + + // Public + + connect(emitter, type, callback, usesCapture) + { + console.assert(!this._emitter && !this._callback, "EventListener already bound to a callback.", this); + console.assert(callback, "Missing callback for event: " + type); + console.assert(emitter, "Missing event emitter for event: " + type); + var emitterIsValid = emitter && (emitter instanceof WebInspector.Object || emitter instanceof Node || (typeof emitter.addEventListener === "function")); + console.assert(emitterIsValid, "Event emitter ", emitter, " (type:" + type + ") is null or does not implement Node or WebInspector.Object!"); + + if (!emitterIsValid || !type || !callback) + return; + + this._emitter = emitter; + this._type = type; + this._usesCapture = !!usesCapture; + + if (emitter instanceof Node) + callback = callback.bind(this._thisObject); + + if (this._fireOnce) { + var listener = this; + this._callback = function() { + listener.disconnect(); + callback.apply(this, arguments); + }; + } else + this._callback = callback; + + if (this._emitter instanceof Node) + this._emitter.addEventListener(this._type, this._callback, this._usesCapture); + else + this._emitter.addEventListener(this._type, this._callback, this._thisObject); + } + + disconnect() + { + console.assert(this._emitter && this._callback, "EventListener is not bound to a callback.", this); + + if (!this._emitter || !this._callback) + return; + + if (this._emitter instanceof Node) + this._emitter.removeEventListener(this._type, this._callback, this._usesCapture); + else + this._emitter.removeEventListener(this._type, this._callback, this._thisObject); + + if (this._fireOnce) + delete this._thisObject; + delete this._emitter; + delete this._type; + delete this._callback; + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Base/EventListenerSet.js b/Source/WebInspectorUI/UserInterface/Base/EventListenerSet.js new file mode 100644 index 000000000..bc392c430 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Base/EventListenerSet.js @@ -0,0 +1,91 @@ +/* + * Copyright (C) 2014, 2015 Apple Inc. All rights reserved. + * Copyright (C) 2013, 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +// This class supports adding and removing many listeners at once. +// Add DOM or Inspector event listeners to the set using `register()`. +// Use `install()` and `uninstall()` to enable or disable all listeners +// in the set at once. + +WebInspector.EventListenerSet = class EventListenerSet +{ + constructor(defaultThisObject, name) + { + this.name = name; + this._defaultThisObject = defaultThisObject; + + this._listeners = []; + this._installed = false; + } + + // Public + + register(emitter, type, callback, thisObject, usesCapture) + { + console.assert(callback, "Missing callback for event: " + type); + console.assert(type, "Tried to register listener for unknown event: " + type); + var emitterIsValid = emitter && (emitter instanceof WebInspector.Object || emitter instanceof Node || (typeof emitter.addEventListener === "function")); + console.assert(emitterIsValid, "Event emitter ", emitter, " (type:" + type + ") is null or does not implement Node or WebInspector.Object!"); + + if (!emitterIsValid || !type || !callback) + return; + + this._listeners.push({listener: new WebInspector.EventListener(thisObject || this._defaultThisObject), emitter, type, callback, usesCapture}); + } + + unregister() + { + if (this._installed) + this.uninstall(); + this._listeners = []; + } + + install() + { + console.assert(!this._installed, "Already installed listener group: " + this.name); + if (this._installed) + return; + + this._installed = true; + + for (var data of this._listeners) + data.listener.connect(data.emitter, data.type, data.callback, data.usesCapture); + } + + uninstall(unregisterListeners) + { + console.assert(this._installed, "Trying to uninstall listener group " + this.name + ", but it isn't installed."); + if (!this._installed) + return; + + this._installed = false; + + for (var data of this._listeners) + data.listener.disconnect(); + + if (unregisterListeners) + this._listeners = []; + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Base/ImageUtilities.js b/Source/WebInspectorUI/UserInterface/Base/ImageUtilities.js new file mode 100644 index 000000000..f04831881 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Base/ImageUtilities.js @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2013, 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +function useSVGSymbol(url, className, title) +{ + const svgNamespace = "http://www.w3.org/2000/svg"; + const xlinkNamespace = "http://www.w3.org/1999/xlink"; + + let svgElement = document.createElementNS(svgNamespace, "svg"); + svgElement.style.width = "100%"; + svgElement.style.height = "100%"; + + // URL must contain a fragment reference to a graphical element, like a symbol. If none is given + // append #root which all of our SVGs have on the top level element. + if (!url.includes("#")) + url += "#root"; + + let useElement = document.createElementNS(svgNamespace, "use"); + useElement.setAttributeNS(xlinkNamespace, "xlink:href", url); + svgElement.appendChild(useElement); + + let wrapper = document.createElement("div"); + wrapper.appendChild(svgElement); + + if (className) + wrapper.className = className; + if (title) + wrapper.title = title; + + return wrapper; +} diff --git a/Source/WebInspectorUI/UserInterface/Base/InspectorFrontendHostStub.js b/Source/WebInspectorUI/UserInterface/Base/InspectorFrontendHostStub.js new file mode 100644 index 000000000..505e9d4af --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Base/InspectorFrontendHostStub.js @@ -0,0 +1,200 @@ +/* + * Copyright (C) 2009 Google Inc. All rights reserved. + * Copyright (C) 2013 Seokju Kwon (seokju.kwon@gmail.com) + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +if (!window.InspectorFrontendHost) { + WebInspector.InspectorFrontendHostStub = function() + { + }; + + WebInspector.InspectorFrontendHostStub.prototype = { + // Public + + initializeWebSocket: function(url) + { + var socket = new WebSocket(url); + socket.addEventListener("open", socketReady.bind(this)); + + function socketReady() + { + this._socket = socket; + + this._socket.addEventListener("message", function(message) { InspectorBackend.dispatch(message.data); }); + this._socket.addEventListener("error", function(error) { console.error(error); }); + + this._sendPendingMessagesToBackendIfNeeded(); + } + }, + + bringToFront: function() + { + this._windowVisible = true; + }, + + closeWindow: function() + { + this._windowVisible = false; + }, + + userInterfaceLayoutDirection: function() + { + return "ltr"; + }, + + requestSetDockSide: function(side) + { + InspectorFrontendAPI.setDockSide(side); + }, + + setAttachedWindowHeight: function(height) + { + }, + + setAttachedWindowWidth: function(width) + { + }, + + startWindowDrag: function() + { + }, + + moveWindowBy: function(x, y) + { + }, + + loaded: function() + { + }, + + localizedStringsURL: function() + { + return undefined; + }, + + backendCommandsURL: function() + { + return undefined; + }, + + debuggableType: function() + { + return "web"; + }, + + inspectionLevel: function() + { + return 1; + }, + + inspectedURLChanged: function(title) + { + document.title = title; + }, + + copyText: function(text) + { + this._textToCopy = text; + if (!document.execCommand("copy")) + console.error("Clipboard access is denied"); + }, + + killText: function(text, shouldStartNewSequence) + { + }, + + openInNewTab: function(url) + { + window.open(url, "_blank"); + }, + + save: function(url, content, base64Encoded, forceSaveAs) + { + }, + + sendMessageToBackend: function(message) + { + if (!this._socket) { + if (!this._pendingMessages) + this._pendingMessages = []; + this._pendingMessages.push(message); + return; + } + + this._sendPendingMessagesToBackendIfNeeded(); + + this._socket.send(message); + }, + + platform: function() + { + return (navigator.platform.match(/mac|win|linux/i) || ["other"])[0].toLowerCase(); + }, + + beep: function() + { + }, + + showContextMenu: function(event, menuObject) + { + }, + + unbufferedLog: function() + { + console.log.apply(console, arguments); + }, + + setZoomFactor: function(zoom) + { + }, + + zoomFactor: function() + { + return 1; + }, + + // Private + + _sendPendingMessagesToBackendIfNeeded: function() + { + if (!this._pendingMessages) + return; + + for (var i = 0; i < this._pendingMessages.length; ++i) + this._socket.send(this._pendingMessages[i]); + + delete this._pendingMessages; + } + }; + + InspectorFrontendHost = new WebInspector.InspectorFrontendHostStub; + + WebInspector.dontLocalizeUserInterface = true; +} diff --git a/Source/WebInspectorUI/UserInterface/Base/LinkedList.js b/Source/WebInspectorUI/UserInterface/Base/LinkedList.js new file mode 100644 index 000000000..f9978af42 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Base/LinkedList.js @@ -0,0 +1,112 @@ +/* + * Copyright (C) 2016 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +class LinkedList +{ + constructor() + { + this.head = new LinkedListNode; + this.head.next = this.head.prev = this.head; + this.length = 0; + } + + clear() + { + this.head.next = this.head.prev = this.head; + this.length = 0; + } + + get last() + { + return this.head.prev; + } + + push(item) + { + let newNode = new LinkedListNode(item); + let last = this.last; + let head = this.head; + + last.next = newNode; + newNode.next = head; + head.prev = newNode; + newNode.prev = last; + + this.length++; + + return newNode; + } + + remove(node) + { + if (!node) + return false; + + node.prev.next = node.next; + node.next.prev = node.prev; + + this.length--; + return true; + } + + forEach(callback) + { + let node = this.head; + for (let i = 0, length = this.length; i < length; i++) { + node = node.next; + let returnValue = callback(node.value, i); + if (returnValue === false) + return; + } + } + + toArray() + { + let node = this.head; + let i = this.length; + let result = new Array(i); + while (i--) { + node = node.prev; + result[i] = node.value; + } + return result; + } + + toJSON() + { + return this.toArray(); + } +} + + +class LinkedListNode +{ + constructor(value) + { + this.value = value; + this.prev = null; + this.next = null; + } +} diff --git a/Source/WebInspectorUI/UserInterface/Base/ListMultimap.js b/Source/WebInspectorUI/UserInterface/Base/ListMultimap.js new file mode 100644 index 000000000..a415fb68f --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Base/ListMultimap.js @@ -0,0 +1,117 @@ +/* + * Copyright (C) 2016 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +class ListMultimap +{ + constructor() + { + this._insertionOrderedEntries = new LinkedList; + this._keyMap = new Map; + } + + get size() + { + return this._insertionOrderedEntries.length; + } + + add(key, value) + { + let nodeMap = this._keyMap.get(key); + if (!nodeMap) { + nodeMap = new Map; + this._keyMap.set(key, nodeMap); + } + + let node = nodeMap.get(value); + if (!node) { + node = this._insertionOrderedEntries.push([key, value]); + nodeMap.set(value, node); + } + + return this; + } + + delete(key, value) + { + let nodeMap = this._keyMap.get(key); + if (!nodeMap) + return false; + + let node = nodeMap.get(value); + if (!node) + return false; + + nodeMap.delete(value); + this._insertionOrderedEntries.remove(node); + return true; + } + + deleteAll(key) + { + let nodeMap = this._keyMap.get(key); + if (!nodeMap) + return false; + + let list = this._insertionOrderedEntries; + let didDelete = false; + nodeMap.forEach(function(node) { + list.remove(node); + didDelete = true; + }); + + this._keyMap.delete(key); + return didDelete; + } + + has(key, value) + { + let nodeMap = this._keyMap.get(key); + if (!nodeMap) + return false; + + return nodeMap.has(value); + } + + clear() + { + this._keyMap = new Map; + this._insertionOrderedEntries = new LinkedList; + } + + forEach(callback) + { + this._insertionOrderedEntries.forEach(callback); + } + + toArray() + { + return this._insertionOrderedEntries.toArray(); + } + + toJSON() + { + return this.toArray(); + } +} diff --git a/Source/WebInspectorUI/UserInterface/Base/LoadLocalizedStrings.js b/Source/WebInspectorUI/UserInterface/Base/LoadLocalizedStrings.js new file mode 100644 index 000000000..84c6e08fe --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Base/LoadLocalizedStrings.js @@ -0,0 +1,34 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +(function() { + if (WebInspector.dontLocalizeUserInterface) + return; + + var localizedStringsURL = InspectorFrontendHost.localizedStringsURL(); + console.assert(localizedStringsURL); + if (localizedStringsURL) + document.write(""); +})(); diff --git a/Source/WebInspectorUI/UserInterface/Base/MIMETypeUtilities.js b/Source/WebInspectorUI/UserInterface/Base/MIMETypeUtilities.js new file mode 100644 index 000000000..42bced52e --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Base/MIMETypeUtilities.js @@ -0,0 +1,122 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.fileExtensionForURL = function(url) +{ + var lastPathComponent = parseURL(url).lastPathComponent; + if (!lastPathComponent) + return ""; + + var index = lastPathComponent.indexOf("."); + if (index === -1) + return ""; + + return lastPathComponent.substr(index + 1); +}; + +WebInspector.mimeTypeForFileExtension = function(extension) +{ + const extensionToMIMEType = { + // Document types. + "html": "text/html", + "xhtml": "application/xhtml+xml", + "xml": "text/xml", + + // Script types. + "js": "text/javascript", + "json": "application/json", + "clj": "text/x-clojure", + "coffee": "text/x-coffeescript", + "ls": "text/x-livescript", + "ts": "text/typescript", + + // Stylesheet types. + "css": "text/css", + "less": "text/x-less", + "sass": "text/x-sass", + "scss": "text/x-scss", + + // Image types. + "bmp": "image/bmp", + "gif": "image/gif", + "jpeg": "image/jpeg", + "jpg": "image/jpeg", + "pdf": "application/pdf", + "png": "image/png", + "tif": "image/tiff", + "tiff": "image/tiff", + + // Font types and Media types are ignored for now. + + // Miscellaneous types. + "svg": "image/svg+xml", + "txt": "text/plain", + "xsl": "text/xsl" + }; + + return extensionToMIMEType[extension] || null; +}; + +WebInspector.fileExtensionForMIMEType = function(mimeType) +{ + const mimeTypeToExtension = { + // Document types. + "text/html": "html", + "application/xhtml+xml": "xhtml", + "text/xml": "xml", + + // Script types. + "text/javascript": "js", + "application/json": "json", + "text/x-clojure": "clj", + "text/x-coffeescript": "coffee", + "text/x-livescript": "ls", + "text/typescript": "ts", + + // Stylesheet types. + "text/css": "css", + "text/x-less": "less", + "text/x-sass": "sass", + "text/x-scss": "scss", + + // Image types. + "image/bmp": "bmp", + "image/gif": "gif", + "image/jpeg": "jpg", + "application/pdf": "pdf", + "image/png": "png", + "image/tiff": "tiff", + + // Font types and Media types are ignored for now. + + // Miscellaneous types. + "image/svg+xml": "svg", + "text/plain": "txt", + "text/xsl": "xsl", + }; + + let extension = mimeTypeToExtension[mimeType]; + return extension ? `.${extension}` : null; +}; diff --git a/Source/WebInspectorUI/UserInterface/Base/Main.js b/Source/WebInspectorUI/UserInterface/Base/Main.js new file mode 100644 index 000000000..11495f4ee --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Base/Main.js @@ -0,0 +1,2693 @@ +/* + * Copyright (C) 2013-2017 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.ContentViewCookieType = { + ApplicationCache: "application-cache", + CookieStorage: "cookie-storage", + Database: "database", + DatabaseTable: "database-table", + DOMStorage: "dom-storage", + Resource: "resource", // includes Frame too. + Timelines: "timelines" +}; + +WebInspector.DebuggableType = { + Web: "web", + JavaScript: "javascript" +}; + +WebInspector.SelectedSidebarPanelCookieKey = "selected-sidebar-panel"; +WebInspector.TypeIdentifierCookieKey = "represented-object-type"; + +WebInspector.StateRestorationType = { + Load: "state-restoration-load", + Navigation: "state-restoration-navigation", + Delayed: "state-restoration-delayed", +}; + +WebInspector.LayoutDirection = { + System: "system", + LTR: "ltr", + RTL: "rtl", +}; + +WebInspector.loaded = function() +{ + // Initialize WebSocket to communication. + this._initializeWebSocketIfNeeded(); + + this.debuggableType = InspectorFrontendHost.debuggableType() === "web" ? WebInspector.DebuggableType.Web : WebInspector.DebuggableType.JavaScript; + this.hasExtraDomains = false; + + // Register observers for events from the InspectorBackend. + if (InspectorBackend.registerInspectorDispatcher) + InspectorBackend.registerInspectorDispatcher(new WebInspector.InspectorObserver); + if (InspectorBackend.registerPageDispatcher) + InspectorBackend.registerPageDispatcher(new WebInspector.PageObserver); + if (InspectorBackend.registerConsoleDispatcher) + InspectorBackend.registerConsoleDispatcher(new WebInspector.ConsoleObserver); + if (InspectorBackend.registerNetworkDispatcher) + InspectorBackend.registerNetworkDispatcher(new WebInspector.NetworkObserver); + if (InspectorBackend.registerDOMDispatcher) + InspectorBackend.registerDOMDispatcher(new WebInspector.DOMObserver); + if (InspectorBackend.registerDebuggerDispatcher) + InspectorBackend.registerDebuggerDispatcher(new WebInspector.DebuggerObserver); + if (InspectorBackend.registerHeapDispatcher) + InspectorBackend.registerHeapDispatcher(new WebInspector.HeapObserver); + if (InspectorBackend.registerMemoryDispatcher) + InspectorBackend.registerMemoryDispatcher(new WebInspector.MemoryObserver); + if (InspectorBackend.registerDatabaseDispatcher) + InspectorBackend.registerDatabaseDispatcher(new WebInspector.DatabaseObserver); + if (InspectorBackend.registerDOMStorageDispatcher) + InspectorBackend.registerDOMStorageDispatcher(new WebInspector.DOMStorageObserver); + if (InspectorBackend.registerApplicationCacheDispatcher) + InspectorBackend.registerApplicationCacheDispatcher(new WebInspector.ApplicationCacheObserver); + if (InspectorBackend.registerScriptProfilerDispatcher) + InspectorBackend.registerScriptProfilerDispatcher(new WebInspector.ScriptProfilerObserver); + if (InspectorBackend.registerTimelineDispatcher) + InspectorBackend.registerTimelineDispatcher(new WebInspector.TimelineObserver); + if (InspectorBackend.registerCSSDispatcher) + InspectorBackend.registerCSSDispatcher(new WebInspector.CSSObserver); + if (InspectorBackend.registerLayerTreeDispatcher) + InspectorBackend.registerLayerTreeDispatcher(new WebInspector.LayerTreeObserver); + if (InspectorBackend.registerRuntimeDispatcher) + InspectorBackend.registerRuntimeDispatcher(new WebInspector.RuntimeObserver); + if (InspectorBackend.registerWorkerDispatcher) + InspectorBackend.registerWorkerDispatcher(new WebInspector.WorkerObserver); + if (InspectorBackend.registerReplayDispatcher) + InspectorBackend.registerReplayDispatcher(new WebInspector.ReplayObserver); + + // Main backend target. + WebInspector.mainTarget = new WebInspector.MainTarget; + + // Enable agents. + InspectorAgent.enable(); + + // Perform one-time tasks. + WebInspector.CSSCompletions.requestCSSCompletions(); + + // Listen for the ProvisionalLoadStarted event before registering for events so our code gets called before any managers or sidebars. + // This lets us save a state cookie before any managers or sidebars do any resets that would affect state (namely TimelineManager). + WebInspector.Frame.addEventListener(WebInspector.Frame.Event.ProvisionalLoadStarted, this._provisionalLoadStarted, this); + + // Create the singleton managers next, before the user interface elements, so the user interface can register + // as event listeners on these managers. + this.targetManager = new WebInspector.TargetManager; + this.branchManager = new WebInspector.BranchManager; + this.frameResourceManager = new WebInspector.FrameResourceManager; + this.storageManager = new WebInspector.StorageManager; + this.domTreeManager = new WebInspector.DOMTreeManager; + this.cssStyleManager = new WebInspector.CSSStyleManager; + this.logManager = new WebInspector.LogManager; + this.issueManager = new WebInspector.IssueManager; + this.analyzerManager = new WebInspector.AnalyzerManager; + this.runtimeManager = new WebInspector.RuntimeManager; + this.heapManager = new WebInspector.HeapManager; + this.memoryManager = new WebInspector.MemoryManager; + this.applicationCacheManager = new WebInspector.ApplicationCacheManager; + this.timelineManager = new WebInspector.TimelineManager; + this.debuggerManager = new WebInspector.DebuggerManager; + this.sourceMapManager = new WebInspector.SourceMapManager; + this.layerTreeManager = new WebInspector.LayerTreeManager; + this.dashboardManager = new WebInspector.DashboardManager; + this.probeManager = new WebInspector.ProbeManager; + this.workerManager = new WebInspector.WorkerManager; + this.replayManager = new WebInspector.ReplayManager; + + // Enable the Console Agent after creating the singleton managers. + ConsoleAgent.enable(); + + // Tell the backend we are initialized after all our initialization messages have been sent. + setTimeout(function() { + // COMPATIBILITY (iOS 8): Inspector.initialized did not exist yet. + if (InspectorAgent.initialized) + InspectorAgent.initialized(); + }, 0); + + // Register for events. + this.replayManager.addEventListener(WebInspector.ReplayManager.Event.CaptureStarted, this._captureDidStart, this); + this.debuggerManager.addEventListener(WebInspector.DebuggerManager.Event.Paused, this._debuggerDidPause, this); + this.debuggerManager.addEventListener(WebInspector.DebuggerManager.Event.Resumed, this._debuggerDidResume, this); + this.domTreeManager.addEventListener(WebInspector.DOMTreeManager.Event.InspectModeStateChanged, this._inspectModeStateChanged, this); + this.domTreeManager.addEventListener(WebInspector.DOMTreeManager.Event.DOMNodeWasInspected, this._domNodeWasInspected, this); + this.storageManager.addEventListener(WebInspector.StorageManager.Event.DOMStorageObjectWasInspected, this._storageWasInspected, this); + this.storageManager.addEventListener(WebInspector.StorageManager.Event.DatabaseWasInspected, this._storageWasInspected, this); + this.frameResourceManager.addEventListener(WebInspector.FrameResourceManager.Event.MainFrameDidChange, this._mainFrameDidChange, this); + this.frameResourceManager.addEventListener(WebInspector.FrameResourceManager.Event.FrameWasAdded, this._frameWasAdded, this); + + WebInspector.Frame.addEventListener(WebInspector.Frame.Event.MainResourceDidChange, this._mainResourceDidChange, this); + + document.addEventListener("DOMContentLoaded", this.contentLoaded.bind(this)); + + // Create settings. + this._showingSplitConsoleSetting = new WebInspector.Setting("showing-split-console", false); + this._splitConsoleHeightSetting = new WebInspector.Setting("split-console-height", 150); + + this._openTabsSetting = new WebInspector.Setting("open-tab-types", ["elements", "network", "resources", "timeline", "debugger", "storage", "console"]); + this._selectedTabIndexSetting = new WebInspector.Setting("selected-tab-index", 0); + + this.showShadowDOMSetting = new WebInspector.Setting("show-shadow-dom", false); + this.showReplayInterfaceSetting = new WebInspector.Setting("show-web-replay", false); + + // COMPATIBILITY (iOS 8): Page.enableTypeProfiler did not exist. + this.showJavaScriptTypeInformationSetting = new WebInspector.Setting("show-javascript-type-information", false); + this.showJavaScriptTypeInformationSetting.addEventListener(WebInspector.Setting.Event.Changed, this._showJavaScriptTypeInformationSettingChanged, this); + if (this.showJavaScriptTypeInformationSetting.value && window.RuntimeAgent && RuntimeAgent.enableTypeProfiler) + RuntimeAgent.enableTypeProfiler(); + + this.enableControlFlowProfilerSetting = new WebInspector.Setting("enable-control-flow-profiler", false); + this.enableControlFlowProfilerSetting.addEventListener(WebInspector.Setting.Event.Changed, this._enableControlFlowProfilerSettingChanged, this); + if (this.enableControlFlowProfilerSetting.value && window.RuntimeAgent && RuntimeAgent.enableControlFlowProfiler) + RuntimeAgent.enableControlFlowProfiler(); + + // COMPATIBILITY (iOS 8): Page.setShowPaintRects did not exist. + this.showPaintRectsSetting = new WebInspector.Setting("show-paint-rects", false); + if (this.showPaintRectsSetting.value && window.PageAgent && PageAgent.setShowPaintRects) + PageAgent.setShowPaintRects(true); + + this.showPrintStylesSetting = new WebInspector.Setting("show-print-styles", false); + if (this.showPrintStylesSetting.value && window.PageAgent) + PageAgent.setEmulatedMedia("print"); + + this.setZoomFactor(WebInspector.settings.zoomFactor.value); + + this.mouseCoords = { + x: 0, + y: 0 + }; + + this.visible = false; + + this._windowKeydownListeners = []; +}; + +WebInspector.contentLoaded = function() +{ + // If there was an uncaught exception earlier during loading, then + // abort loading more content. We could be in an inconsistent state. + if (window.__uncaughtExceptions) + return; + + // Register for global events. + document.addEventListener("beforecopy", this._beforecopy.bind(this)); + document.addEventListener("copy", this._copy.bind(this)); + + document.addEventListener("click", this._mouseWasClicked.bind(this)); + document.addEventListener("dragover", this._dragOver.bind(this)); + document.addEventListener("focus", WebInspector._focusChanged.bind(this), true); + + window.addEventListener("focus", this._windowFocused.bind(this)); + window.addEventListener("blur", this._windowBlurred.bind(this)); + window.addEventListener("resize", this._windowResized.bind(this)); + window.addEventListener("keydown", this._windowKeyDown.bind(this)); + window.addEventListener("keyup", this._windowKeyUp.bind(this)); + window.addEventListener("mousedown", this._mouseDown.bind(this), true); + window.addEventListener("mousemove", this._mouseMoved.bind(this), true); + window.addEventListener("pagehide", this._pageHidden.bind(this)); + window.addEventListener("contextmenu", this._contextMenuRequested.bind(this)); + + // Add platform style classes so the UI can be tweaked per-platform. + document.body.classList.add(WebInspector.Platform.name + "-platform"); + if (WebInspector.Platform.isNightlyBuild) + document.body.classList.add("nightly-build"); + + if (WebInspector.Platform.name === "mac") { + document.body.classList.add(WebInspector.Platform.version.name); + + if (WebInspector.Platform.version.release >= 11) + document.body.classList.add("latest-mac"); + else + document.body.classList.add("legacy-mac"); + } + + document.body.classList.add(this.debuggableType); + document.body.setAttribute("dir", this.resolvedLayoutDirection()); + + function setTabSize() { + document.body.style.tabSize = WebInspector.settings.tabSize.value; + } + WebInspector.settings.tabSize.addEventListener(WebInspector.Setting.Event.Changed, setTabSize); + setTabSize(); + + function setInvalidCharacterClassName() { + document.body.classList.toggle("show-invalid-characters", WebInspector.settings.showInvalidCharacters.value); + } + WebInspector.settings.showInvalidCharacters.addEventListener(WebInspector.Setting.Event.Changed, setInvalidCharacterClassName); + setInvalidCharacterClassName(); + + function setWhitespaceCharacterClassName() { + document.body.classList.toggle("show-whitespace-characters", WebInspector.settings.showWhitespaceCharacters.value); + } + WebInspector.settings.showWhitespaceCharacters.addEventListener(WebInspector.Setting.Event.Changed, setWhitespaceCharacterClassName); + setWhitespaceCharacterClassName(); + + this.settingsTabContentView = new WebInspector.SettingsTabContentView; + + this._settingsKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, WebInspector.KeyboardShortcut.Key.Comma, this._showSettingsTab.bind(this)); + + // Create the user interface elements. + this.toolbar = new WebInspector.Toolbar(document.getElementById("toolbar"), null, true); + this.toolbar.displayMode = WebInspector.Toolbar.DisplayMode.IconOnly; + this.toolbar.sizeMode = WebInspector.Toolbar.SizeMode.Small; + + this.tabBar = new WebInspector.TabBar(document.getElementById("tab-bar")); + this.tabBar.addEventListener(WebInspector.TabBar.Event.OpenDefaultTab, this._openDefaultTab, this); + + this._contentElement = document.getElementById("content"); + this._contentElement.setAttribute("role", "main"); + this._contentElement.setAttribute("aria-label", WebInspector.UIString("Content")); + + const disableBackForward = true; + const disableFindBanner = false; + this.splitContentBrowser = new WebInspector.ContentBrowser(document.getElementById("split-content-browser"), this, disableBackForward, disableFindBanner); + this.splitContentBrowser.navigationBar.element.addEventListener("mousedown", this._consoleResizerMouseDown.bind(this)); + + this.clearKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, "K", this._clear.bind(this)); + + this.quickConsole = new WebInspector.QuickConsole(document.getElementById("quick-console")); + this.quickConsole.addEventListener(WebInspector.QuickConsole.Event.DidResize, this._quickConsoleDidResize, this); + + this._consoleRepresentedObject = new WebInspector.LogObject; + this._consoleTreeElement = new WebInspector.LogTreeElement(this._consoleRepresentedObject); + this.consoleContentView = WebInspector.splitContentBrowser.contentViewForRepresentedObject(this._consoleRepresentedObject); + this.consoleLogViewController = this.consoleContentView.logViewController; + this.breakpointPopoverController = new WebInspector.BreakpointPopoverController; + + // FIXME: The sidebars should be flipped in RTL languages. + this.navigationSidebar = new WebInspector.Sidebar(document.getElementById("navigation-sidebar"), WebInspector.Sidebar.Sides.Left); + this.navigationSidebar.addEventListener(WebInspector.Sidebar.Event.WidthDidChange, this._sidebarWidthDidChange, this); + + this.detailsSidebar = new WebInspector.Sidebar(document.getElementById("details-sidebar"), WebInspector.Sidebar.Sides.Right, null, null, WebInspector.UIString("Details"), true); + this.detailsSidebar.addEventListener(WebInspector.Sidebar.Event.WidthDidChange, this._sidebarWidthDidChange, this); + + this.searchKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl | WebInspector.KeyboardShortcut.Modifier.Shift, "F", this._focusSearchField.bind(this)); + this._findKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, "F", this._find.bind(this)); + this._saveKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, "S", this._save.bind(this)); + this._saveAsKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.Shift | WebInspector.KeyboardShortcut.Modifier.CommandOrControl, "S", this._saveAs.bind(this)); + + this.openResourceKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl | WebInspector.KeyboardShortcut.Modifier.Shift, "O", this._showOpenResourceDialog.bind(this)); + new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, "P", this._showOpenResourceDialog.bind(this)); + + this.navigationSidebarKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl | WebInspector.KeyboardShortcut.Modifier.Shift, "0", this.toggleNavigationSidebar.bind(this)); + this.detailsSidebarKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl | WebInspector.KeyboardShortcut.Modifier.Option, "0", this.toggleDetailsSidebar.bind(this)); + + let boundIncreaseZoom = this._increaseZoom.bind(this); + let boundDecreaseZoom = this._decreaseZoom.bind(this); + this._increaseZoomKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, WebInspector.KeyboardShortcut.Key.Plus, boundIncreaseZoom); + this._decreaseZoomKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, WebInspector.KeyboardShortcut.Key.Minus, boundDecreaseZoom); + this._increaseZoomKeyboardShortcut2 = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl | WebInspector.KeyboardShortcut.Modifier.Shift, WebInspector.KeyboardShortcut.Key.Plus, boundIncreaseZoom); + this._decreaseZoomKeyboardShortcut2 = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl | WebInspector.KeyboardShortcut.Modifier.Shift, WebInspector.KeyboardShortcut.Key.Minus, boundDecreaseZoom); + this._resetZoomKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, "0", this._resetZoom.bind(this)); + + this._showTabAtIndexKeyboardShortcuts = [1, 2, 3, 4, 5, 6, 7, 8, 9].map((i) => new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl | WebInspector.KeyboardShortcut.Modifier.Option, `${i}`, this._showTabAtIndex.bind(this, i))); + this._openNewTabKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl | WebInspector.KeyboardShortcut.Modifier.Option, "T", this.showNewTabTab.bind(this)); + + this.tabBrowser = new WebInspector.TabBrowser(document.getElementById("tab-browser"), this.tabBar, this.navigationSidebar, this.detailsSidebar); + this.tabBrowser.addEventListener(WebInspector.TabBrowser.Event.SelectedTabContentViewDidChange, this._tabBrowserSelectedTabContentViewDidChange, this); + + this._reloadPageKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, "R", this._reloadPage.bind(this)); + this._reloadPageIgnoringCacheKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl | WebInspector.KeyboardShortcut.Modifier.Shift, "R", this._reloadPageIgnoringCache.bind(this)); + this._reloadPageKeyboardShortcut.implicitlyPreventsDefault = this._reloadPageIgnoringCacheKeyboardShortcut.implicitlyPreventsDefault = false; + + this._consoleTabKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.Option | WebInspector.KeyboardShortcut.Modifier.CommandOrControl, "C", this._showConsoleTab.bind(this)); + this._quickConsoleKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.Control, WebInspector.KeyboardShortcut.Key.Apostrophe, this._focusConsolePrompt.bind(this)); + + this._inspectModeKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl | WebInspector.KeyboardShortcut.Modifier.Shift, "C", this._toggleInspectMode.bind(this)); + + this._undoKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, "Z", this._undoKeyboardShortcut.bind(this)); + this._redoKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl | WebInspector.KeyboardShortcut.Modifier.Shift, "Z", this._redoKeyboardShortcut.bind(this)); + this._undoKeyboardShortcut.implicitlyPreventsDefault = this._redoKeyboardShortcut.implicitlyPreventsDefault = false; + + this.toggleBreakpointsKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, "Y", this.debuggerToggleBreakpoints.bind(this)); + this.pauseOrResumeKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.Control | WebInspector.KeyboardShortcut.Modifier.CommandOrControl, "Y", this.debuggerPauseResumeToggle.bind(this)); + this.stepOverKeyboardShortcut = new WebInspector.KeyboardShortcut(null, WebInspector.KeyboardShortcut.Key.F6, this.debuggerStepOver.bind(this)); + this.stepIntoKeyboardShortcut = new WebInspector.KeyboardShortcut(null, WebInspector.KeyboardShortcut.Key.F7, this.debuggerStepInto.bind(this)); + this.stepOutKeyboardShortcut = new WebInspector.KeyboardShortcut(null, WebInspector.KeyboardShortcut.Key.F8, this.debuggerStepOut.bind(this)); + + this.pauseOrResumeAlternateKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, WebInspector.KeyboardShortcut.Key.Backslash, this.debuggerPauseResumeToggle.bind(this)); + this.stepOverAlternateKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, WebInspector.KeyboardShortcut.Key.SingleQuote, this.debuggerStepOver.bind(this)); + this.stepIntoAlternateKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, WebInspector.KeyboardShortcut.Key.Semicolon, this.debuggerStepInto.bind(this)); + this.stepOutAlternateKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.Shift | WebInspector.KeyboardShortcut.Modifier.CommandOrControl, WebInspector.KeyboardShortcut.Key.Semicolon, this.debuggerStepOut.bind(this)); + + this._closeToolbarButton = new WebInspector.ControlToolbarItem("dock-close", WebInspector.UIString("Close"), "Images/Close.svg", 16, 14); + this._closeToolbarButton.addEventListener(WebInspector.ButtonNavigationItem.Event.Clicked, this.close, this); + + this._undockToolbarButton = new WebInspector.ButtonToolbarItem("undock", WebInspector.UIString("Detach into separate window"), null, "Images/Undock.svg"); + this._undockToolbarButton.element.classList.add(WebInspector.Popover.IgnoreAutoDismissClassName); + this._undockToolbarButton.addEventListener(WebInspector.ButtonNavigationItem.Event.Clicked, this._undock, this); + + let dockImage = WebInspector.resolvedLayoutDirection() === WebInspector.LayoutDirection.RTL ? "Images/DockLeft.svg" : "Images/DockRight.svg"; + this._dockToSideToolbarButton = new WebInspector.ButtonToolbarItem("dock-right", WebInspector.UIString("Dock to side of window"), null, dockImage); + this._dockToSideToolbarButton.element.classList.add(WebInspector.Popover.IgnoreAutoDismissClassName); + + let dockToSideCallback = WebInspector.resolvedLayoutDirection() === WebInspector.LayoutDirection.RTL ? this._dockLeft : this._dockRight; + this._dockToSideToolbarButton.addEventListener(WebInspector.ButtonNavigationItem.Event.Clicked, dockToSideCallback, this); + + this._dockBottomToolbarButton = new WebInspector.ButtonToolbarItem("dock-bottom", WebInspector.UIString("Dock to bottom of window"), null, "Images/DockBottom.svg"); + this._dockBottomToolbarButton.element.classList.add(WebInspector.Popover.IgnoreAutoDismissClassName); + this._dockBottomToolbarButton.addEventListener(WebInspector.ButtonNavigationItem.Event.Clicked, this._dockBottom, this); + + this._togglePreviousDockConfigurationKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl | WebInspector.KeyboardShortcut.Modifier.Shift, "D", this._togglePreviousDockConfiguration.bind(this)); + + var toolTip; + if (WebInspector.debuggableType === WebInspector.DebuggableType.JavaScript) + toolTip = WebInspector.UIString("Restart (%s)").format(this._reloadPageKeyboardShortcut.displayName); + else + toolTip = WebInspector.UIString("Reload page (%s)\nReload ignoring cache (%s)").format(this._reloadPageKeyboardShortcut.displayName, this._reloadPageIgnoringCacheKeyboardShortcut.displayName); + + this._reloadToolbarButton = new WebInspector.ButtonToolbarItem("reload", toolTip, null, "Images/ReloadToolbar.svg"); + this._reloadToolbarButton.addEventListener(WebInspector.ButtonNavigationItem.Event.Clicked, this._reloadPageClicked, this); + + this._downloadToolbarButton = new WebInspector.ButtonToolbarItem("download", WebInspector.UIString("Download Web Archive"), null, "Images/DownloadArrow.svg"); + this._downloadToolbarButton.addEventListener(WebInspector.ButtonNavigationItem.Event.Clicked, this._downloadWebArchive, this); + + this._updateReloadToolbarButton(); + this._updateDownloadToolbarButton(); + + // The toolbar button for node inspection. + if (this.debuggableType === WebInspector.DebuggableType.Web) { + var toolTip = WebInspector.UIString("Start element selection (%s)").format(WebInspector._inspectModeKeyboardShortcut.displayName); + var activatedToolTip = WebInspector.UIString("Stop element selection (%s)").format(WebInspector._inspectModeKeyboardShortcut.displayName); + this._inspectModeToolbarButton = new WebInspector.ActivateButtonToolbarItem("inspect", toolTip, activatedToolTip, null, "Images/Crosshair.svg"); + this._inspectModeToolbarButton.addEventListener(WebInspector.ButtonNavigationItem.Event.Clicked, this._toggleInspectMode, this); + } + + this._dashboardContainer = new WebInspector.DashboardContainerView; + this._dashboardContainer.showDashboardViewForRepresentedObject(this.dashboardManager.dashboards.default); + + this._searchToolbarItem = new WebInspector.SearchBar("inspector-search", WebInspector.UIString("Search"), null, true); + this._searchToolbarItem.addEventListener(WebInspector.SearchBar.Event.TextChanged, this._searchTextDidChange, this); + + this.toolbar.addToolbarItem(this._closeToolbarButton, WebInspector.Toolbar.Section.Control); + + this.toolbar.addToolbarItem(this._undockToolbarButton, WebInspector.Toolbar.Section.Left); + this.toolbar.addToolbarItem(this._dockToSideToolbarButton, WebInspector.Toolbar.Section.Left); + this.toolbar.addToolbarItem(this._dockBottomToolbarButton, WebInspector.Toolbar.Section.Left); + + this.toolbar.addToolbarItem(this._reloadToolbarButton, WebInspector.Toolbar.Section.CenterLeft); + this.toolbar.addToolbarItem(this._downloadToolbarButton, WebInspector.Toolbar.Section.CenterLeft); + + this.toolbar.addToolbarItem(this._dashboardContainer.toolbarItem, WebInspector.Toolbar.Section.Center); + + if (this._inspectModeToolbarButton) + this.toolbar.addToolbarItem(this._inspectModeToolbarButton, WebInspector.Toolbar.Section.CenterRight); + + this.toolbar.addToolbarItem(this._searchToolbarItem, WebInspector.Toolbar.Section.Right); + + this.resourceDetailsSidebarPanel = new WebInspector.ResourceDetailsSidebarPanel; + this.domNodeDetailsSidebarPanel = new WebInspector.DOMNodeDetailsSidebarPanel; + this.cssStyleDetailsSidebarPanel = new WebInspector.CSSStyleDetailsSidebarPanel; + this.applicationCacheDetailsSidebarPanel = new WebInspector.ApplicationCacheDetailsSidebarPanel; + this.indexedDatabaseDetailsSidebarPanel = new WebInspector.IndexedDatabaseDetailsSidebarPanel; + this.scopeChainDetailsSidebarPanel = new WebInspector.ScopeChainDetailsSidebarPanel; + this.probeDetailsSidebarPanel = new WebInspector.ProbeDetailsSidebarPanel; + + if (window.LayerTreeAgent) + this.layerTreeDetailsSidebarPanel = new WebInspector.LayerTreeDetailsSidebarPanel; + + this.modifierKeys = {altKey: false, metaKey: false, shiftKey: false}; + + let dockedResizerElement = document.getElementById("docked-resizer"); + dockedResizerElement.classList.add(WebInspector.Popover.IgnoreAutoDismissClassName); + dockedResizerElement.addEventListener("mousedown", this._dockedResizerMouseDown.bind(this)); + + this._dockingAvailable = false; + + this._updateDockNavigationItems(); + this._setupViewHierarchy(); + + // These tabs are always available for selecting, modulo isTabAllowed(). + // Other tabs may be engineering-only or toggled at runtime if incomplete. + let productionTabClasses = [ + WebInspector.ConsoleTabContentView, + WebInspector.DebuggerTabContentView, + WebInspector.ElementsTabContentView, + WebInspector.NetworkTabContentView, + WebInspector.NewTabContentView, + WebInspector.ResourcesTabContentView, + WebInspector.SearchTabContentView, + WebInspector.SettingsTabContentView, + WebInspector.StorageTabContentView, + WebInspector.TimelineTabContentView, + ]; + + this._knownTabClassesByType = new Map; + // Set tab classes directly. The public API triggers other updates and + // notifications that won't work or have no listeners at this point. + for (let tabClass of productionTabClasses) + this._knownTabClassesByType.set(tabClass.Type, tabClass); + + this._pendingOpenTabs = []; + + // Previously we may have stored duplicates in this setting. Avoid creating duplicate tabs. + let openTabTypes = this._openTabsSetting.value; + let seenTabTypes = new Set; + + for (let i = 0; i < openTabTypes.length; ++i) { + let tabType = openTabTypes[i]; + + if (seenTabTypes.has(tabType)) + continue; + seenTabTypes.add(tabType); + + if (!this.isTabTypeAllowed(tabType)) { + this._pendingOpenTabs.push({tabType, index: i}); + continue; + } + + let tabContentView = this._createTabContentViewForType(tabType); + if (!tabContentView) + continue; + this.tabBrowser.addTabForContentView(tabContentView, true); + } + + this._restoreCookieForOpenTabs(WebInspector.StateRestorationType.Load); + + this.tabBar.selectedTabBarItem = this._selectedTabIndexSetting.value; + + if (!this.tabBar.selectedTabBarItem) + this.tabBar.selectedTabBarItem = 0; + + if (!this.tabBar.normalTabCount) + this.showNewTabTab(); + + // Listen to the events after restoring the saved tabs to avoid recursion. + this.tabBar.addEventListener(WebInspector.TabBar.Event.TabBarItemAdded, this._rememberOpenTabs, this); + this.tabBar.addEventListener(WebInspector.TabBar.Event.TabBarItemRemoved, this._rememberOpenTabs, this); + this.tabBar.addEventListener(WebInspector.TabBar.Event.TabBarItemsReordered, this._rememberOpenTabs, this); + + // Signal that the frontend is now ready to receive messages. + InspectorFrontendAPI.loadCompleted(); + + // Tell the InspectorFrontendHost we loaded, which causes the window to display + // and pending InspectorFrontendAPI commands to be sent. + InspectorFrontendHost.loaded(); + + this._updateSplitConsoleHeight(this._splitConsoleHeightSetting.value); + + if (this._showingSplitConsoleSetting.value) + this.showSplitConsole(); + + // Store this on the window in case the WebInspector global gets corrupted. + window.__frontendCompletedLoad = true; + + if (this.runBootstrapOperations) + this.runBootstrapOperations(); +}; + +WebInspector.isTabTypeAllowed = function(tabType) +{ + let tabClass = this._knownTabClassesByType.get(tabType); + if (!tabClass) + return false; + + return tabClass.isTabAllowed(); +}; + +WebInspector.knownTabClasses = function() +{ + return new Set(this._knownTabClassesByType.values()); +}; + +WebInspector._showOpenResourceDialog = function() +{ + if (!this._openResourceDialog) + this._openResourceDialog = new WebInspector.OpenResourceDialog(this); + + if (this._openResourceDialog.visible) + return; + + this._openResourceDialog.present(this._contentElement); +}; + +WebInspector._createTabContentViewForType = function(tabType) +{ + let tabClass = this._knownTabClassesByType.get(tabType); + if (!tabClass) { + console.error("Unknown tab type", tabType); + return null; + } + + console.assert(WebInspector.TabContentView.isPrototypeOf(tabClass)); + return new tabClass; +}; + +WebInspector._rememberOpenTabs = function() +{ + let seenTabTypes = new Set; + let openTabs = []; + + for (let tabBarItem of this.tabBar.tabBarItems) { + let tabContentView = tabBarItem.representedObject; + if (!(tabContentView instanceof WebInspector.TabContentView)) + continue; + if (!tabContentView.constructor.shouldSaveTab()) + continue; + console.assert(tabContentView.type, "Tab type can't be null, undefined, or empty string", tabContentView.type, tabContentView); + openTabs.push(tabContentView.type); + seenTabTypes.add(tabContentView.type); + } + + // Keep currently unsupported tabs in the setting at their previous index. + for (let {tabType, index} of this._pendingOpenTabs) { + if (seenTabTypes.has(tabType)) + continue; + openTabs.insertAtIndex(tabType, index); + seenTabTypes.add(tabType); + } + + this._openTabsSetting.value = openTabs; +}; + +WebInspector._openDefaultTab = function(event) +{ + this.showNewTabTab(); +}; + +WebInspector._showSettingsTab = function(event) +{ + this.tabBrowser.showTabForContentView(this.settingsTabContentView); +}; + +WebInspector._tryToRestorePendingTabs = function() +{ + let stillPendingOpenTabs = []; + for (let {tabType, index} of this._pendingOpenTabs) { + if (!this.isTabTypeAllowed(tabType)) { + stillPendingOpenTabs.push({tabType, index}); + continue; + } + + let tabContentView = this._createTabContentViewForType(tabType); + if (!tabContentView) + continue; + + this.tabBrowser.addTabForContentView(tabContentView, true, index); + + tabContentView.restoreStateFromCookie(WebInspector.StateRestorationType.Load); + } + + this._pendingOpenTabs = stillPendingOpenTabs; + + this.tabBrowser.tabBar.updateNewTabTabBarItemState(); +}; + +WebInspector.showNewTabTab = function(shouldAnimate) +{ + if (!this.isNewTabWithTypeAllowed(WebInspector.NewTabContentView.Type)) + return; + + let tabContentView = this.tabBrowser.bestTabContentViewForClass(WebInspector.NewTabContentView); + if (!tabContentView) + tabContentView = new WebInspector.NewTabContentView; + this.tabBrowser.showTabForContentView(tabContentView, !shouldAnimate); +}; + +WebInspector.isNewTabWithTypeAllowed = function(tabType) +{ + let tabClass = this._knownTabClassesByType.get(tabType); + if (!tabClass || !tabClass.isTabAllowed()) + return false; + + // Only allow one tab per class for now. + for (let tabBarItem of this.tabBar.tabBarItems) { + let tabContentView = tabBarItem.representedObject; + if (!(tabContentView instanceof WebInspector.TabContentView)) + continue; + if (tabContentView.constructor === tabClass) + return false; + } + + if (tabClass === WebInspector.NewTabContentView) { + let allTabs = Array.from(this.knownTabClasses()); + let addableTabs = allTabs.filter((tabClass) => !tabClass.isEphemeral()); + let canMakeNewTab = addableTabs.some((tabClass) => WebInspector.isNewTabWithTypeAllowed(tabClass.Type)); + return canMakeNewTab; + } + + return true; +}; + +WebInspector.createNewTabWithType = function(tabType, options = {}) +{ + console.assert(this.isNewTabWithTypeAllowed(tabType)); + + let {referencedView, shouldReplaceTab, shouldShowNewTab} = options; + console.assert(!referencedView || referencedView instanceof WebInspector.TabContentView, referencedView); + console.assert(!shouldReplaceTab || referencedView, "Must provide a reference view to replace a tab."); + + let tabContentView = this._createTabContentViewForType(tabType); + const suppressAnimations = true; + let insertionIndex = referencedView ? this.tabBar.tabBarItems.indexOf(referencedView.tabBarItem) : undefined; + this.tabBrowser.addTabForContentView(tabContentView, suppressAnimations, insertionIndex); + + if (shouldReplaceTab) + this.tabBrowser.closeTabForContentView(referencedView, suppressAnimations); + + if (shouldShowNewTab) + this.tabBrowser.showTabForContentView(tabContentView); +}; + +WebInspector.registerTabClass = function(tabClass) +{ + console.assert(WebInspector.TabContentView.isPrototypeOf(tabClass)); + if (!WebInspector.TabContentView.isPrototypeOf(tabClass)) + return; + + if (this._knownTabClassesByType.has(tabClass.Type)) + return; + + this._knownTabClassesByType.set(tabClass.Type, tabClass); + + this._tryToRestorePendingTabs(); + this.notifications.dispatchEventToListeners(WebInspector.Notification.TabTypesChanged); +}; + +WebInspector.activateExtraDomains = function(domains) +{ + this.hasExtraDomains = true; + + for (var domain of domains) { + var agent = InspectorBackend.activateDomain(domain); + if (agent.enable) + agent.enable(); + } + + this.notifications.dispatchEventToListeners(WebInspector.Notification.ExtraDomainsActivated, {"domains": domains}); + + WebInspector.CSSCompletions.requestCSSCompletions(); + + this._updateReloadToolbarButton(); + this._updateDownloadToolbarButton(); + this._tryToRestorePendingTabs(); +}; + +WebInspector.contentBrowserTreeElementForRepresentedObject = function(contentBrowser, representedObject) +{ + // The console does not have a sidebar, so return a tree element here so something is shown. + if (representedObject === this._consoleRepresentedObject) + return this._consoleTreeElement; + return null; +}; + +WebInspector.updateWindowTitle = function() +{ + var mainFrame = this.frameResourceManager.mainFrame; + if (!mainFrame) + return; + + var urlComponents = mainFrame.mainResource.urlComponents; + + var lastPathComponent; + try { + lastPathComponent = decodeURIComponent(urlComponents.lastPathComponent || ""); + } catch (e) { + lastPathComponent = urlComponents.lastPathComponent; + } + + // Build a title based on the URL components. + if (urlComponents.host && lastPathComponent) + var title = this.displayNameForHost(urlComponents.host) + " \u2014 " + lastPathComponent; + else if (urlComponents.host) + var title = this.displayNameForHost(urlComponents.host); + else if (lastPathComponent) + var title = lastPathComponent; + else + var title = mainFrame.url; + + // The name "inspectedURLChanged" sounds like the whole URL is required, however this is only + // used for updating the window title and it can be any string. + InspectorFrontendHost.inspectedURLChanged(title); +}; + +WebInspector.updateDockingAvailability = function(available) +{ + this._dockingAvailable = available; + + this._updateDockNavigationItems(); +}; + +WebInspector.updateDockedState = function(side) +{ + if (this._dockConfiguration === side) + return; + + this._previousDockConfiguration = this._dockConfiguration; + + if (!this._previousDockConfiguration) { + if (side === WebInspector.DockConfiguration.Right || side === WebInspector.DockConfiguration.Left) + this._previousDockConfiguration = WebInspector.DockConfiguration.Bottom; + else + this._previousDockConfiguration = WebInspector.resolvedLayoutDirection() === WebInspector.LayoutDirection.RTL ? WebInspector.DockConfiguration.Left : WebInspector.DockConfiguration.Right; + } + + this._dockConfiguration = side; + + this.docked = side !== WebInspector.DockConfiguration.Undocked; + + this._ignoreToolbarModeDidChangeEvents = true; + + if (side === WebInspector.DockConfiguration.Bottom) { + document.body.classList.add("docked", WebInspector.DockConfiguration.Bottom); + document.body.classList.remove("window-inactive", WebInspector.DockConfiguration.Right, WebInspector.DockConfiguration.Left); + } else if (side === WebInspector.DockConfiguration.Right) { + document.body.classList.add("docked", WebInspector.DockConfiguration.Right); + document.body.classList.remove("window-inactive", WebInspector.DockConfiguration.Bottom, WebInspector.DockConfiguration.Left); + } else if (side === WebInspector.DockConfiguration.Left) { + document.body.classList.add("docked", WebInspector.DockConfiguration.Left); + document.body.classList.remove("window-inactive", WebInspector.DockConfiguration.Bottom, WebInspector.DockConfiguration.Right); + } else + document.body.classList.remove("docked", WebInspector.DockConfiguration.Right, WebInspector.DockConfiguration.Left, WebInspector.DockConfiguration.Bottom); + + this._ignoreToolbarModeDidChangeEvents = false; + + this._updateDockNavigationItems(); + + if (!this.dockedConfigurationSupportsSplitContentBrowser() && !this.doesCurrentTabSupportSplitContentBrowser()) + this.hideSplitConsole(); +}; + +WebInspector.updateVisibilityState = function(visible) +{ + this.visible = visible; + this.notifications.dispatchEventToListeners(WebInspector.Notification.VisibilityStateDidChange); +}; + +WebInspector.handlePossibleLinkClick = function(event, frame, alwaysOpenExternally) +{ + var anchorElement = event.target.enclosingNodeOrSelfWithNodeName("a"); + if (!anchorElement || !anchorElement.href) + return false; + + if (WebInspector.isBeingEdited(anchorElement)) { + // Don't follow the link when it is being edited. + return false; + } + + // Prevent the link from navigating, since we don't do any navigation by following links normally. + event.preventDefault(); + event.stopPropagation(); + + this.openURL(anchorElement.href, frame, false, anchorElement.lineNumber); + + return true; +}; + +WebInspector.openURL = function(url, frame, alwaysOpenExternally, lineNumber) +{ + console.assert(url); + if (!url) + return; + + console.assert(typeof lineNumber === "undefined" || typeof lineNumber === "number", "lineNumber should be a number."); + + // If alwaysOpenExternally is not defined, base it off the command/meta key for the current event. + if (alwaysOpenExternally === undefined || alwaysOpenExternally === null) + alwaysOpenExternally = window.event ? window.event.metaKey : false; + + if (alwaysOpenExternally) { + InspectorFrontendHost.openInNewTab(url); + return; + } + + var searchChildFrames = false; + if (!frame) { + frame = this.frameResourceManager.mainFrame; + searchChildFrames = true; + } + + console.assert(frame); + + // WebInspector.Frame.resourceForURL does not check the main resource, only sub-resources. So check both. + let simplifiedURL = removeURLFragment(url); + var resource = frame.url === simplifiedURL ? frame.mainResource : frame.resourceForURL(simplifiedURL, searchChildFrames); + if (resource) { + var position = new WebInspector.SourceCodePosition(lineNumber, 0); + this.showSourceCode(resource, position); + return; + } + + InspectorFrontendHost.openInNewTab(url); +}; + +WebInspector.close = function() +{ + if (this._isClosing) + return; + + this._isClosing = true; + + InspectorFrontendHost.closeWindow(); +}; + +WebInspector.saveDataToFile = function(saveData, forceSaveAs) +{ + console.assert(saveData); + if (!saveData) + return; + + if (typeof saveData.customSaveHandler === "function") { + saveData.customSaveHandler(forceSaveAs); + return; + } + + console.assert(saveData.url); + console.assert(saveData.content); + if (!saveData.url || !saveData.content) + return; + + let suggestedName = parseURL(saveData.url).lastPathComponent; + if (!suggestedName) { + suggestedName = WebInspector.UIString("Untitled"); + let dataURLTypeMatch = /^data:([^;]+)/.exec(saveData.url); + if (dataURLTypeMatch) + suggestedName += WebInspector.fileExtensionForMIMEType(dataURLTypeMatch[1]) || ""; + } + + if (typeof saveData.content === "string") { + const base64Encoded = false; + InspectorFrontendHost.save(suggestedName, saveData.content, base64Encoded, forceSaveAs || saveData.forceSaveAs); + return; + } + + let fileReader = new FileReader; + fileReader.readAsDataURL(saveData.content); + fileReader.addEventListener("loadend", () => { + let dataURLComponents = parseDataURL(fileReader.result); + + const base64Encoded = true; + InspectorFrontendHost.save(suggestedName, dataURLComponents.data, base64Encoded, forceSaveAs || saveData.forceSaveAs); + }); +}; + +WebInspector.isConsoleFocused = function() +{ + return this.quickConsole.prompt.focused; +}; + +WebInspector.isShowingSplitConsole = function() +{ + return !this.splitContentBrowser.element.classList.contains("hidden"); +}; + +WebInspector.dockedConfigurationSupportsSplitContentBrowser = function() +{ + return this._dockConfiguration !== WebInspector.DockConfiguration.Bottom; +}; + +WebInspector.doesCurrentTabSupportSplitContentBrowser = function() +{ + var currentContentView = this.tabBrowser.selectedTabContentView; + return !currentContentView || currentContentView.supportsSplitContentBrowser; +}; + +WebInspector.toggleSplitConsole = function() +{ + if (!this.doesCurrentTabSupportSplitContentBrowser()) { + this.showConsoleTab(); + return; + } + + if (this.isShowingSplitConsole()) + this.hideSplitConsole(); + else + this.showSplitConsole(); +}; + +WebInspector.showSplitConsole = function() +{ + if (!this.doesCurrentTabSupportSplitContentBrowser()) { + this.showConsoleTab(); + return; + } + + this.splitContentBrowser.element.classList.remove("hidden"); + + this._showingSplitConsoleSetting.value = true; + + if (this.splitContentBrowser.currentContentView !== this.consoleContentView) { + // Be sure to close the view in the tab content browser before showing it in the + // split content browser. We can only show a content view in one browser at a time. + if (this.consoleContentView.parentContainer) + this.consoleContentView.parentContainer.closeContentView(this.consoleContentView); + this.splitContentBrowser.showContentView(this.consoleContentView); + } else { + // This causes the view to know it was shown and focus the prompt. + this.splitContentBrowser.shown(); + } + + this.quickConsole.consoleLogVisibilityChanged(true); +}; + +WebInspector.hideSplitConsole = function() +{ + if (!this.isShowingSplitConsole()) + return; + + this.splitContentBrowser.element.classList.add("hidden"); + + this._showingSplitConsoleSetting.value = false; + + // This causes the view to know it was hidden. + this.splitContentBrowser.hidden(); + + this.quickConsole.consoleLogVisibilityChanged(false); +}; + +WebInspector.showConsoleTab = function(requestedScope) +{ + requestedScope = requestedScope || WebInspector.LogContentView.Scopes.All; + + this.hideSplitConsole(); + + this.consoleContentView.scopeBar.item(requestedScope).selected = true; + + this.showRepresentedObject(this._consoleRepresentedObject); + + console.assert(this.isShowingConsoleTab()); +}; + +WebInspector.isShowingConsoleTab = function() +{ + return this.tabBrowser.selectedTabContentView instanceof WebInspector.ConsoleTabContentView; +}; + +WebInspector.showElementsTab = function() +{ + var tabContentView = this.tabBrowser.bestTabContentViewForClass(WebInspector.ElementsTabContentView); + if (!tabContentView) + tabContentView = new WebInspector.ElementsTabContentView; + this.tabBrowser.showTabForContentView(tabContentView); +}; + +WebInspector.showDebuggerTab = function(breakpointToSelect) +{ + var tabContentView = this.tabBrowser.bestTabContentViewForClass(WebInspector.DebuggerTabContentView); + if (!tabContentView) + tabContentView = new WebInspector.DebuggerTabContentView; + + if (breakpointToSelect instanceof WebInspector.Breakpoint) + tabContentView.revealAndSelectBreakpoint(breakpointToSelect); + + this.tabBrowser.showTabForContentView(tabContentView); +}; + +WebInspector.isShowingDebuggerTab = function() +{ + return this.tabBrowser.selectedTabContentView instanceof WebInspector.DebuggerTabContentView; +}; + +WebInspector.showResourcesTab = function() +{ + var tabContentView = this.tabBrowser.bestTabContentViewForClass(WebInspector.ResourcesTabContentView); + if (!tabContentView) + tabContentView = new WebInspector.ResourcesTabContentView; + this.tabBrowser.showTabForContentView(tabContentView); +}; + +WebInspector.showStorageTab = function() +{ + var tabContentView = this.tabBrowser.bestTabContentViewForClass(WebInspector.StorageTabContentView); + if (!tabContentView) + tabContentView = new WebInspector.StorageTabContentView; + this.tabBrowser.showTabForContentView(tabContentView); +}; + +WebInspector.showNetworkTab = function() +{ + var tabContentView = this.tabBrowser.bestTabContentViewForClass(WebInspector.NetworkTabContentView); + if (!tabContentView) + tabContentView = new WebInspector.NetworkTabContentView; + this.tabBrowser.showTabForContentView(tabContentView); +}; + +WebInspector.showTimelineTab = function() +{ + var tabContentView = this.tabBrowser.bestTabContentViewForClass(WebInspector.TimelineTabContentView); + if (!tabContentView) + tabContentView = new WebInspector.TimelineTabContentView; + this.tabBrowser.showTabForContentView(tabContentView); +}; + +WebInspector.unlocalizedString = function(string) +{ + // Intentionally do nothing, since this is for engineering builds + // (such as in Debug UI) or in text that is standardized in English. + // For example, CSS property names and values are never localized. + return string; +}; + +WebInspector.UIString = function(string, vararg) +{ + if (WebInspector.dontLocalizeUserInterface) + return string; + + if (window.localizedStrings && string in window.localizedStrings) + return window.localizedStrings[string]; + + if (!this._missingLocalizedStrings) + this._missingLocalizedStrings = {}; + + if (!(string in this._missingLocalizedStrings)) { + console.error("Localized string \"" + string + "\" was not found."); + this._missingLocalizedStrings[string] = true; + } + + return "LOCALIZED STRING NOT FOUND"; +}; + +WebInspector.indentString = function() +{ + if (WebInspector.settings.indentWithTabs.value) + return "\t"; + return " ".repeat(WebInspector.settings.indentUnit.value); +}; + +WebInspector.restoreFocusFromElement = function(element) +{ + if (element && element.isSelfOrAncestor(this.currentFocusElement)) + this.previousFocusElement.focus(); +}; + +WebInspector.toggleNavigationSidebar = function(event) +{ + if (!this.navigationSidebar.collapsed || !this.navigationSidebar.sidebarPanels.length) { + this.navigationSidebar.collapsed = true; + return; + } + + if (!this.navigationSidebar.selectedSidebarPanel) + this.navigationSidebar.selectedSidebarPanel = this.navigationSidebar.sidebarPanels[0]; + this.navigationSidebar.collapsed = false; +}; + +WebInspector.toggleDetailsSidebar = function(event) +{ + if (!this.detailsSidebar.collapsed || !this.detailsSidebar.sidebarPanels.length) { + this.detailsSidebar.collapsed = true; + return; + } + + if (!this.detailsSidebar.selectedSidebarPanel) + this.detailsSidebar.selectedSidebarPanel = this.detailsSidebar.sidebarPanels[0]; + this.detailsSidebar.collapsed = false; +}; + +WebInspector.tabContentViewClassForRepresentedObject = function(representedObject) +{ + if (representedObject instanceof WebInspector.DOMTree) + return WebInspector.ElementsTabContentView; + + if (representedObject instanceof WebInspector.TimelineRecording) + return WebInspector.TimelineTabContentView; + + // We only support one console tab right now. So this isn't an instanceof check. + if (representedObject === this._consoleRepresentedObject) + return WebInspector.ConsoleTabContentView; + + if (WebInspector.debuggerManager.paused) { + if (representedObject instanceof WebInspector.Script) + return WebInspector.DebuggerTabContentView; + + if (representedObject instanceof WebInspector.Resource && (representedObject.type === WebInspector.Resource.Type.Document || representedObject.type === WebInspector.Resource.Type.Script)) + return WebInspector.DebuggerTabContentView; + } + + if (representedObject instanceof WebInspector.Frame || representedObject instanceof WebInspector.Resource || representedObject instanceof WebInspector.Script) + return WebInspector.ResourcesTabContentView; + + // FIXME: Move Content Flows to the Elements tab? + if (representedObject instanceof WebInspector.ContentFlow) + return WebInspector.ResourcesTabContentView; + + // FIXME: Move these to a Storage tab. + if (representedObject instanceof WebInspector.DOMStorageObject || representedObject instanceof WebInspector.CookieStorageObject || + representedObject instanceof WebInspector.DatabaseTableObject || representedObject instanceof WebInspector.DatabaseObject || + representedObject instanceof WebInspector.ApplicationCacheFrame || representedObject instanceof WebInspector.IndexedDatabaseObjectStore || + representedObject instanceof WebInspector.IndexedDatabaseObjectStoreIndex) + return WebInspector.ResourcesTabContentView; + + if (representedObject instanceof WebInspector.Collection) + return WebInspector.CollectionContentView; + + return null; +}; + +WebInspector.tabContentViewForRepresentedObject = function(representedObject, options = {}) +{ + let tabContentView = this.tabBrowser.bestTabContentViewForRepresentedObject(representedObject, options); + if (tabContentView) + return tabContentView; + + var tabContentViewClass = this.tabContentViewClassForRepresentedObject(representedObject); + if (!tabContentViewClass) { + console.error("Unknown representedObject, couldn't create TabContentView.", representedObject); + return null; + } + + tabContentView = new tabContentViewClass; + + this.tabBrowser.addTabForContentView(tabContentView); + + return tabContentView; +}; + +WebInspector.showRepresentedObject = function(representedObject, cookie, options = {}) +{ + let tabContentView = this.tabContentViewForRepresentedObject(representedObject, options); + console.assert(tabContentView); + if (!tabContentView) + return; + + this.tabBrowser.showTabForContentView(tabContentView); + tabContentView.showRepresentedObject(representedObject, cookie); +}; + +WebInspector.showMainFrameDOMTree = function(nodeToSelect, options = {}) +{ + console.assert(WebInspector.frameResourceManager.mainFrame); + if (!WebInspector.frameResourceManager.mainFrame) + return; + this.showRepresentedObject(WebInspector.frameResourceManager.mainFrame.domTree, {nodeToSelect}, options); +}; + +WebInspector.showSourceCodeForFrame = function(frameIdentifier, options = {}) +{ + var frame = WebInspector.frameResourceManager.frameForIdentifier(frameIdentifier); + if (!frame) { + this._frameIdentifierToShowSourceCodeWhenAvailable = frameIdentifier; + return; + } + + this._frameIdentifierToShowSourceCodeWhenAvailable = undefined; + + this.showRepresentedObject(frame, null, options); +}; + +WebInspector.showSourceCode = function(sourceCode, options = {}) +{ + const positionToReveal = options.positionToReveal; + + console.assert(!positionToReveal || positionToReveal instanceof WebInspector.SourceCodePosition, positionToReveal); + var representedObject = sourceCode; + + if (representedObject instanceof WebInspector.Script) { + // A script represented by a resource should always show the resource. + representedObject = representedObject.resource || representedObject; + } + + var cookie = positionToReveal ? {lineNumber: positionToReveal.lineNumber, columnNumber: positionToReveal.columnNumber} : {}; + this.showRepresentedObject(representedObject, cookie, options); +}; + +WebInspector.showSourceCodeLocation = function(sourceCodeLocation, options = {}) +{ + this.showSourceCode(sourceCodeLocation.displaySourceCode, Object.shallowMerge(options, { + positionToReveal: sourceCodeLocation.displayPosition() + })); +}; + +WebInspector.showOriginalUnformattedSourceCodeLocation = function(sourceCodeLocation, options = {}) +{ + this.showSourceCode(sourceCodeLocation.sourceCode, Object.shallowMerge(options, { + positionToReveal: sourceCodeLocation.position(), + forceUnformatted: true + })); +}; + +WebInspector.showOriginalOrFormattedSourceCodeLocation = function(sourceCodeLocation, options = {}) +{ + this.showSourceCode(sourceCodeLocation.sourceCode, Object.shallowMerge(options, { + positionToReveal: sourceCodeLocation.formattedPosition() + })); +}; + +WebInspector.showOriginalOrFormattedSourceCodeTextRange = function(sourceCodeTextRange, options = {}) +{ + var textRangeToSelect = sourceCodeTextRange.formattedTextRange; + this.showSourceCode(sourceCodeTextRange.sourceCode, Object.shallowMerge(options, { + positionToReveal: textRangeToSelect.startPosition(), + textRangeToSelect + })); +}; + +WebInspector.showResourceRequest = function(resource, options = {}) +{ + this.showRepresentedObject(resource, {[WebInspector.ResourceClusterContentView.ContentViewIdentifierCookieKey]: WebInspector.ResourceClusterContentView.RequestIdentifier}, options); +}; + +WebInspector.debuggerToggleBreakpoints = function(event) +{ + WebInspector.debuggerManager.breakpointsEnabled = !WebInspector.debuggerManager.breakpointsEnabled; +}; + +WebInspector.debuggerPauseResumeToggle = function(event) +{ + if (WebInspector.debuggerManager.paused) + WebInspector.debuggerManager.resume(); + else + WebInspector.debuggerManager.pause(); +}; + +WebInspector.debuggerStepOver = function(event) +{ + WebInspector.debuggerManager.stepOver(); +}; + +WebInspector.debuggerStepInto = function(event) +{ + WebInspector.debuggerManager.stepInto(); +}; + +WebInspector.debuggerStepOut = function(event) +{ + WebInspector.debuggerManager.stepOut(); +}; + +WebInspector._searchTextDidChange = function(event) +{ + var tabContentView = this.tabBrowser.bestTabContentViewForClass(WebInspector.SearchTabContentView); + if (!tabContentView) + tabContentView = new WebInspector.SearchTabContentView; + + var searchQuery = this._searchToolbarItem.text; + this._searchToolbarItem.text = ""; + + this.tabBrowser.showTabForContentView(tabContentView); + + tabContentView.performSearch(searchQuery); +}; + +WebInspector._focusSearchField = function(event) +{ + if (this.tabBrowser.selectedTabContentView instanceof WebInspector.SearchTabContentView) { + this.tabBrowser.selectedTabContentView.focusSearchField(); + return; + } + + this._searchToolbarItem.focus(); +}; + +WebInspector._focusChanged = function(event) +{ + // Make a caret selection inside the focused element if there isn't a range selection and there isn't already + // a caret selection inside. This is needed (at least) to remove caret from console when focus is moved. + // The selection change should not apply to text fields and text areas either. + + if (WebInspector.isEventTargetAnEditableField(event)) { + // Still update the currentFocusElement if inside of a CodeMirror editor. + var codeMirrorEditorElement = event.target.enclosingNodeOrSelfWithClass("CodeMirror"); + if (codeMirrorEditorElement && codeMirrorEditorElement !== this.currentFocusElement) { + this.previousFocusElement = this.currentFocusElement; + this.currentFocusElement = codeMirrorEditorElement; + } + return; + } + + var selection = window.getSelection(); + if (!selection.isCollapsed) + return; + + var element = event.target; + + if (element !== this.currentFocusElement) { + this.previousFocusElement = this.currentFocusElement; + this.currentFocusElement = element; + } + + if (element.isInsertionCaretInside()) + return; + + var selectionRange = element.ownerDocument.createRange(); + selectionRange.setStart(element, 0); + selectionRange.setEnd(element, 0); + + selection.removeAllRanges(); + selection.addRange(selectionRange); +}; + +WebInspector._mouseWasClicked = function(event) +{ + this.handlePossibleLinkClick(event); +}; + +WebInspector._dragOver = function(event) +{ + // Do nothing if another event listener handled the event already. + if (event.defaultPrevented) + return; + + // Allow dropping into editable areas. + if (WebInspector.isEventTargetAnEditableField(event)) + return; + + // Prevent the drop from being accepted. + event.dataTransfer.dropEffect = "none"; + event.preventDefault(); +}; + +WebInspector._captureDidStart = function(event) +{ + this._dashboardContainer.showDashboardViewForRepresentedObject(this.dashboardManager.dashboards.replay); +}; + +WebInspector._debuggerDidPause = function(event) +{ + // FIXME: Web Inspector: Preference for Auto Showing Scope Chain sidebar on pause + this.showDebuggerTab(); + + this._dashboardContainer.showDashboardViewForRepresentedObject(this.dashboardManager.dashboards.debugger); + + InspectorFrontendHost.bringToFront(); +}; + +WebInspector._debuggerDidResume = function(event) +{ + this._dashboardContainer.closeDashboardViewForRepresentedObject(this.dashboardManager.dashboards.debugger); +}; + +WebInspector._frameWasAdded = function(event) +{ + if (!this._frameIdentifierToShowSourceCodeWhenAvailable) + return; + + var frame = event.data.frame; + if (frame.id !== this._frameIdentifierToShowSourceCodeWhenAvailable) + return; + + function delayedWork() + { + this.showSourceCodeForFrame(frame.id); + } + + // Delay showing the frame since FrameWasAdded is called before MainFrameChanged. + // Calling showSourceCodeForFrame before MainFrameChanged will show the frame then close it. + setTimeout(delayedWork.bind(this)); +}; + +WebInspector._mainFrameDidChange = function(event) +{ + this._updateDownloadToolbarButton(); + + this.updateWindowTitle(); +}; + +WebInspector._mainResourceDidChange = function(event) +{ + if (!event.target.isMainFrame()) + return; + + this._inProvisionalLoad = false; + + // Run cookie restoration after we are sure all of the Tabs and NavigationSidebarPanels + // have updated with respect to the main resource change. + setTimeout(this._restoreCookieForOpenTabs.bind(this, WebInspector.StateRestorationType.Navigation)); + + this._updateDownloadToolbarButton(); + + this.updateWindowTitle(); +}; + +WebInspector._provisionalLoadStarted = function(event) +{ + if (!event.target.isMainFrame()) + return; + + this._saveCookieForOpenTabs(); + + this._inProvisionalLoad = true; +}; + +WebInspector._restoreCookieForOpenTabs = function(restorationType) +{ + for (var tabBarItem of this.tabBar.tabBarItems) { + var tabContentView = tabBarItem.representedObject; + if (!(tabContentView instanceof WebInspector.TabContentView)) + continue; + tabContentView.restoreStateFromCookie(restorationType); + } +}; + +WebInspector._saveCookieForOpenTabs = function() +{ + for (var tabBarItem of this.tabBar.tabBarItems) { + var tabContentView = tabBarItem.representedObject; + if (!(tabContentView instanceof WebInspector.TabContentView)) + continue; + tabContentView.saveStateToCookie(); + } +}; + +WebInspector._windowFocused = function(event) +{ + if (event.target.document.nodeType !== Node.DOCUMENT_NODE) + return; + + // FIXME: We should use the :window-inactive pseudo class once https://webkit.org/b/38927 is fixed. + document.body.classList.remove(this.docked ? "window-docked-inactive" : "window-inactive"); +}; + +WebInspector._windowBlurred = function(event) +{ + if (event.target.document.nodeType !== Node.DOCUMENT_NODE) + return; + + // FIXME: We should use the :window-inactive pseudo class once https://webkit.org/b/38927 is fixed. + document.body.classList.add(this.docked ? "window-docked-inactive" : "window-inactive"); +}; + +WebInspector._windowResized = function(event) +{ + this.toolbar.updateLayout(WebInspector.View.LayoutReason.Resize); + this.tabBar.updateLayout(WebInspector.View.LayoutReason.Resize); + this._tabBrowserSizeDidChange(); +}; + +WebInspector._updateModifierKeys = function(event) +{ + var didChange = this.modifierKeys.altKey !== event.altKey || this.modifierKeys.metaKey !== event.metaKey || this.modifierKeys.shiftKey !== event.shiftKey; + + this.modifierKeys = {altKey: event.altKey, metaKey: event.metaKey, shiftKey: event.shiftKey}; + + if (didChange) + this.notifications.dispatchEventToListeners(WebInspector.Notification.GlobalModifierKeysDidChange, event); +}; + +WebInspector._windowKeyDown = function(event) +{ + this._updateModifierKeys(event); +}; + +WebInspector._windowKeyUp = function(event) +{ + this._updateModifierKeys(event); +}; + +WebInspector._mouseDown = function(event) +{ + if (this.toolbar.element.isSelfOrAncestor(event.target)) + this._toolbarMouseDown(event); +}; + +WebInspector._mouseMoved = function(event) +{ + this._updateModifierKeys(event); + this.mouseCoords = { + x: event.pageX, + y: event.pageY + }; +}; + +WebInspector._pageHidden = function(event) +{ + this._saveCookieForOpenTabs(); +}; + +WebInspector._contextMenuRequested = function(event) +{ + let proposedContextMenu; + + // This is setting is only defined in engineering builds. + if (WebInspector.isDebugUIEnabled()) { + proposedContextMenu = WebInspector.ContextMenu.createFromEvent(event); + proposedContextMenu.appendSeparator(); + proposedContextMenu.appendItem(WebInspector.unlocalizedString("Reload Web Inspector"), () => { + window.location.reload(); + }); + + let protocolSubMenu = proposedContextMenu.appendSubMenuItem(WebInspector.unlocalizedString("Protocol Debugging"), null, false); + let isCapturingTraffic = InspectorBackend.activeTracer instanceof WebInspector.CapturingProtocolTracer; + + protocolSubMenu.appendCheckboxItem(WebInspector.unlocalizedString("Capture Trace"), () => { + if (isCapturingTraffic) + InspectorBackend.activeTracer = null; + else + InspectorBackend.activeTracer = new WebInspector.CapturingProtocolTracer; + }, isCapturingTraffic); + + protocolSubMenu.appendSeparator(); + + protocolSubMenu.appendItem(WebInspector.unlocalizedString("Export Trace\u2026"), () => { + const forceSaveAs = true; + WebInspector.saveDataToFile(InspectorBackend.activeTracer.trace.saveData, forceSaveAs); + }, !isCapturingTraffic); + } else { + const onlyExisting = true; + proposedContextMenu = WebInspector.ContextMenu.createFromEvent(event, onlyExisting); + } + + if (proposedContextMenu) + proposedContextMenu.show(); +}; + +WebInspector.isDebugUIEnabled = function() +{ + return WebInspector.showDebugUISetting && WebInspector.showDebugUISetting.value; +}; + +WebInspector._undock = function(event) +{ + InspectorFrontendHost.requestSetDockSide(WebInspector.DockConfiguration.Undocked); +}; + +WebInspector._dockBottom = function(event) +{ + InspectorFrontendHost.requestSetDockSide(WebInspector.DockConfiguration.Bottom); +}; + +WebInspector._dockRight = function(event) +{ + InspectorFrontendHost.requestSetDockSide(WebInspector.DockConfiguration.Right); +}; + +WebInspector._dockLeft = function(event) +{ + InspectorFrontendHost.requestSetDockSide(WebInspector.DockConfiguration.Left); +}; + +WebInspector._togglePreviousDockConfiguration = function(event) +{ + InspectorFrontendHost.requestSetDockSide(this._previousDockConfiguration); +}; + +WebInspector._updateDockNavigationItems = function() +{ + if (this._dockingAvailable || this.docked) { + this._closeToolbarButton.hidden = !this.docked; + this._undockToolbarButton.hidden = this._dockConfiguration === WebInspector.DockConfiguration.Undocked; + this._dockBottomToolbarButton.hidden = this._dockConfiguration === WebInspector.DockConfiguration.Bottom; + this._dockToSideToolbarButton.hidden = this._dockConfiguration === WebInspector.DockConfiguration.Right || this._dockConfiguration === WebInspector.DockConfiguration.Left; + } else { + this._closeToolbarButton.hidden = true; + this._undockToolbarButton.hidden = true; + this._dockBottomToolbarButton.hidden = true; + this._dockToSideToolbarButton.hidden = true; + } +}; + +WebInspector._tabBrowserSizeDidChange = function() +{ + this.tabBrowser.updateLayout(WebInspector.View.LayoutReason.Resize); + this.splitContentBrowser.updateLayout(WebInspector.View.LayoutReason.Resize); + this.quickConsole.updateLayout(WebInspector.View.LayoutReason.Resize); +}; + +WebInspector._quickConsoleDidResize = function(event) +{ + this.tabBrowser.updateLayout(WebInspector.View.LayoutReason.Resize); +}; + +WebInspector._sidebarWidthDidChange = function(event) +{ + this._tabBrowserSizeDidChange(); +}; + +WebInspector._setupViewHierarchy = function() +{ + let rootView = WebInspector.View.rootView(); + rootView.addSubview(this.toolbar); + rootView.addSubview(this.tabBar); + rootView.addSubview(this.navigationSidebar); + rootView.addSubview(this.tabBrowser); + rootView.addSubview(this.splitContentBrowser); + rootView.addSubview(this.quickConsole); + rootView.addSubview(this.detailsSidebar); +}; + +WebInspector._tabBrowserSelectedTabContentViewDidChange = function(event) +{ + if (this.tabBar.selectedTabBarItem && this.tabBar.selectedTabBarItem.representedObject.constructor.shouldSaveTab()) + this._selectedTabIndexSetting.value = this.tabBar.tabBarItems.indexOf(this.tabBar.selectedTabBarItem); + + if (!this.doesCurrentTabSupportSplitContentBrowser()) + this.hideSplitConsole(); + + if (!this.isShowingSplitConsole()) + this.quickConsole.consoleLogVisibilityChanged(this.isShowingConsoleTab()); +}; + +WebInspector._initializeWebSocketIfNeeded = function() +{ + if (!InspectorFrontendHost.initializeWebSocket) + return; + + var queryParams = parseLocationQueryParameters(); + + if ("ws" in queryParams) + var url = "ws://" + queryParams.ws; + else if ("page" in queryParams) { + var page = queryParams.page; + var host = "host" in queryParams ? queryParams.host : window.location.host; + var url = "ws://" + host + "/devtools/page/" + page; + } + + if (!url) + return; + + InspectorFrontendHost.initializeWebSocket(url); +}; + +WebInspector._updateSplitConsoleHeight = function(height) +{ + const minimumHeight = 64; + const maximumHeight = window.innerHeight * 0.55; + + height = Math.max(minimumHeight, Math.min(height, maximumHeight)); + + this.splitContentBrowser.element.style.height = height + "px"; +}; + +WebInspector._consoleResizerMouseDown = function(event) +{ + if (event.button !== 0 || event.ctrlKey) + return; + + // Only start dragging if the target is one of the elements that we expect. + if (!event.target.classList.contains("navigation-bar") && !event.target.classList.contains("flexible-space")) + return; + + var resizerElement = event.target; + var mouseOffset = resizerElement.offsetHeight - (event.pageY - resizerElement.totalOffsetTop); + + function dockedResizerDrag(event) + { + if (event.button !== 0) + return; + + var height = window.innerHeight - event.pageY - mouseOffset; + + this._splitConsoleHeightSetting.value = height; + + this._updateSplitConsoleHeight(height); + + this.quickConsole.dispatchEventToListeners(WebInspector.QuickConsole.Event.DidResize); + } + + function dockedResizerDragEnd(event) + { + if (event.button !== 0) + return; + + this.elementDragEnd(event); + } + + this.elementDragStart(resizerElement, dockedResizerDrag.bind(this), dockedResizerDragEnd.bind(this), event, "row-resize"); +}; + +WebInspector._toolbarMouseDown = function(event) +{ + if (event.ctrlKey) + return; + + if (this._dockConfiguration === WebInspector.DockConfiguration.Right || this._dockConfiguration === WebInspector.DockConfiguration.Left) + return; + + if (this.docked) + this._dockedResizerMouseDown(event); + else + this._moveWindowMouseDown(event); +}; + +WebInspector._dockedResizerMouseDown = function(event) +{ + if (event.button !== 0 || event.ctrlKey) + return; + + if (!this.docked) + return; + + // Only start dragging if the target is one of the elements that we expect. + if (event.target.id !== "docked-resizer" && !event.target.classList.contains("toolbar") && + !event.target.classList.contains("flexible-space") && !event.target.classList.contains("item-section")) + return; + + event[WebInspector.Popover.EventPreventDismissSymbol] = true; + + let windowProperty = this._dockConfiguration === WebInspector.DockConfiguration.Bottom ? "innerHeight" : "innerWidth"; + let eventScreenProperty = this._dockConfiguration === WebInspector.DockConfiguration.Bottom ? "screenY" : "screenX"; + let eventClientProperty = this._dockConfiguration === WebInspector.DockConfiguration.Bottom ? "clientY" : "clientX"; + + var resizerElement = event.target; + var firstClientPosition = event[eventClientProperty]; + var lastScreenPosition = event[eventScreenProperty]; + + function dockedResizerDrag(event) + { + if (event.button !== 0) + return; + + var position = event[eventScreenProperty]; + var delta = position - lastScreenPosition; + var clientPosition = event[eventClientProperty]; + + lastScreenPosition = position; + + if (this._dockConfiguration === WebInspector.DockConfiguration.Left) { + // If the mouse is travelling rightward but is positioned left of the resizer, ignore the event. + if (delta > 0 && clientPosition < firstClientPosition) + return; + + // If the mouse is travelling leftward but is positioned to the right of the resizer, ignore the event. + if (delta < 0 && clientPosition > window[windowProperty]) + return; + + // We later subtract the delta from the current position, but since the inspected view and inspector view + // are flipped when docked to left, we want dragging to have the opposite effect from docked to right. + delta *= -1; + } else { + // If the mouse is travelling downward/rightward but is positioned above/left of the resizer, ignore the event. + if (delta > 0 && clientPosition < firstClientPosition) + return; + + // If the mouse is travelling upward/leftward but is positioned below/right of the resizer, ignore the event. + if (delta < 0 && clientPosition > firstClientPosition) + return; + } + + let dimension = Math.max(0, window[windowProperty] - delta); + // If zoomed in/out, there be greater/fewer document pixels shown, but the inspector's + // width or height should be the same in device pixels regardless of the document zoom. + dimension *= this.getZoomFactor(); + + if (this._dockConfiguration === WebInspector.DockConfiguration.Bottom) + InspectorFrontendHost.setAttachedWindowHeight(dimension); + else + InspectorFrontendHost.setAttachedWindowWidth(dimension); + } + + function dockedResizerDragEnd(event) + { + if (event.button !== 0) + return; + + WebInspector.elementDragEnd(event); + } + + WebInspector.elementDragStart(resizerElement, dockedResizerDrag.bind(this), dockedResizerDragEnd.bind(this), event, this._dockConfiguration === WebInspector.DockConfiguration.Bottom ? "row-resize" : "col-resize"); +}; + +WebInspector._moveWindowMouseDown = function(event) +{ + console.assert(!this.docked); + + if (event.button !== 0 || event.ctrlKey) + return; + + // Only start dragging if the target is one of the elements that we expect. + if (!event.target.classList.contains("toolbar") && !event.target.classList.contains("flexible-space") && + !event.target.classList.contains("item-section")) + return; + + event[WebInspector.Popover.EventPreventDismissSymbol] = true; + + if (WebInspector.Platform.name === "mac") { + // New Mac releases can start a window drag. + if (WebInspector.Platform.version.release >= 11) { + InspectorFrontendHost.startWindowDrag(); + event.preventDefault(); + return; + } + + // Ignore dragging on the top of the toolbar on Mac if the system handles it. + if (WebInspector.Platform.version.release === 10) { + const windowDragHandledTitleBarHeight = 22; + if (event.pageY < windowDragHandledTitleBarHeight) { + event.preventDefault(); + return; + } + } + } + + var lastScreenX = event.screenX; + var lastScreenY = event.screenY; + + function toolbarDrag(event) + { + if (event.button !== 0) + return; + + var x = event.screenX - lastScreenX; + var y = event.screenY - lastScreenY; + + InspectorFrontendHost.moveWindowBy(x, y); + + lastScreenX = event.screenX; + lastScreenY = event.screenY; + } + + function toolbarDragEnd(event) + { + if (event.button !== 0) + return; + + WebInspector.elementDragEnd(event); + } + + WebInspector.elementDragStart(event.target, toolbarDrag, toolbarDragEnd, event, "default"); +}; + +WebInspector._storageWasInspected = function(event) +{ + this.showStorageTab(); +}; + +WebInspector._domNodeWasInspected = function(event) +{ + this.domTreeManager.highlightDOMNodeForTwoSeconds(event.data.node.id); + + InspectorFrontendHost.bringToFront(); + + this.showElementsTab(); + this.showMainFrameDOMTree(event.data.node); +}; + +WebInspector._inspectModeStateChanged = function(event) +{ + this._inspectModeToolbarButton.activated = this.domTreeManager.inspectModeEnabled; +}; + +WebInspector._toggleInspectMode = function(event) +{ + this.domTreeManager.inspectModeEnabled = !this.domTreeManager.inspectModeEnabled; +}; + +WebInspector._downloadWebArchive = function(event) +{ + this.archiveMainFrame(); +}; + +WebInspector._reloadPage = function(event) +{ + if (!window.PageAgent) + return; + + PageAgent.reload(); + event.preventDefault(); +}; + +WebInspector._reloadPageClicked = function(event) +{ + // Ignore cache when the shift key is pressed. + PageAgent.reload(window.event ? window.event.shiftKey : false); +}; + +WebInspector._reloadPageIgnoringCache = function(event) +{ + if (!window.PageAgent) + return; + + PageAgent.reload(true); + event.preventDefault(); +}; + +WebInspector._updateReloadToolbarButton = function() +{ + if (!window.PageAgent) { + this._reloadToolbarButton.hidden = true; + return; + } + + this._reloadToolbarButton.hidden = false; +}; + +WebInspector._updateDownloadToolbarButton = function() +{ + // COMPATIBILITY (iOS 7): Page.archive did not exist yet. + if (!window.PageAgent || !PageAgent.archive || this.debuggableType !== WebInspector.DebuggableType.Web) { + this._downloadToolbarButton.hidden = true; + return; + } + + if (this._downloadingPage) { + this._downloadToolbarButton.enabled = false; + return; + } + + this._downloadToolbarButton.enabled = this.canArchiveMainFrame(); +}; + +WebInspector._toggleInspectMode = function(event) +{ + this.domTreeManager.inspectModeEnabled = !this.domTreeManager.inspectModeEnabled; +}; + +WebInspector._showConsoleTab = function(event) +{ + this.showConsoleTab(); +}; + +WebInspector._focusConsolePrompt = function(event) +{ + this.quickConsole.prompt.focus(); +}; + +WebInspector._focusedContentBrowser = function() +{ + if (this.tabBrowser.element.isSelfOrAncestor(this.currentFocusElement) || document.activeElement === document.body) { + var tabContentView = this.tabBrowser.selectedTabContentView; + if (tabContentView instanceof WebInspector.ContentBrowserTabContentView) + return tabContentView.contentBrowser; + return null; + } + + if (this.splitContentBrowser.element.isSelfOrAncestor(this.currentFocusElement) + || (WebInspector.isShowingSplitConsole() && this.quickConsole.element.isSelfOrAncestor(this.currentFocusElement))) + return this.splitContentBrowser; + + return null; +}; + +WebInspector._focusedContentView = function() +{ + if (this.tabBrowser.element.isSelfOrAncestor(this.currentFocusElement) || document.activeElement === document.body) { + var tabContentView = this.tabBrowser.selectedTabContentView; + if (tabContentView instanceof WebInspector.ContentBrowserTabContentView) + return tabContentView.contentBrowser.currentContentView; + return tabContentView; + } + + if (this.splitContentBrowser.element.isSelfOrAncestor(this.currentFocusElement) + || (WebInspector.isShowingSplitConsole() && this.quickConsole.element.isSelfOrAncestor(this.currentFocusElement))) + return this.splitContentBrowser.currentContentView; + + return null; +}; + +WebInspector._focusedOrVisibleContentBrowser = function() +{ + let focusedContentBrowser = this._focusedContentBrowser(); + if (focusedContentBrowser) + return focusedContentBrowser; + + var tabContentView = this.tabBrowser.selectedTabContentView; + if (tabContentView instanceof WebInspector.ContentBrowserTabContentView) + return tabContentView.contentBrowser; + + return null; +}; + +WebInspector.focusedOrVisibleContentView = function() +{ + let focusedContentView = this._focusedContentView(); + if (focusedContentView) + return focusedContentView; + + var tabContentView = this.tabBrowser.selectedTabContentView; + if (tabContentView instanceof WebInspector.ContentBrowserTabContentView) + return tabContentView.contentBrowser.currentContentView; + return tabContentView; +}; + +WebInspector._beforecopy = function(event) +{ + var selection = window.getSelection(); + + // If there is no selection, see if the focused element or focused ContentView can handle the copy event. + if (selection.isCollapsed && !WebInspector.isEventTargetAnEditableField(event)) { + var focusedCopyHandler = this.currentFocusElement && this.currentFocusElement.copyHandler; + if (focusedCopyHandler && typeof focusedCopyHandler.handleBeforeCopyEvent === "function") { + focusedCopyHandler.handleBeforeCopyEvent(event); + if (event.defaultPrevented) + return; + } + + var focusedContentView = this._focusedContentView(); + if (focusedContentView && typeof focusedContentView.handleCopyEvent === "function") { + event.preventDefault(); + return; + } + + return; + } + + if (selection.isCollapsed) + return; + + // Say we can handle it (by preventing default) to remove word break characters. + event.preventDefault(); +}; + +WebInspector._find = function(event) +{ + let contentBrowser = this._focusedOrVisibleContentBrowser(); + if (!contentBrowser) + return; + + contentBrowser.showFindBanner(); +}; + +WebInspector._save = function(event) +{ + var contentView = this.focusedOrVisibleContentView(); + if (!contentView || !contentView.supportsSave) + return; + + WebInspector.saveDataToFile(contentView.saveData); +}; + +WebInspector._saveAs = function(event) +{ + var contentView = this.focusedOrVisibleContentView(); + if (!contentView || !contentView.supportsSave) + return; + + WebInspector.saveDataToFile(contentView.saveData, true); +}; + +WebInspector._clear = function(event) +{ + let contentView = this.focusedOrVisibleContentView(); + if (!contentView || typeof contentView.handleClearShortcut !== "function") { + // If the current content view is unable to handle this event, clear the console to reset + // the dashboard counters. + this.logManager.requestClearMessages(); + return; + } + + contentView.handleClearShortcut(event); +}; + +WebInspector._copy = function(event) +{ + var selection = window.getSelection(); + + // If there is no selection, pass the copy event on to the focused element or focused ContentView. + if (selection.isCollapsed && !WebInspector.isEventTargetAnEditableField(event)) { + var focusedCopyHandler = this.currentFocusElement && this.currentFocusElement.copyHandler; + if (focusedCopyHandler && typeof focusedCopyHandler.handleCopyEvent === "function") { + focusedCopyHandler.handleCopyEvent(event); + if (event.defaultPrevented) + return; + } + + var focusedContentView = this._focusedContentView(); + if (focusedContentView && typeof focusedContentView.handleCopyEvent === "function") { + focusedContentView.handleCopyEvent(event); + return; + } + + return; + } + + if (selection.isCollapsed) + return; + + // Remove word break characters from the selection before putting it on the pasteboard. + var selectionString = selection.toString().removeWordBreakCharacters(); + event.clipboardData.setData("text/plain", selectionString); + event.preventDefault(); +}; + +WebInspector._increaseZoom = function(event) +{ + const epsilon = 0.0001; + const maximumZoom = 2.4; + let currentZoom = this.getZoomFactor(); + if (currentZoom + epsilon >= maximumZoom) { + InspectorFrontendHost.beep(); + return; + } + + this.setZoomFactor(Math.min(maximumZoom, currentZoom + 0.2)); +}; + +WebInspector._decreaseZoom = function(event) +{ + const epsilon = 0.0001; + const minimumZoom = 0.6; + let currentZoom = this.getZoomFactor(); + if (currentZoom - epsilon <= minimumZoom) { + InspectorFrontendHost.beep(); + return; + } + + this.setZoomFactor(Math.max(minimumZoom, currentZoom - 0.2)); +}; + +WebInspector._resetZoom = function(event) +{ + this.setZoomFactor(1); +}; + +WebInspector.getZoomFactor = function() +{ + return WebInspector.settings.zoomFactor.value; +}; + +WebInspector.setZoomFactor = function(factor) +{ + InspectorFrontendHost.setZoomFactor(factor); + // Round-trip through the frontend host API in case the requested factor is not used. + WebInspector.settings.zoomFactor.value = InspectorFrontendHost.zoomFactor(); +}; + +WebInspector.resolvedLayoutDirection = function() +{ + let layoutDirection = WebInspector.settings.layoutDirection.value; + if (layoutDirection === WebInspector.LayoutDirection.System) + layoutDirection = InspectorFrontendHost.userInterfaceLayoutDirection(); + + return layoutDirection; +} + +WebInspector.setLayoutDirection = function(value) +{ + if (!Object.values(WebInspector.LayoutDirection).includes(value)) + WebInspector.reportInternalError("Unknown layout direction requested: " + value); + + if (value === WebInspector.settings.layoutDirection.value) + return; + + WebInspector.settings.layoutDirection.value = value; + + if (value === WebInspector.LayoutDirection.RTL && this._dockConfiguration === WebInspector.DockConfiguration.Right) + this._dockLeft(); + + if (value === WebInspector.LayoutDirection.LTR && this._dockConfiguration === WebInspector.DockConfiguration.Left) + this._dockRight(); + + window.location.reload(); +}; + +WebInspector._showTabAtIndex = function(i, event) +{ + if (i <= WebInspector.tabBar.tabBarItems.length) + WebInspector.tabBar.selectedTabBarItem = i - 1; +}; + +WebInspector._showJavaScriptTypeInformationSettingChanged = function(event) +{ + if (this.showJavaScriptTypeInformationSetting.value) { + for (let target of WebInspector.targets) + target.RuntimeAgent.enableTypeProfiler(); + } else { + for (let target of WebInspector.targets) + target.RuntimeAgent.disableTypeProfiler(); + } +}; + +WebInspector._enableControlFlowProfilerSettingChanged = function(event) +{ + if (this.enableControlFlowProfilerSetting.value) { + for (let target of WebInspector.targets) + target.RuntimeAgent.enableControlFlowProfiler(); + } else { + for (let target of WebInspector.targets) + target.RuntimeAgent.disableControlFlowProfiler(); + } +}; + +WebInspector.elementDragStart = function(element, dividerDrag, elementDragEnd, event, cursor, eventTarget) +{ + if (WebInspector._elementDraggingEventListener || WebInspector._elementEndDraggingEventListener) + WebInspector.elementDragEnd(event); + + if (element) { + // Install glass pane + if (WebInspector._elementDraggingGlassPane) + WebInspector._elementDraggingGlassPane.remove(); + + var glassPane = document.createElement("div"); + glassPane.style.cssText = "position:absolute;top:0;bottom:0;left:0;right:0;opacity:0;z-index:1"; + glassPane.id = "glass-pane-for-drag"; + element.ownerDocument.body.appendChild(glassPane); + WebInspector._elementDraggingGlassPane = glassPane; + } + + WebInspector._elementDraggingEventListener = dividerDrag; + WebInspector._elementEndDraggingEventListener = elementDragEnd; + + var targetDocument = event.target.ownerDocument; + + WebInspector._elementDraggingEventTarget = eventTarget || targetDocument; + WebInspector._elementDraggingEventTarget.addEventListener("mousemove", dividerDrag, true); + WebInspector._elementDraggingEventTarget.addEventListener("mouseup", elementDragEnd, true); + + targetDocument.body.style.cursor = cursor; + + event.preventDefault(); +}; + +WebInspector.elementDragEnd = function(event) +{ + WebInspector._elementDraggingEventTarget.removeEventListener("mousemove", WebInspector._elementDraggingEventListener, true); + WebInspector._elementDraggingEventTarget.removeEventListener("mouseup", WebInspector._elementEndDraggingEventListener, true); + + event.target.ownerDocument.body.style.removeProperty("cursor"); + + if (WebInspector._elementDraggingGlassPane) + WebInspector._elementDraggingGlassPane.remove(); + + delete WebInspector._elementDraggingGlassPane; + delete WebInspector._elementDraggingEventTarget; + delete WebInspector._elementDraggingEventListener; + delete WebInspector._elementEndDraggingEventListener; + + event.preventDefault(); +}; + +WebInspector.createMessageTextView = function(message, isError) +{ + var messageElement = document.createElement("div"); + messageElement.className = "message-text-view"; + if (isError) + messageElement.classList.add("error"); + + messageElement.textContent = message; + + return messageElement; +}; + +WebInspector.createGoToArrowButton = function() +{ + var button = document.createElement("button"); + button.addEventListener("mousedown", (event) => { event.stopPropagation(); }, true); + button.className = "go-to-arrow"; + button.tabIndex = -1; + return button; +}; + +WebInspector.createSourceCodeLocationLink = function(sourceCodeLocation, dontFloat, useGoToArrowButton) +{ + console.assert(sourceCodeLocation); + if (!sourceCodeLocation) + return null; + + var linkElement = document.createElement("a"); + linkElement.className = "go-to-link"; + WebInspector.linkifyElement(linkElement, sourceCodeLocation); + sourceCodeLocation.populateLiveDisplayLocationTooltip(linkElement); + + if (useGoToArrowButton) + linkElement.appendChild(WebInspector.createGoToArrowButton()); + else + sourceCodeLocation.populateLiveDisplayLocationString(linkElement, "textContent"); + + if (dontFloat) + linkElement.classList.add("dont-float"); + + return linkElement; +}; + +WebInspector.linkifyLocation = function(url, lineNumber, columnNumber, className) +{ + var sourceCode = WebInspector.sourceCodeForURL(url); + + if (!sourceCode) { + var anchor = document.createElement("a"); + anchor.href = url; + anchor.lineNumber = lineNumber; + if (className) + anchor.className = className; + anchor.append(WebInspector.displayNameForURL(url) + ":" + lineNumber); + return anchor; + } + + var sourceCodeLocation = sourceCode.createSourceCodeLocation(lineNumber, columnNumber); + var linkElement = WebInspector.createSourceCodeLocationLink(sourceCodeLocation, true); + if (className) + linkElement.classList.add(className); + return linkElement; +}; + +WebInspector.linkifyElement = function(linkElement, sourceCodeLocation) { + console.assert(sourceCodeLocation); + + function showSourceCodeLocation(event) + { + event.stopPropagation(); + event.preventDefault(); + + if (event.metaKey) + this.showOriginalUnformattedSourceCodeLocation(sourceCodeLocation); + else + this.showSourceCodeLocation(sourceCodeLocation); + } + + linkElement.addEventListener("click", showSourceCodeLocation.bind(this)); +}; + +WebInspector.sourceCodeForURL = function(url) +{ + var sourceCode = WebInspector.frameResourceManager.resourceForURL(url); + if (!sourceCode) { + sourceCode = WebInspector.debuggerManager.scriptsForURL(url, WebInspector.assumingMainTarget())[0]; + if (sourceCode) + sourceCode = sourceCode.resource || sourceCode; + } + return sourceCode || null; +}; + +WebInspector.linkifyURLAsNode = function(url, linkText, classes) +{ + if (!linkText) + linkText = url; + + classes = (classes ? classes + " " : ""); + + var a = document.createElement("a"); + a.href = url; + a.className = classes; + + a.textContent = linkText; + a.style.maxWidth = "100%"; + + return a; +}; + +WebInspector.linkifyStringAsFragmentWithCustomLinkifier = function(string, linkifier) +{ + var container = document.createDocumentFragment(); + var linkStringRegEx = /(?:[a-zA-Z][a-zA-Z0-9+.-]{2,}:\/\/|www\.)[\w$\-_+*'=\|\/\\(){}[\]%@&#~,:;.!?]{2,}[\w$\-_+*=\|\/\\({%@&#~]/; + var lineColumnRegEx = /:(\d+)(:(\d+))?$/; + + while (string) { + var linkString = linkStringRegEx.exec(string); + if (!linkString) + break; + + linkString = linkString[0]; + var linkIndex = string.indexOf(linkString); + var nonLink = string.substring(0, linkIndex); + container.append(nonLink); + + if (linkString.startsWith("data:") || linkString.startsWith("javascript:") || linkString.startsWith("mailto:")) { + container.append(linkString); + string = string.substring(linkIndex + linkString.length, string.length); + continue; + } + + var title = linkString; + var realURL = linkString.startsWith("www.") ? "http://" + linkString : linkString; + var lineColumnMatch = lineColumnRegEx.exec(realURL); + if (lineColumnMatch) + realURL = realURL.substring(0, realURL.length - lineColumnMatch[0].length); + + var lineNumber; + if (lineColumnMatch) + lineNumber = parseInt(lineColumnMatch[1]) - 1; + + var linkNode = linkifier(title, realURL, lineNumber); + container.appendChild(linkNode); + string = string.substring(linkIndex + linkString.length, string.length); + } + + if (string) + container.append(string); + + return container; +}; + +WebInspector.linkifyStringAsFragment = function(string) +{ + function linkifier(title, url, lineNumber) + { + var urlNode = WebInspector.linkifyURLAsNode(url, title, undefined); + if (lineNumber !== undefined) + urlNode.lineNumber = lineNumber; + + return urlNode; + } + + return WebInspector.linkifyStringAsFragmentWithCustomLinkifier(string, linkifier); +}; + +WebInspector.createResourceLink = function(resource, className) +{ + function handleClick(event) + { + event.stopPropagation(); + event.preventDefault(); + + WebInspector.showRepresentedObject(resource); + } + + let linkNode = document.createElement("a"); + linkNode.classList.add("resource-link", className); + linkNode.title = resource.url; + linkNode.textContent = (resource.urlComponents.lastPathComponent || resource.url).insertWordBreakCharacters(); + linkNode.addEventListener("click", handleClick.bind(this)); + return linkNode; +}; + +WebInspector._undoKeyboardShortcut = function(event) +{ + if (!this.isEditingAnyField() && !this.isEventTargetAnEditableField(event)) { + this.undo(); + event.preventDefault(); + } +}; + +WebInspector._redoKeyboardShortcut = function(event) +{ + if (!this.isEditingAnyField() && !this.isEventTargetAnEditableField(event)) { + this.redo(); + event.preventDefault(); + } +}; + +WebInspector.undo = function() +{ + DOMAgent.undo(); +}; + +WebInspector.redo = function() +{ + DOMAgent.redo(); +}; + +WebInspector.highlightRangesWithStyleClass = function(element, resultRanges, styleClass, changes) +{ + changes = changes || []; + var highlightNodes = []; + var lineText = element.textContent; + var ownerDocument = element.ownerDocument; + var textNodeSnapshot = ownerDocument.evaluate(".//text()", element, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); + + var snapshotLength = textNodeSnapshot.snapshotLength; + if (snapshotLength === 0) + return highlightNodes; + + var nodeRanges = []; + var rangeEndOffset = 0; + for (var i = 0; i < snapshotLength; ++i) { + var range = {}; + range.offset = rangeEndOffset; + range.length = textNodeSnapshot.snapshotItem(i).textContent.length; + rangeEndOffset = range.offset + range.length; + nodeRanges.push(range); + } + + var startIndex = 0; + for (var i = 0; i < resultRanges.length; ++i) { + var startOffset = resultRanges[i].offset; + var endOffset = startOffset + resultRanges[i].length; + + while (startIndex < snapshotLength && nodeRanges[startIndex].offset + nodeRanges[startIndex].length <= startOffset) + startIndex++; + var endIndex = startIndex; + while (endIndex < snapshotLength && nodeRanges[endIndex].offset + nodeRanges[endIndex].length < endOffset) + endIndex++; + if (endIndex === snapshotLength) + break; + + var highlightNode = ownerDocument.createElement("span"); + highlightNode.className = styleClass; + highlightNode.textContent = lineText.substring(startOffset, endOffset); + + var lastTextNode = textNodeSnapshot.snapshotItem(endIndex); + var lastText = lastTextNode.textContent; + lastTextNode.textContent = lastText.substring(endOffset - nodeRanges[endIndex].offset); + changes.push({node: lastTextNode, type: "changed", oldText: lastText, newText: lastTextNode.textContent}); + + if (startIndex === endIndex) { + lastTextNode.parentElement.insertBefore(highlightNode, lastTextNode); + changes.push({node: highlightNode, type: "added", nextSibling: lastTextNode, parent: lastTextNode.parentElement}); + highlightNodes.push(highlightNode); + + var prefixNode = ownerDocument.createTextNode(lastText.substring(0, startOffset - nodeRanges[startIndex].offset)); + lastTextNode.parentElement.insertBefore(prefixNode, highlightNode); + changes.push({node: prefixNode, type: "added", nextSibling: highlightNode, parent: lastTextNode.parentElement}); + } else { + var firstTextNode = textNodeSnapshot.snapshotItem(startIndex); + var firstText = firstTextNode.textContent; + var anchorElement = firstTextNode.nextSibling; + + firstTextNode.parentElement.insertBefore(highlightNode, anchorElement); + changes.push({node: highlightNode, type: "added", nextSibling: anchorElement, parent: firstTextNode.parentElement}); + highlightNodes.push(highlightNode); + + firstTextNode.textContent = firstText.substring(0, startOffset - nodeRanges[startIndex].offset); + changes.push({node: firstTextNode, type: "changed", oldText: firstText, newText: firstTextNode.textContent}); + + for (var j = startIndex + 1; j < endIndex; j++) { + var textNode = textNodeSnapshot.snapshotItem(j); + var text = textNode.textContent; + textNode.textContent = ""; + changes.push({node: textNode, type: "changed", oldText: text, newText: textNode.textContent}); + } + } + startIndex = endIndex; + nodeRanges[startIndex].offset = endOffset; + nodeRanges[startIndex].length = lastTextNode.textContent.length; + + } + return highlightNodes; +}; + +WebInspector.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.archiveMainFrame = function() +{ + this._downloadingPage = true; + this._updateDownloadToolbarButton(); + + PageAgent.archive((error, data) => { + this._downloadingPage = false; + this._updateDownloadToolbarButton(); + + if (error) + return; + + let mainFrame = WebInspector.frameResourceManager.mainFrame; + let archiveName = mainFrame.mainResource.urlComponents.host || mainFrame.mainResource.displayName || "Archive"; + let url = "web-inspector:///" + encodeURI(archiveName) + ".webarchive"; + + InspectorFrontendHost.save(url, data, true, true); + }); +}; + +WebInspector.canArchiveMainFrame = function() +{ + // COMPATIBILITY (iOS 7): Page.archive did not exist yet. + if (!PageAgent.archive || this.debuggableType !== WebInspector.DebuggableType.Web) + return false; + + if (!WebInspector.frameResourceManager.mainFrame || !WebInspector.frameResourceManager.mainFrame.mainResource) + return false; + + return WebInspector.Resource.typeFromMIMEType(WebInspector.frameResourceManager.mainFrame.mainResource.mimeType) === WebInspector.Resource.Type.Document; +}; + +WebInspector.addWindowKeydownListener = function(listener) +{ + if (typeof listener.handleKeydownEvent !== "function") + return; + + this._windowKeydownListeners.push(listener); + + this._updateWindowKeydownListener(); +}; + +WebInspector.removeWindowKeydownListener = function(listener) +{ + this._windowKeydownListeners.remove(listener); + + this._updateWindowKeydownListener(); +}; + +WebInspector._updateWindowKeydownListener = function() +{ + if (this._windowKeydownListeners.length === 1) + window.addEventListener("keydown", WebInspector._sharedWindowKeydownListener, true); + else if (!this._windowKeydownListeners.length) + window.removeEventListener("keydown", WebInspector._sharedWindowKeydownListener, true); +}; + +WebInspector._sharedWindowKeydownListener = function(event) +{ + for (var i = WebInspector._windowKeydownListeners.length - 1; i >= 0; --i) { + if (WebInspector._windowKeydownListeners[i].handleKeydownEvent(event)) { + event.stopImmediatePropagation(); + event.preventDefault(); + break; + } + } +}; + +WebInspector.reportInternalError = function(errorOrString, details={}) +{ + // The 'details' object includes additional information from the caller as free-form string keys and values. + // Each key and value will be shown in the uncaught exception reporter, console error message, or in + // a pre-filled bug report generated for this internal error. + + let error = (errorOrString instanceof Error) ? errorOrString : new Error(errorOrString); + error.details = details; + + // The error will be displayed in the Uncaught Exception Reporter sheet if DebugUI is enabled. + if (WebInspector.isDebugUIEnabled()) { + // This assert allows us to stop the debugger at an internal exception. It doesn't re-throw + // exceptions because the original exception would be lost through window.onerror. + // This workaround can be removed once is fixed. + console.assert(false, "An internal exception was thrown.", error); + handleInternalException(error); + } else + console.error(error); +}; + +Object.defineProperty(WebInspector, "targets", +{ + get() { return this.targetManager.targets; } +}); + +// Many places assume the main target because they cannot yet be +// used by reached by Worker debugging. Eventually, once all +// Worker domains have been implemented, all of these must be +// handled properly. +WebInspector.assumingMainTarget = function() +{ + return WebInspector.mainTarget; +}; + +// OpenResourceDialog delegate + +WebInspector.dialogWasDismissed = function(dialog) +{ + let representedObject = dialog.representedObject; + if (!representedObject) + return; + + WebInspector.showRepresentedObject(representedObject, dialog.cookie); +}; + +WebInspector.DockConfiguration = { + Right: "right", + Left: "left", + Bottom: "bottom", + Undocked: "undocked", +}; diff --git a/Source/WebInspectorUI/UserInterface/Base/Object.js b/Source/WebInspectorUI/UserInterface/Base/Object.js new file mode 100644 index 000000000..2a91983af --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Base/Object.js @@ -0,0 +1,229 @@ +/* + * Copyright (C) 2008, 2013 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.Object = class WebInspectorObject +{ + constructor() + { + this._listeners = null; + } + + // Static + + static addEventListener(eventType, listener, thisObject) + { + thisObject = thisObject || null; + + console.assert(eventType, "Object.addEventListener: invalid event type ", eventType, "(listener: ", listener, "thisObject: ", thisObject, ")"); + if (!eventType) + return null; + + console.assert(listener, "Object.addEventListener: invalid listener ", listener, "(event type: ", eventType, "thisObject: ", thisObject, ")"); + if (!listener) + return null; + + if (!this._listeners) + this._listeners = new Map(); + + let listenersTable = this._listeners.get(eventType); + if (!listenersTable) { + listenersTable = new ListMultimap(); + this._listeners.set(eventType, listenersTable); + } + + listenersTable.add(thisObject, listener); + return listener; + } + + static singleFireEventListener(eventType, listener, thisObject) + { + let wrappedCallback = function() { + this.removeEventListener(eventType, wrappedCallback, null); + listener.apply(thisObject, arguments); + }.bind(this); + + this.addEventListener(eventType, wrappedCallback, null); + return wrappedCallback; + } + + static removeEventListener(eventType, listener, thisObject) + { + eventType = eventType || null; + listener = listener || null; + thisObject = thisObject || null; + + if (!this._listeners) + return; + + if (thisObject && !eventType) { + this._listeners.forEach(function(listenersTable) { + let listenerPairs = listenersTable.toArray(); + for (let i = 0, length = listenerPairs.length; i < length; ++i) { + let existingThisObject = listenerPairs[i][0]; + if (existingThisObject === thisObject) + listenersTable.deleteAll(existingThisObject); + } + }); + + return; + } + + let listenersTable = this._listeners.get(eventType); + if (!listenersTable || listenersTable.size === 0) + return; + + let didDelete = listenersTable.delete(thisObject, listener); + console.assert(didDelete, "removeEventListener cannot remove " + eventType.toString() + " because it doesn't exist."); + } + + static awaitEvent(eventType) + { + let wrapper = new WebInspector.WrappedPromise; + this.singleFireEventListener(eventType, (event) => wrapper.resolve(event)); + return wrapper.promise; + } + + // Only used by tests. + static hasEventListeners(eventType) + { + if (!this._listeners) + return false; + + let listenersTable = this._listeners.get(eventType); + return listenersTable && listenersTable.size > 0; + } + + // This should only be used within regression tests to detect leaks. + static retainedObjectsWithPrototype(proto) + { + let results = new Set; + + if (this._listeners) { + this._listeners.forEach(function(listenersTable, eventType) { + listenersTable.forEach(function(pair) { + let thisObject = pair[0]; + if (thisObject instanceof proto) + results.add(thisObject); + }); + }); + } + + return results; + } + + // Public + + addEventListener() { return WebInspector.Object.addEventListener.apply(this, arguments); } + singleFireEventListener() { return WebInspector.Object.singleFireEventListener.apply(this, arguments); } + removeEventListener() { return WebInspector.Object.removeEventListener.apply(this, arguments); } + awaitEvent() { return WebInspector.Object.awaitEvent.apply(this, arguments); } + hasEventListeners() { return WebInspector.Object.hasEventListeners.apply(this, arguments); } + retainedObjectsWithPrototype() { return WebInspector.Object.retainedObjectsWithPrototype.apply(this, arguments); } + + dispatchEventToListeners(eventType, eventData) + { + let event = new WebInspector.Event(this, eventType, eventData); + + function dispatch(object) + { + if (!object || event._stoppedPropagation) + return; + + let listenerTypesMap = object._listeners; + if (!listenerTypesMap || !object.hasOwnProperty("_listeners")) + return; + + console.assert(listenerTypesMap instanceof Map); + + let listenersTable = listenerTypesMap.get(eventType); + if (!listenersTable) + return; + + // Make a copy with slice so mutations during the loop doesn't affect us. + let listeners = listenersTable.toArray(); + + // Iterate over the listeners and call them. Stop if stopPropagation is called. + for (let i = 0, length = listeners.length; i < length; ++i) { + let [thisObject, listener] = listeners[i]; + listener.call(thisObject, event); + if (event._stoppedPropagation) + break; + } + } + + // Dispatch to listeners of this specific object. + dispatch(this); + + // Allow propagation again so listeners on the constructor always have a crack at the event. + event._stoppedPropagation = false; + + // Dispatch to listeners on all constructors up the prototype chain, including the immediate constructor. + let constructor = this.constructor; + while (constructor) { + dispatch(constructor); + + if (!constructor.prototype.__proto__) + break; + + constructor = constructor.prototype.__proto__.constructor; + } + + return event.defaultPrevented; + } +}; + +WebInspector.Event = class Event +{ + constructor(target, type, data) + { + this.target = target; + this.type = type; + this.data = data; + this.defaultPrevented = false; + this._stoppedPropagation = false; + } + + stopPropagation() + { + this._stoppedPropagation = true; + } + + preventDefault() + { + this.defaultPrevented = true; + } +}; + +WebInspector.notifications = new WebInspector.Object; + +WebInspector.Notification = { + GlobalModifierKeysDidChange: "global-modifiers-did-change", + PageArchiveStarted: "page-archive-started", + PageArchiveEnded: "page-archive-ended", + ExtraDomainsActivated: "extra-domains-activated", + TabTypesChanged: "tab-types-changed", + DebugUIEnabledDidChange: "debug-ui-enabled-did-change", + VisibilityStateDidChange: "visibility-state-did-change", +}; diff --git a/Source/WebInspectorUI/UserInterface/Base/Platform.js b/Source/WebInspectorUI/UserInterface/Base/Platform.js new file mode 100644 index 000000000..65764ec7d --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Base/Platform.js @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.Platform = { + name: InspectorFrontendHost.platform(), + isNightlyBuild: false, + version: { + base: 0, + release: 0, + name: "" + } +}; + +(function () { + // Check for a nightly build by looking for a plus in the version number and a small number of stylesheets (indicating combined resources). + var versionMatch = / AppleWebKit\/([^ ]+)/.exec(navigator.userAgent); + if (versionMatch && versionMatch[1].indexOf("+") !== -1 && document.styleSheets.length < 10) + WebInspector.Platform.isNightlyBuild = true; + + var osVersionMatch = / Mac OS X (\d+)_(\d+)/.exec(navigator.appVersion); + if (osVersionMatch && osVersionMatch[1] === "10") { + WebInspector.Platform.version.base = 10; + WebInspector.Platform.version.release = parseInt(osVersionMatch[2]); + switch (osVersionMatch[2]) { + case "12": + WebInspector.Platform.version.name = "sierra"; + break; + case "11": + WebInspector.Platform.version.name = "el-capitan"; + break; + case "10": + WebInspector.Platform.version.name = "yosemite"; + break; + default: + WebInspector.Platform.version.name = "unknown-mac"; + break; + } + } +})(); diff --git a/Source/WebInspectorUI/UserInterface/Base/Setting.js b/Source/WebInspectorUI/UserInterface/Base/Setting.js new file mode 100644 index 000000000..257524e3f --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Base/Setting.js @@ -0,0 +1,118 @@ +/* + * Copyright (C) 2009 Google Inc. All rights reserved. + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.Setting = class Setting extends WebInspector.Object +{ + constructor(name, defaultValue) + { + super(); + + this._name = name; + + let inspectionLevel = InspectorFrontendHost ? InspectorFrontendHost.inspectionLevel() : 1; + let levelString = inspectionLevel > 1 ? "-" + inspectionLevel : ""; + this._localStorageKey = `com.apple.WebInspector${levelString}.${name}`; + this._defaultValue = defaultValue; + } + + // Public + + get name() + { + return this._name; + } + + get value() + { + if ("_value" in this) + return this._value; + + // Make a copy of the default value so changes to object values don't modify the default value. + this._value = JSON.parse(JSON.stringify(this._defaultValue)); + + if (!window.InspectorTest && window.localStorage && this._localStorageKey in window.localStorage) { + try { + this._value = JSON.parse(window.localStorage[this._localStorageKey]); + } catch (e) { + delete window.localStorage[this._localStorageKey]; + } + } + + return this._value; + } + + set value(value) + { + if (this._value === value) + return; + + this._value = value; + + if (!window.InspectorTest && window.localStorage) { + try { + // Use Object.shallowEqual to properly compare objects. + if (Object.shallowEqual(this._value, this._defaultValue)) + delete window.localStorage[this._localStorageKey]; + else + window.localStorage[this._localStorageKey] = JSON.stringify(this._value); + } catch (e) { + console.error("Error saving setting with name: " + this._name); + } + } + + this.dispatchEventToListeners(WebInspector.Setting.Event.Changed, this._value, {name: this._name}); + } + + reset() + { + // Make a copy of the default value so changes to object values don't modify the default value. + this.value = JSON.parse(JSON.stringify(this._defaultValue)); + } +}; + +WebInspector.Setting.Event = { + Changed: "setting-changed" +}; + +WebInspector.settings = { + enableLineWrapping: new WebInspector.Setting("enable-line-wrapping", false), + indentUnit: new WebInspector.Setting("indent-unit", 4), + tabSize: new WebInspector.Setting("tab-size", 4), + indentWithTabs: new WebInspector.Setting("indent-with-tabs", false), + showWhitespaceCharacters: new WebInspector.Setting("show-whitespace-characters", false), + showInvalidCharacters: new WebInspector.Setting("show-invalid-characters", false), + clearLogOnNavigate: new WebInspector.Setting("clear-log-on-navigate", true), + clearNetworkOnNavigate: new WebInspector.Setting("clear-network-on-navigate", true), + zoomFactor: new WebInspector.Setting("zoom-factor", 1), + // FIXME: change initial value to 'system' once we are happy with RTL support. + // This will cause Web Inspector to use the system user interface layout direction. + layoutDirection: new WebInspector.Setting("layout-direction", "ltr"), +}; diff --git a/Source/WebInspectorUI/UserInterface/Base/URLUtilities.js b/Source/WebInspectorUI/UserInterface/Base/URLUtilities.js new file mode 100644 index 000000000..e3935f504 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Base/URLUtilities.js @@ -0,0 +1,265 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +// FIXME: Web Inspector: Use URL constructor to better handle all kinds of URLs + +function removeURLFragment(url) +{ + var hashIndex = url.indexOf("#"); + if (hashIndex >= 0) + return url.substring(0, hashIndex); + return url; +} + +function relativePath(path, basePath) +{ + console.assert(path.charAt(0) === "/"); + console.assert(basePath.charAt(0) === "/"); + + var pathComponents = path.split("/"); + var baseComponents = basePath.replace(/\/$/, "").split("/"); + var finalComponents = []; + + var index = 1; + for (; index < pathComponents.length && index < baseComponents.length; ++index) { + if (pathComponents[index] !== baseComponents[index]) + break; + } + + for (var i = index; i < baseComponents.length; ++i) + finalComponents.push(".."); + + for (var i = index; i < pathComponents.length; ++i) + finalComponents.push(pathComponents[i]); + + return finalComponents.join("/"); +} + +function parseSecurityOrigin(securityOrigin) +{ + securityOrigin = securityOrigin ? securityOrigin.trim() : ""; + + var match = securityOrigin.match(/^([^:]+):\/\/([^\/:]*)(?::([\d]+))?$/i); + if (!match) + return {scheme: null, host: null, port: null}; + + var scheme = match[1].toLowerCase(); + var host = match[2].toLowerCase(); + var port = Number(match[3]) || null; + + return {scheme, host, port}; +} + +function parseDataURL(url) +{ + if (!url.startsWith("data:")) + return null; + + // data:[][;charset=][;base64], + let match = url.match(/^data:([^;,]*)?(?:;charset=([^;,]*?))?(;base64)?,(.*)$/); + if (!match) + return null; + + let scheme = "data"; + let mimeType = match[1] || "text/plain"; + let charset = match[2] || "US-ASCII"; + let base64 = !!match[3]; + let data = decodeURIComponent(match[4]); + + return {scheme, mimeType, charset, base64, data}; +} + +function parseURL(url) +{ + url = url ? url.trim() : ""; + + if (url.startsWith("data:")) + return {scheme: "data", host: null, port: null, path: null, queryString: null, fragment: null, lastPathComponent: null}; + + var match = url.match(/^([^\/:]+):\/\/([^\/#:]*)(?::([\d]+))?(?:(\/[^#]*)?(?:#(.*))?)?$/i); + if (!match) + return {scheme: null, host: null, port: null, path: null, queryString: null, fragment: null, lastPathComponent: null}; + + var scheme = match[1].toLowerCase(); + var host = match[2].toLowerCase(); + var port = Number(match[3]) || null; + var wholePath = match[4] || null; + var fragment = match[5] || null; + var path = wholePath; + var queryString = null; + + // Split the path and the query string. + if (wholePath) { + var indexOfQuery = wholePath.indexOf("?"); + if (indexOfQuery !== -1) { + path = wholePath.substring(0, indexOfQuery); + queryString = wholePath.substring(indexOfQuery + 1); + } + path = resolveDotsInPath(path); + } + + // Find last path component. + var lastPathComponent = null; + if (path && path !== "/") { + // Skip the trailing slash if there is one. + var endOffset = path[path.length - 1] === "/" ? 1 : 0; + var lastSlashIndex = path.lastIndexOf("/", path.length - 1 - endOffset); + if (lastSlashIndex !== -1) + lastPathComponent = path.substring(lastSlashIndex + 1, path.length - endOffset); + } + + return {scheme, host, port, path, queryString, fragment, lastPathComponent}; +} + +function absoluteURL(partialURL, baseURL) +{ + partialURL = partialURL ? partialURL.trim() : ""; + + // Return data and javascript URLs as-is. + if (partialURL.startsWith("data:") || partialURL.startsWith("javascript:") || partialURL.startsWith("mailto:")) + return partialURL; + + // If the URL has a scheme it is already a full URL, so return it. + if (parseURL(partialURL).scheme) + return partialURL; + + // If there is no partial URL, just return the base URL. + if (!partialURL) + return baseURL || null; + + var baseURLComponents = parseURL(baseURL); + + // The base URL needs to be an absolute URL. Return null if it isn't. + if (!baseURLComponents.scheme) + return null; + + // A URL that starts with "//" is a full URL without the scheme. Use the base URL scheme. + if (partialURL[0] === "/" && partialURL[1] === "/") + return baseURLComponents.scheme + ":" + partialURL; + + // The path can be null for URLs that have just a scheme and host (like "http://apple.com"). So make the path be "/". + if (!baseURLComponents.path) + baseURLComponents.path = "/"; + + // Generate the base URL prefix that is used in the rest of the cases. + var baseURLPrefix = baseURLComponents.scheme + "://" + baseURLComponents.host + (baseURLComponents.port ? (":" + baseURLComponents.port) : ""); + + // A URL that starts with "?" is just a query string that gets applied to the base URL (replacing the base URL query string and fragment). + if (partialURL[0] === "?") + return baseURLPrefix + baseURLComponents.path + partialURL; + + // A URL that starts with "/" is an absolute path that gets applied to the base URL (replacing the base URL path, query string and fragment). + if (partialURL[0] === "/") + return baseURLPrefix + resolveDotsInPath(partialURL); + + // A URL that starts with "#" is just a fragment that gets applied to the base URL (replacing the base URL fragment, maintaining the query string). + if (partialURL[0] === "#") { + let queryStringComponent = baseURLComponents.queryString ? "?" + baseURLComponents.queryString : ""; + return baseURLPrefix + baseURLComponents.path + queryStringComponent + partialURL; + } + + // Generate the base path that is used in the final case by removing everything after the last "/" from the base URL's path. + var basePath = baseURLComponents.path.substring(0, baseURLComponents.path.lastIndexOf("/")) + "/"; + return baseURLPrefix + resolveDotsInPath(basePath + partialURL); +} + +function parseLocationQueryParameters(arrayResult) +{ + // The first character is always the "?". + return parseQueryString(window.location.search.substring(1), arrayResult); +} + +function parseQueryString(queryString, arrayResult) +{ + if (!queryString) + return arrayResult ? [] : {}; + + function decode(string) + { + try { + // Replace "+" with " " then decode percent encoded values. + return decodeURIComponent(string.replace(/\+/g, " ")); + } catch (e) { + return string; + } + } + + var parameters = arrayResult ? [] : {}; + var parameterStrings = queryString.split("&"); + for (var i = 0; i < parameterStrings.length; ++i) { + var pair = parameterStrings[i].split("=").map(decode); + if (arrayResult) + parameters.push({name: pair[0], value: pair[1]}); + else + parameters[pair[0]] = pair[1]; + } + + return parameters; +} + +WebInspector.displayNameForURL = function(url, urlComponents) +{ + if (url.startsWith("data:")) + return WebInspector.truncateURL(url); + + if (!urlComponents) + urlComponents = parseURL(url); + + var displayName; + try { + displayName = decodeURIComponent(urlComponents.lastPathComponent || ""); + } catch (e) { + displayName = urlComponents.lastPathComponent; + } + + return displayName || WebInspector.displayNameForHost(urlComponents.host) || url; +}; + +WebInspector.truncateURL = function(url, multiline = false, dataURIMaxSize = 6) +{ + if (!url.startsWith("data:")) + return url; + + const dataIndex = url.indexOf(",") + 1; + let header = url.slice(0, dataIndex); + if (multiline) + header += "\n"; + + const data = url.slice(dataIndex); + if (data.length < dataURIMaxSize) + return header + data; + + const firstChunk = data.slice(0, Math.ceil(dataURIMaxSize / 2)); + const ellipsis = "\u2026"; + const middleChunk = multiline ? `\n${ellipsis}\n` : ellipsis; + const lastChunk = data.slice(-Math.floor(dataURIMaxSize / 2)); + return header + firstChunk + middleChunk + lastChunk; +}; + +WebInspector.displayNameForHost = function(host) +{ + // FIXME : This should decode punycode hostnames. + return host; +}; diff --git a/Source/WebInspectorUI/UserInterface/Base/Utilities.js b/Source/WebInspectorUI/UserInterface/Base/Utilities.js new file mode 100644 index 000000000..06c2f1cb5 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Base/Utilities.js @@ -0,0 +1,1509 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +var emDash = "\u2014"; +var enDash = "\u2013"; +var figureDash = "\u2012"; +var ellipsis = "\u2026"; + +Object.defineProperty(Object, "shallowCopy", +{ + value: function(object) + { + // Make a new object and copy all the key/values. The values are not copied. + var copy = {}; + var keys = Object.keys(object); + for (var i = 0; i < keys.length; ++i) + copy[keys[i]] = object[keys[i]]; + return copy; + } +}); + +Object.defineProperty(Object, "shallowEqual", +{ + value: function(a, b) + { + // Checks if two objects have the same top-level properties. + + // Only objects can proceed. + if (!(a instanceof Object) || !(b instanceof Object)) + return false; + + // Check for strict equality in case they are the same object. + if (a === b) + return true; + + // Use an optimized version of shallowEqual for arrays. + if (Array.isArray(a) && Array.isArray(b)) + return Array.shallowEqual(a, b); + + if (a.constructor !== b.constructor) + return false; + + var aKeys = Object.keys(a); + var bKeys = Object.keys(b); + + // Check that each object has the same number of keys. + if (aKeys.length !== bKeys.length) + return false; + + // Check if all the keys and their values are equal. + for (var i = 0; i < aKeys.length; ++i) { + // Check that b has the same key as a. + if (!(aKeys[i] in b)) + return false; + + // Check that the values are strict equal since this is only + // a shallow check, not a recursive one. + if (a[aKeys[i]] !== b[aKeys[i]]) + return false; + } + + return true; + } +}); + +Object.defineProperty(Object, "shallowMerge", +{ + value(a, b) + { + let result = Object.shallowCopy(a); + let keys = Object.keys(b); + for (let i = 0; i < keys.length; ++i) { + console.assert(!result.hasOwnProperty(keys[i]) || result[keys[i]] === b[keys[i]], keys[i]); + result[keys[i]] = b[keys[i]]; + } + return result; + } +}); + +Object.defineProperty(Object.prototype, "valueForCaseInsensitiveKey", +{ + value: function(key) + { + if (this.hasOwnProperty(key)) + return this[key]; + + var lowerCaseKey = key.toLowerCase(); + for (var currentKey in this) { + if (currentKey.toLowerCase() === lowerCaseKey) + return this[currentKey]; + } + + return undefined; + } +}); + +Object.defineProperty(Map, "fromObject", +{ + value: function(object) + { + let map = new Map; + for (let key in object) + map.set(key, object[key]); + return map; + } +}); + +Object.defineProperty(Map.prototype, "take", +{ + value: function(key) + { + var deletedValue = this.get(key); + this.delete(key); + return deletedValue; + } +}); + +Object.defineProperty(Node.prototype, "enclosingNodeOrSelfWithClass", +{ + value: function(className) + { + for (var node = this; node && node !== this.ownerDocument; node = node.parentNode) + if (node.nodeType === Node.ELEMENT_NODE && node.classList.contains(className)) + return node; + return null; + } +}); + +Object.defineProperty(Node.prototype, "enclosingNodeOrSelfWithNodeNameInArray", +{ + value: function(nameArray) + { + var lowerCaseNameArray = nameArray.map(function(name) { return name.toLowerCase(); }); + for (var node = this; node && node !== this.ownerDocument; node = node.parentNode) { + for (var i = 0; i < nameArray.length; ++i) { + if (node.nodeName.toLowerCase() === lowerCaseNameArray[i]) + return node; + } + } + + return null; + } +}); + +Object.defineProperty(Node.prototype, "enclosingNodeOrSelfWithNodeName", +{ + value: function(nodeName) + { + return this.enclosingNodeOrSelfWithNodeNameInArray([nodeName]); + } +}); + +Object.defineProperty(Node.prototype, "isAncestor", +{ + value: function(node) + { + if (!node) + return false; + + var currentNode = node.parentNode; + while (currentNode) { + if (this === currentNode) + return true; + currentNode = currentNode.parentNode; + } + + return false; + } +}); + +Object.defineProperty(Node.prototype, "isDescendant", +{ + value: function(descendant) + { + return !!descendant && descendant.isAncestor(this); + } +}); + + +Object.defineProperty(Node.prototype, "isSelfOrAncestor", +{ + value: function(node) + { + return !!node && (node === this || this.isAncestor(node)); + } +}); + + +Object.defineProperty(Node.prototype, "isSelfOrDescendant", +{ + value: function(node) + { + return !!node && (node === this || this.isDescendant(node)); + } +}); + +Object.defineProperty(Node.prototype, "traverseNextNode", +{ + value: function(stayWithin) + { + var node = this.firstChild; + if (node) + return node; + + if (stayWithin && this === stayWithin) + return null; + + node = this.nextSibling; + if (node) + return node; + + node = this; + while (node && !node.nextSibling && (!stayWithin || !node.parentNode || node.parentNode !== stayWithin)) + node = node.parentNode; + if (!node) + return null; + + return node.nextSibling; + } +}); + +Object.defineProperty(Node.prototype, "traversePreviousNode", +{ + value: function(stayWithin) + { + if (stayWithin && this === stayWithin) + return null; + var node = this.previousSibling; + while (node && node.lastChild) + node = node.lastChild; + if (node) + return node; + return this.parentNode; + } +}); + + +Object.defineProperty(Node.prototype, "rangeOfWord", +{ + value: 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; + + } +}); + +Object.defineProperty(Element.prototype, "realOffsetWidth", +{ + get: function() + { + return this.getBoundingClientRect().width; + } +}); + +Object.defineProperty(Element.prototype, "realOffsetHeight", +{ + get: function() + { + return this.getBoundingClientRect().height; + } +}); + +Object.defineProperty(Element.prototype, "totalOffsetLeft", +{ + get: function() + { + return this.getBoundingClientRect().left; + } +}); + +Object.defineProperty(Element.prototype, "totalOffsetTop", +{ + get: function() + { + return this.getBoundingClientRect().top; + } +}); + +Object.defineProperty(Element.prototype, "removeChildren", +{ + value: function() + { + // This has been tested to be the fastest removal method. + if (this.firstChild) + this.textContent = ""; + } +}); + +Object.defineProperty(Element.prototype, "isInsertionCaretInside", +{ + value: function() + { + var selection = window.getSelection(); + if (!selection.rangeCount || !selection.isCollapsed) + return false; + var selectionRange = selection.getRangeAt(0); + return selectionRange.startContainer === this || selectionRange.startContainer.isDescendant(this); + } +}); + +Object.defineProperty(Element.prototype, "removeMatchingStyleClasses", +{ + value: function(classNameRegex) + { + var regex = new RegExp("(^|\\s+)" + classNameRegex + "($|\\s+)"); + if (regex.test(this.className)) + this.className = this.className.replace(regex, " "); + } +}); + +Object.defineProperty(Element.prototype, "createChild", +{ + value: function(elementName, className) + { + var element = this.ownerDocument.createElement(elementName); + if (className) + element.className = className; + this.appendChild(element); + return element; + } +}); + +Object.defineProperty(Element.prototype, "isScrolledToBottom", +{ + value: function() + { + // This code works only for 0-width border + return this.scrollTop + this.clientHeight === this.scrollHeight; + } +}); + +Object.defineProperty(Element.prototype, "recalculateStyles", +{ + value: function() + { + this.ownerDocument.defaultView.getComputedStyle(this); + } +}); + +Object.defineProperty(DocumentFragment.prototype, "createChild", +{ + value: Element.prototype.createChild +}); + +Object.defineProperty(Array, "shallowEqual", +{ + value: function(a, b) + { + if (!Array.isArray(a) || !Array.isArray(b)) + return false; + + if (a === b) + return true; + + let length = a.length; + + if (length !== b.length) + return false; + + for (let i = 0; i < length; ++i) { + if (a[i] === b[i]) + continue; + + if (!Object.shallowEqual(a[i], b[i])) + return false; + } + + return true; + } +}); + +Object.defineProperty(Array.prototype, "lastValue", +{ + get: function() + { + if (!this.length) + return undefined; + return this[this.length - 1]; + } +}); + +Object.defineProperty(Array.prototype, "remove", +{ + value: function(value, onlyFirst) + { + for (var i = this.length - 1; i >= 0; --i) { + if (this[i] === value) { + this.splice(i, 1); + if (onlyFirst) + return; + } + } + } +}); + +Object.defineProperty(Array.prototype, "toggleIncludes", +{ + value: function(value, force) + { + let exists = this.includes(value); + if (exists === !!force) + return; + + if (exists) + this.remove(value); + else + this.push(value); + } +}); + +Object.defineProperty(Array.prototype, "insertAtIndex", +{ + value: function(value, index) + { + this.splice(index, 0, value); + } +}); + +Object.defineProperty(Array.prototype, "keySet", +{ + value: function() + { + let keys = Object.create(null); + for (var i = 0; i < this.length; ++i) + keys[this[i]] = true; + return keys; + } +}); + +Object.defineProperty(Array.prototype, "partition", +{ + value: function(callback) + { + let positive = []; + let negative = []; + for (let i = 0; i < this.length; ++i) { + let value = this[i]; + if (callback(value)) + positive.push(value); + else + negative.push(value); + } + return [positive, negative]; + } +}); + +Object.defineProperty(String.prototype, "isLowerCase", +{ + value: function() + { + return String(this) === this.toLowerCase(); + } +}); + +Object.defineProperty(String.prototype, "isUpperCase", +{ + value: function() + { + return String(this) === this.toUpperCase(); + } +}); + +Object.defineProperty(String.prototype, "trimMiddle", +{ + value: function(maxLength) + { + if (this.length <= maxLength) + return this; + var leftHalf = maxLength >> 1; + var rightHalf = maxLength - leftHalf - 1; + return this.substr(0, leftHalf) + ellipsis + this.substr(this.length - rightHalf, rightHalf); + } +}); + +Object.defineProperty(String.prototype, "trimEnd", +{ + value: function(maxLength) + { + if (this.length <= maxLength) + return this; + return this.substr(0, maxLength - 1) + ellipsis; + } +}); + +Object.defineProperty(String.prototype, "truncate", +{ + value: function(maxLength) + { + "use strict"; + + if (this.length <= maxLength) + return this; + + let clipped = this.slice(0, maxLength); + let indexOfLastWhitespace = clipped.search(/\s\S*$/); + if (indexOfLastWhitespace > Math.floor(maxLength / 2)) + clipped = clipped.slice(0, indexOfLastWhitespace - 1); + + return clipped + ellipsis; + } +}); + +Object.defineProperty(String.prototype, "collapseWhitespace", +{ + value: function() + { + return this.replace(/[\s\xA0]+/g, " "); + } +}); + +Object.defineProperty(String.prototype, "removeWhitespace", +{ + value: function() + { + return this.replace(/[\s\xA0]+/g, ""); + } +}); + +Object.defineProperty(String.prototype, "escapeCharacters", +{ + value: 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 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; + } +}); + +Object.defineProperty(String.prototype, "escapeForRegExp", +{ + value: function() + { + return this.escapeCharacters("^[]{}()\\.$*+?|"); + } +}); + +Object.defineProperty(String.prototype, "capitalize", +{ + value: function() + { + return this.charAt(0).toUpperCase() + this.slice(1); + } +}); + +Object.defineProperty(String, "tokenizeFormatString", +{ + value: function(format) + { + var tokens = []; + var substitutionIndex = 0; + + function addStringToken(str) + { + tokens.push({type: "string", value: str}); + } + + function addSpecifierToken(specifier, precision, substitutionIndex) + { + tokens.push({type: "specifier", specifier, precision, substitutionIndex}); + } + + var index = 0; + for (var precentIndex = format.indexOf("%", index); precentIndex !== -1; precentIndex = format.indexOf("%", index)) { + addStringToken(format.substring(index, precentIndex)); + index = precentIndex + 1; + + if (format[index] === "%") { + addStringToken("%"); + ++index; + continue; + } + + if (!isNaN(format[index])) { + // The first character is a number, it might be a substitution index. + var number = parseInt(format.substring(index), 10); + while (!isNaN(format[index])) + ++index; + + // If the number is greater than zero and ends with a "$", + // then this is a substitution index. + if (number > 0 && format[index] === "$") { + substitutionIndex = (number - 1); + ++index; + } + } + + const defaultPrecision = 6; + + let precision = defaultPrecision; + if (format[index] === ".") { + // This is a precision specifier. If no digit follows the ".", + // then use the default precision of six digits (ISO C99 specification). + ++index; + + precision = parseInt(format.substring(index), 10); + if (isNaN(precision)) + precision = defaultPrecision; + + while (!isNaN(format[index])) + ++index; + } + + addSpecifierToken(format[index], precision, substitutionIndex); + + ++substitutionIndex; + ++index; + } + + addStringToken(format.substring(index)); + + return tokens; + } +}); + +Object.defineProperty(String.prototype, "hash", +{ + get: function() + { + // Matches the wtf/Hasher.h (SuperFastHash) algorithm. + + // Arbitrary start value to avoid mapping all 0's to all 0's. + const stringHashingStartValue = 0x9e3779b9; + + var result = stringHashingStartValue; + var pendingCharacter = null; + for (var i = 0; i < this.length; ++i) { + var currentCharacter = this[i].charCodeAt(0); + if (pendingCharacter === null) { + pendingCharacter = currentCharacter; + continue; + } + + result += pendingCharacter; + result = (result << 16) ^ ((currentCharacter << 11) ^ result); + result += result >> 11; + + pendingCharacter = null; + } + + // Handle the last character in odd length strings. + if (pendingCharacter !== null) { + result += pendingCharacter; + result ^= result << 11; + result += result >> 17; + } + + // Force "avalanching" of final 31 bits. + result ^= result << 3; + result += result >> 5; + result ^= result << 2; + result += result >> 15; + result ^= result << 10; + + // Prevent 0 and negative results. + return (0xffffffff + result + 1).toString(36); + } +}); + +Object.defineProperty(String, "standardFormatters", +{ + value: { + d: function(substitution) + { + return parseInt(substitution); + }, + + f: function(substitution, token) + { + let value = parseFloat(substitution); + if (isNaN(value)) + return NaN; + + let options = { + minimumFractionDigits: token.precision, + maximumFractionDigits: token.precision, + useGrouping: false + }; + return value.toLocaleString(undefined, options); + }, + + s: function(substitution) + { + return substitution; + } + } +}); + +Object.defineProperty(String, "format", +{ + value: function(format, substitutions, formatters, initialValue, append) + { + if (!format || !substitutions || !substitutions.length) + return {formattedResult: append(initialValue, format), unusedSubstitutions: substitutions}; + + function prettyFunctionName() + { + return "String.format(\"" + format + "\", \"" + Array.from(substitutions).join("\", \"") + "\")"; + } + + function warn(msg) + { + console.warn(prettyFunctionName() + ": " + msg); + } + + function error(msg) + { + console.error(prettyFunctionName() + ": " + msg); + } + + var result = initialValue; + var tokens = String.tokenizeFormatString(format); + 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) { + // If there are not enough substitutions for the current substitutionIndex + // just output the format specifier literally and move on. + 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)) { + // Encountered an unsupported format character, treat as a string. + 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}; + } +}); + +Object.defineProperty(String.prototype, "format", +{ + value: function() + { + return String.format(this, arguments, String.standardFormatters, "", function(a, b) { return a + b; }).formattedResult; + } +}); + +Object.defineProperty(String.prototype, "insertWordBreakCharacters", +{ + value: function() + { + // Add zero width spaces after characters that are good to break after. + // Otherwise a string with no spaces will not break and overflow its container. + // This is mainly used on URL strings, so the characters are tailored for URLs. + return this.replace(/([\/;:\)\]\}&?])/g, "$1\u200b"); + } +}); + +Object.defineProperty(String.prototype, "removeWordBreakCharacters", +{ + value: function() + { + // Undoes what insertWordBreakCharacters did. + return this.replace(/\u200b/g, ""); + } +}); + +Object.defineProperty(String.prototype, "getMatchingIndexes", +{ + value: function(needle) + { + var indexesOfNeedle = []; + var index = this.indexOf(needle); + + while (index >= 0) { + indexesOfNeedle.push(index); + index = this.indexOf(needle, index + 1); + } + + return indexesOfNeedle; + } +}); + +Object.defineProperty(String.prototype, "levenshteinDistance", +{ + value: function(s) + { + var m = this.length; + var n = s.length; + var d = new Array(m + 1); + + for (var i = 0; i <= m; ++i) { + d[i] = new Array(n + 1); + d[i][0] = i; + } + + for (var j = 0; j <= n; ++j) + d[0][j] = j; + + for (var j = 1; j <= n; ++j) { + for (var i = 1; i <= m; ++i) { + if (this[i - 1] === s[j - 1]) + d[i][j] = d[i - 1][j - 1]; + else { + var deletion = d[i - 1][j] + 1; + var insertion = d[i][j - 1] + 1; + var substitution = d[i - 1][j - 1] + 1; + d[i][j] = Math.min(deletion, insertion, substitution); + } + } + } + + return d[m][n]; + } +}); + +Object.defineProperty(String.prototype, "toCamelCase", +{ + value: function() + { + return this.toLowerCase().replace(/[^\w]+(\w)/g, (match, group) => group.toUpperCase()); + } +}); + +Object.defineProperty(String.prototype, "hasMatchingEscapedQuotes", +{ + value: function() + { + return /^\"(?:[^\"\\]|\\.)*\"$/.test(this) || /^\'(?:[^\'\\]|\\.)*\'$/.test(this); + } +}); + +Object.defineProperty(Math, "roundTo", +{ + value: function(num, step) + { + return Math.round(num / step) * step; + } +}); + +Object.defineProperty(Number, "constrain", +{ + value: function(num, min, max) + { + if (max < min) + return min; + + if (num < min) + num = min; + else if (num > max) + num = max; + return num; + } +}); + +Object.defineProperty(Number, "percentageString", +{ + value: function(fraction, precision = 1) + { + console.assert(fraction >= 0 && fraction <= 1); + return fraction.toLocaleString(undefined, {minimumFractionDigits: precision, style: "percent"}); + } +}); + +Object.defineProperty(Number, "secondsToMillisecondsString", +{ + value: function(seconds, higherResolution) + { + let ms = seconds * 1000; + + if (higherResolution) + return WebInspector.UIString("%.2fms").format(ms); + return WebInspector.UIString("%.1fms").format(ms); + } +}); + +Object.defineProperty(Number, "secondsToString", +{ + value: function(seconds, higherResolution) + { + let ms = seconds * 1000; + if (!ms) + return WebInspector.UIString("%.0fms").format(0); + + if (Math.abs(ms) < 10) { + if (higherResolution) + return WebInspector.UIString("%.3fms").format(ms); + return WebInspector.UIString("%.2fms").format(ms); + } + + if (Math.abs(ms) < 100) { + if (higherResolution) + return WebInspector.UIString("%.2fms").format(ms); + return WebInspector.UIString("%.1fms").format(ms); + } + + if (Math.abs(ms) < 1000) { + if (higherResolution) + return WebInspector.UIString("%.1fms").format(ms); + return WebInspector.UIString("%.0fms").format(ms); + } + + // Do not go over seconds when in high resolution mode. + if (higherResolution || Math.abs(seconds) < 60) + return WebInspector.UIString("%.2fs").format(seconds); + + let minutes = seconds / 60; + if (Math.abs(minutes) < 60) + return WebInspector.UIString("%.1fmin").format(minutes); + + let hours = minutes / 60; + if (Math.abs(hours) < 24) + return WebInspector.UIString("%.1fhrs").format(hours); + + let days = hours / 24; + return WebInspector.UIString("%.1f days").format(days); + } +}); + +Object.defineProperty(Number, "bytesToString", +{ + value: function(bytes, higherResolution) + { + if (higherResolution === undefined) + higherResolution = true; + + if (Math.abs(bytes) < 1024) + return WebInspector.UIString("%.0f B").format(bytes); + + let kilobytes = bytes / 1024; + if (Math.abs(kilobytes) < 1024) { + if (higherResolution || Math.abs(kilobytes) < 10) + return WebInspector.UIString("%.2f KB").format(kilobytes); + return WebInspector.UIString("%.1f KB").format(kilobytes); + } + + let megabytes = kilobytes / 1024; + if (higherResolution || Math.abs(megabytes) < 10) + return WebInspector.UIString("%.2f MB").format(megabytes); + return WebInspector.UIString("%.1f MB").format(megabytes); + } +}); + +Object.defineProperty(Number, "abbreviate", +{ + value: function(num) + { + if (num < 1000) + return num; + + if (num < 1000000) + return WebInspector.UIString("%.1fK").format(Math.round(num / 100) / 10); + + if (num < 1000000000) + return WebInspector.UIString("%.1fM").format(Math.round(num / 100000) / 10); + + return WebInspector.UIString("%.1fB").format(Math.round(num / 100000000) / 10); + } +}); + +Object.defineProperty(Number.prototype, "maxDecimals", +{ + value(decimals) + { + let power = 10 ** decimals; + return Math.round(this * power) / power; + } +}); + +Object.defineProperty(Uint32Array, "isLittleEndian", +{ + value: function() + { + if ("_isLittleEndian" in this) + return this._isLittleEndian; + + var buffer = new ArrayBuffer(4); + var longData = new Uint32Array(buffer); + var data = new Uint8Array(buffer); + + longData[0] = 0x0a0b0c0d; + + this._isLittleEndian = data[0] === 0x0d && data[1] === 0x0c && data[2] === 0x0b && data[3] === 0x0a; + + return this._isLittleEndian; + } +}); + +function isEmptyObject(object) +{ + for (var property in object) + return false; + return true; +} + +function isEnterKey(event) +{ + // Check if this is an IME event. + return event.keyCode !== 229 && event.keyIdentifier === "Enter"; +} + +function resolveDotsInPath(path) +{ + if (!path) + return path; + + if (path.indexOf("./") === -1) + return path; + + console.assert(path.charAt(0) === "/"); + + var result = []; + + var components = path.split("/"); + for (var i = 0; i < components.length; ++i) { + var component = components[i]; + + // Skip over "./". + if (component === ".") + continue; + + // Rewind one component for "../". + if (component === "..") { + if (result.length === 1) + continue; + result.pop(); + continue; + } + + result.push(component); + } + + return result.join("/"); +} + +function parseMIMEType(fullMimeType) +{ + if (!fullMimeType) + return {type: fullMimeType, boundary: null, encoding: null}; + + var typeParts = fullMimeType.split(/\s*;\s*/); + console.assert(typeParts.length >= 1); + + var type = typeParts[0]; + var boundary = null; + var encoding = null; + + for (var i = 1; i < typeParts.length; ++i) { + var subparts = typeParts[i].split(/\s*=\s*/); + if (subparts.length !== 2) + continue; + + if (subparts[0].toLowerCase() === "boundary") + boundary = subparts[1]; + else if (subparts[0].toLowerCase() === "charset") + encoding = subparts[1].replace("^\"|\"$", ""); // Trim quotes. + } + + return {type, boundary: boundary || null, encoding: encoding || null}; +} + +function simpleGlobStringToRegExp(globString, regExpFlags) +{ + // Only supports "*" globs. + + if (!globString) + return null; + + // Escape everything from String.prototype.escapeForRegExp except "*". + var regexString = globString.escapeCharacters("^[]{}()\\.$+?|"); + + // Unescape all doubly escaped backslashes in front of escaped asterisks. + // So "\\*" will become "\*" again, undoing escapeCharacters escaping of "\". + // This makes "\*" match a literal "*" instead of using the "*" for globbing. + regexString = regexString.replace(/\\\\\*/g, "\\*"); + + // The following regex doesn't match an asterisk that has a backslash in front. + // It also catches consecutive asterisks so they collapse down when replaced. + var unescapedAsteriskRegex = /(^|[^\\])\*+/g; + if (unescapedAsteriskRegex.test(globString)) { + // Replace all unescaped asterisks with ".*". + regexString = regexString.replace(unescapedAsteriskRegex, "$1.*"); + + // Match edge boundaries when there is an asterisk to better meet the expectations + // of the user. When someone types "*.js" they don't expect "foo.json" to match. They + // would only expect that if they type "*.js*". We use \b (instead of ^ and $) to allow + // matches inside paths or URLs, so "ba*.js" will match "foo/bar.js" but not "boo/bbar.js". + // When there isn't an asterisk the regexString is just a substring search. + regexString = "\\b" + regexString + "\\b"; + } + + return new RegExp(regexString, regExpFlags); +} + +Object.defineProperty(Array.prototype, "lowerBound", +{ + // Return index of the leftmost element that is equal or greater + // than the specimen object. If there's no such element (i.e. all + // elements are smaller than the specimen) returns array.length. + // The function works for sorted array. + value: function(object, comparator) + { + function defaultComparator(a, b) + { + return a - b; + } + comparator = comparator || defaultComparator; + var l = 0; + var r = 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", +{ + // Return index of the leftmost element that is greater + // than the specimen object. If there's no such element (i.e. all + // elements are smaller than the specimen) returns array.length. + // The function works for sorted array. + value: function(object, comparator) + { + function defaultComparator(a, b) + { + return a - b; + } + comparator = comparator || defaultComparator; + var l = 0; + var r = 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, "binaryIndexOf", +{ + value: function(value, comparator) + { + var index = this.lowerBound(value, comparator); + return index < this.length && comparator(value, this[index]) === 0 ? index : -1; + } +}); + +(function() { + // The `debounce` function lets you call any function on an object with a delay + // and if the function keeps getting called, the delay gets reset. Since `debounce` + // returns a Proxy, you can cache it and call multiple functions with the same delay. + + // Use: object.debounce(200).foo("Argument 1", "Argument 2") + // Note: The last call's arguments get used for the delayed call. + + const debounceTimeoutSymbol = Symbol("debounce-timeout"); + const debounceSoonProxySymbol = Symbol("debounce-soon-proxy"); + + Object.defineProperty(Object.prototype, "soon", + { + get: function() + { + if (!this[debounceSoonProxySymbol]) + this[debounceSoonProxySymbol] = this.debounce(0); + return this[debounceSoonProxySymbol]; + } + }); + + Object.defineProperty(Object.prototype, "debounce", + { + value: function(delay) + { + console.assert(delay >= 0); + + return new Proxy(this, { + get(target, property, receiver) { + return (...args) => { + let original = target[property]; + console.assert(typeof original === "function"); + + if (original[debounceTimeoutSymbol]) + clearTimeout(original[debounceTimeoutSymbol]); + + let performWork = () => { + original[debounceTimeoutSymbol] = undefined; + original.apply(target, args); + }; + + original[debounceTimeoutSymbol] = setTimeout(performWork, delay); + }; + } + }); + } + }); + + Object.defineProperty(Function.prototype, "cancelDebounce", + { + value: function() + { + if (!this[debounceTimeoutSymbol]) + return; + + clearTimeout(this[debounceTimeoutSymbol]); + this[debounceTimeoutSymbol] = undefined; + } + }); + + const requestAnimationFrameSymbol = Symbol("peform-on-animation-frame"); + const requestAnimationFrameProxySymbol = Symbol("perform-on-animation-frame-proxy"); + + Object.defineProperty(Object.prototype, "onNextFrame", + { + get: function() + { + if (!this[requestAnimationFrameProxySymbol]) { + this[requestAnimationFrameProxySymbol] = new Proxy(this, { + get(target, property, receiver) { + return (...args) => { + let original = target[property]; + console.assert(typeof original === "function"); + + if (original[requestAnimationFrameSymbol]) + return; + + let performWork = () => { + original[requestAnimationFrameSymbol] = undefined; + original.apply(target, args); + }; + + original[requestAnimationFrameSymbol] = requestAnimationFrame(performWork); + }; + } + }); + } + + return this[requestAnimationFrameProxySymbol]; + } + }); +})(); + +function appendWebInspectorSourceURL(string) +{ + if (string.includes("//# sourceURL")) + return string; + return "\n//# sourceURL=__WebInspectorInternal__\n" + string; +} + +function appendWebInspectorConsoleEvaluationSourceURL(string) +{ + if (string.includes("//# sourceURL")) + return string; + return "\n//# sourceURL=__WebInspectorConsoleEvaluation__\n" + string; +} + +function isWebInspectorInternalScript(url) +{ + return url === "__WebInspectorInternal__"; +} + +function isWebInspectorConsoleEvaluationScript(url) +{ + return url === "__WebInspectorConsoleEvaluation__"; +} + +function isWebKitInjectedScript(url) +{ + return url && url.startsWith("__InjectedScript_") && url.endsWith(".js"); +} + +function isWebKitInternalScript(url) +{ + if (isWebInspectorConsoleEvaluationScript(url)) + return false; + + if (isWebKitInjectedScript(url)) + return true; + + return url && url.startsWith("__Web") && url.endsWith("__"); +} + +function isFunctionStringNativeCode(str) +{ + return str.endsWith("{\n [native code]\n}"); +} + +function isTextLikelyMinified(content) +{ + const autoFormatMaxCharactersToCheck = 5000; + const autoFormatWhitespaceRatio = 0.2; + + let whitespaceScore = 0; + let size = Math.min(autoFormatMaxCharactersToCheck, content.length); + + for (let i = 0; i < size; i++) { + let char = content[i]; + + if (char === " ") + whitespaceScore++; + else if (char === "\t") + whitespaceScore += 4; + else if (char === "\n") + whitespaceScore += 8; + } + + let ratio = whitespaceScore / size; + return ratio < autoFormatWhitespaceRatio; +} + +function doubleQuotedString(str) +{ + return "\"" + str.replace(/\\/g, "\\\\").replace(/"/g, "\\\"") + "\""; +} + +function insertionIndexForObjectInListSortedByFunction(object, list, comparator, insertionIndexAfter) +{ + if (insertionIndexAfter) { + return list.upperBound(object, comparator); + } else { + return list.lowerBound(object, comparator); + } +} + +function insertObjectIntoSortedArray(object, array, comparator) +{ + array.splice(insertionIndexForObjectInListSortedByFunction(object, array, comparator), 0, object); +} + +function decodeBase64ToBlob(base64Data, mimeType) +{ + mimeType = mimeType || ''; + + const sliceSize = 1024; + var byteCharacters = atob(base64Data); + var bytesLength = byteCharacters.length; + var slicesCount = Math.ceil(bytesLength / sliceSize); + var byteArrays = new Array(slicesCount); + + for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) { + var begin = sliceIndex * sliceSize; + var end = Math.min(begin + sliceSize, bytesLength); + + var bytes = new Array(end - begin); + for (var offset = begin, i = 0 ; offset < end; ++i, ++offset) + bytes[i] = byteCharacters[offset].charCodeAt(0); + + byteArrays[sliceIndex] = new Uint8Array(bytes); + } + + return new Blob(byteArrays, {type: mimeType}); +} + +// FIXME: This can be removed when WEB_TIMING is enabled for all platforms. +function timestamp() +{ + return window.performance ? performance.now() : Date.now(); +} + +if (!window.handlePromiseException) { + window.handlePromiseException = function handlePromiseException(error) + { + console.error("Uncaught exception in Promise", error); + }; +} diff --git a/Source/WebInspectorUI/UserInterface/Base/WebInspector.js b/Source/WebInspectorUI/UserInterface/Base/WebInspector.js new file mode 100644 index 000000000..15460bb44 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Base/WebInspector.js @@ -0,0 +1,26 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +var WebInspector = {}; // Namespace diff --git a/Source/WebInspectorUI/UserInterface/Base/YieldableTask.js b/Source/WebInspectorUI/UserInterface/Base/YieldableTask.js new file mode 100644 index 000000000..e7ceb5119 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Base/YieldableTask.js @@ -0,0 +1,156 @@ +/* + * Copyright (C) 2016 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.YieldableTask = class YieldableTask extends WebInspector.Object +{ + constructor(delegate, items, options={}) + { + super(); + + let {workInterval, idleInterval} = options; + console.assert(!workInterval || workInterval > 0, workInterval); + console.assert(!idleInterval || idleInterval > 0, idleInterval); + + console.assert(delegate && typeof delegate.yieldableTaskWillProcessItem === "function", "Delegate provide an implementation of method 'yieldableTaskWillProcessItem'."); + + console.assert(items instanceof Object && Symbol.iterator in items, "Argument `items` must subclass Object and be iterable.", items); + + // Milliseconds to run before the task should yield. + this._workInterval = workInterval || 10; + // Milliseconds to idle before asynchronously resuming the task. + this._idleInterval = idleInterval || 0; + + this._delegate = delegate; + + this._items = items; + this._idleTimeoutIdentifier = undefined; + this._processing = false; + this._processing = false; + this._cancelled = false; + } + + // Public + + get processing() { return this._processing; } + get cancelled() { return this._cancelled; } + + get idleInterval() { return this._idleInterval; } + get workInterval() { return this._workInterval; } + + start() + { + console.assert(!this._processing); + if (this._processing) + return; + + console.assert(!this._cancelled); + if (this._cancelled) + return; + + function* createIteratorForProcessingItems() + { + let startTime = Date.now(); + let processedItems = []; + + for (let item of this._items) { + if (this._cancelled) + break; + + this._delegate.yieldableTaskWillProcessItem(this, item); + processedItems.push(item); + + // Calling out to the delegate may cause the task to be cancelled. + if (this._cancelled) + break; + + let elapsedTime = Date.now() - startTime; + if (elapsedTime > this._workInterval) { + let returnedItems = processedItems.slice(); + processedItems = []; + this._willYield(returnedItems, elapsedTime); + + yield; + + startTime = Date.now(); + } + } + + // The task sends a fake yield notification to the delegate so that + // the delegate receives notification of all processed items before finishing. + if (processedItems.length) + this._willYield(processedItems, Date.now() - startTime); + } + + this._processing = true; + this._pendingItemsIterator = createIteratorForProcessingItems.call(this); + this._processPendingItems(); + } + + cancel() + { + if (!this._processing) + return; + + this._cancelled = true; + } + + // Private + + _processPendingItems() + { + console.assert(this._processing); + + if (this._cancelled) + return; + + if (!this._pendingItemsIterator.next().done) { + this._idleTimeoutIdentifier = setTimeout(() => { this._processPendingItems(); }, this._idleInterval); + return; + } + + this._didFinish(); + } + + _willYield(processedItems, elapsedTime) + { + if (typeof this._delegate.yieldableTaskDidYield === "function") + this._delegate.yieldableTaskDidYield(this, processedItems, elapsedTime); + } + + _didFinish() + { + this._processing = false; + this._pendingItemsIterator = null; + + if (this._idleTimeoutIdentifier) { + clearTimeout(this._idleTimeoutIdentifier); + this._idleTimeoutIdentifier = undefined; + } + + if (typeof this._delegate.yieldableTaskDidFinish === "function") + this._delegate.yieldableTaskDidFinish(this); + } +}; + diff --git a/Source/WebInspectorUI/UserInterface/BinarySearch.js b/Source/WebInspectorUI/UserInterface/BinarySearch.js deleted file mode 100644 index c652d6ef8..000000000 --- a/Source/WebInspectorUI/UserInterface/BinarySearch.js +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (C) 2011 Google Inc. All rights reserved. - * Copyright (C) 2007, 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/** - * @param {*} object - * @param {Array.<*>} array - * @param {function(*, *)} comparator - */ -function binarySearch(object, array, comparator) -{ - var first = 0; - var last = array.length - 1; - - while (first <= last) { - var mid = (first + last) >> 1; - var c = comparator(object, array[mid]); - if (c > 0) - first = mid + 1; - else if (c < 0) - last = mid - 1; - else - return mid; - } - - // Return the nearest lesser index, "-1" means "0, "-2" means "1", etc. - return -(first + 1); -} - -Object.defineProperty(Array.prototype, "binaryIndexOf", { value: function(value, comparator) -{ - var result = binarySearch(value, this, comparator); - return result >= 0 ? result : -1; -}}); - -/** - * @param {*} anObject - * @param {Array.<*>} aList - * @param {function(*, *)} aFunction - */ -function insertionIndexForObjectInListSortedByFunction(anObject, aList, aFunction) -{ - var index = binarySearch(anObject, aList, aFunction); - if (index < 0) - // See binarySearch implementation. - return -index - 1; - else { - // Return the first occurance of an item in the list. - while (index > 0 && aFunction(anObject, aList[index - 1]) === 0) - index--; - return index; - } -} - -function insertObjectIntoSortedArray(value, array, compareFunction) -{ - array.splice(insertionIndexForObjectInListSortedByFunction(value, array, compareFunction), 0, value); -} diff --git a/Source/WebInspectorUI/UserInterface/BlankStylePropertiesSection.js b/Source/WebInspectorUI/UserInterface/BlankStylePropertiesSection.js deleted file mode 100644 index 0ed2a7244..000000000 --- a/Source/WebInspectorUI/UserInterface/BlankStylePropertiesSection.js +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (C) 2007, 2013 Apple Inc. All rights reserved. - * Copyright (C) 2009 Joseph Pecoraro - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/** - * @constructor - * @extends {WebInspector.StylePropertiesSection} - */ -WebInspector.BlankStylePropertiesSection = function(parentPane, defaultSelectorText) -{ - WebInspector.StylePropertiesSection.call(this, parentPane, {selectorText: defaultSelectorText, rule: {isViaInspector: true}}, true, false, false); - this.element.classList.add("blank-section"); -} - -WebInspector.BlankStylePropertiesSection.prototype = { - get isBlank() - { - return !this._normal; - }, - - expand: function() - { - if (!this.isBlank) - WebInspector.StylePropertiesSection.prototype.expand.call(this); - }, - - editingSelectorCommitted: function(element, newContent, oldContent, context, moveDirection) - { - if (!this.isBlank) { - WebInspector.StylePropertiesSection.prototype.editingSelectorCommitted.call(this, element, newContent, oldContent, context, moveDirection); - return; - } - - function successCallback(newRule, doesSelectorAffectSelectedNode) - { - var styleRule = { section: this, style: newRule.style, selectorText: newRule.selectorText, sourceURL: newRule.sourceURL, rule: newRule }; - this.makeNormal(styleRule); - - if (!doesSelectorAffectSelectedNode) { - this.noAffect = true; - this.element.classList.add("no-affect"); - } - - this._selectorRefElement.textContent = WebInspector.UIString("via inspector"); - this.expand(); - if (this.element.parentElement) // Might have been detached already. - this._moveEditorFromSelector(moveDirection); - } - - WebInspector.cssModel.addRule(this.pane.node.id, newContent, successCallback.bind(this), this.editingSelectorCancelled.bind(this)); - }, - - editingSelectorCancelled: function() - { - if (!this.isBlank) { - WebInspector.StylePropertiesSection.prototype.editingSelectorCancelled.call(this); - return; - } - - this.pane.removeSection(this); - }, - - makeNormal: function(styleRule) - { - this.element.classList.remove("blank-section"); - this.styleRule = styleRule; - this.rule = styleRule.rule; - - // FIXME: replace this instance by a normal WebInspector.StylePropertiesSection. - this._normal = true; - } -} - -WebInspector.BlankStylePropertiesSection.prototype.__proto__ = WebInspector.StylePropertiesSection.prototype; diff --git a/Source/WebInspectorUI/UserInterface/BottomUpProfileDataGridTree.js b/Source/WebInspectorUI/UserInterface/BottomUpProfileDataGridTree.js deleted file mode 100644 index 899f50355..000000000 --- a/Source/WebInspectorUI/UserInterface/BottomUpProfileDataGridTree.js +++ /dev/null @@ -1,265 +0,0 @@ -/* - * Copyright (C) 2009 280 North Inc. All Rights Reserved. - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -// Bottom Up Profiling shows the entire callstack backwards: -// The root node is a representation of each individual function called, and each child of that node represents -// a reverse-callstack showing how many of those calls came from it. So, unlike top-down, the statistics in -// each child still represent the root node. We have to be particularly careful of recursion with this mode -// because a root node can represent itself AND an ancestor. - -WebInspector.BottomUpProfileDataGridNode = function(/*ProfileView*/ profileView, /*ProfileNode*/ profileNode, /*BottomUpProfileDataGridTree*/ owningTree) -{ - WebInspector.ProfileDataGridNode.call(this, profileView, profileNode, owningTree, this._willHaveChildren(profileNode)); - - this._remainingNodeInfos = []; -} - -WebInspector.BottomUpProfileDataGridNode.prototype = { - _takePropertiesFromProfileDataGridNode: function(/*ProfileDataGridNode*/ profileDataGridNode) - { - this._save(); - - this.selfTime = profileDataGridNode.selfTime; - this.totalTime = profileDataGridNode.totalTime; - this.numberOfCalls = profileDataGridNode.numberOfCalls; - }, - - // When focusing, we keep just the members of the callstack. - _keepOnlyChild: function(/*ProfileDataGridNode*/ child) - { - this._save(); - - this.removeChildren(); - this.appendChild(child); - }, - - _exclude: function(aCallUID) - { - if (this._remainingNodeInfos) - this._populate(); - - this._save(); - - var children = this.children; - var index = this.children.length; - - while (index--) - children[index]._exclude(aCallUID); - - var child = this.childrenByCallUID[aCallUID]; - - if (child) - this._merge(child, true); - }, - - _restore: function() - { - WebInspector.ProfileDataGridNode.prototype._restore(); - - if (!this.children.length) - this.hasChildren = this._willHaveChildren(); - }, - - _merge: function(/*ProfileDataGridNode*/ child, /*Boolean*/ shouldAbsorb) - { - this.selfTime -= child.selfTime; - - WebInspector.ProfileDataGridNode.prototype._merge.call(this, child, shouldAbsorb); - }, - - _sharedPopulate: function() - { - var remainingNodeInfos = this._remainingNodeInfos; - var count = remainingNodeInfos.length; - - for (var index = 0; index < count; ++index) { - var nodeInfo = remainingNodeInfos[index]; - var ancestor = nodeInfo.ancestor; - var focusNode = nodeInfo.focusNode; - var child = this.findChild(ancestor); - - // If we already have this child, then merge the data together. - if (child) { - var totalTimeAccountedFor = nodeInfo.totalTimeAccountedFor; - - child.selfTime += focusNode.selfTime; - child.numberOfCalls += focusNode.numberOfCalls; - - if (!totalTimeAccountedFor) - child.totalTime += focusNode.totalTime; - } else { - // If not, add it as a true ancestor. - // In heavy mode, we take our visual identity from ancestor node... - child = new WebInspector.BottomUpProfileDataGridNode(this.profileView, ancestor, this.tree); - - if (ancestor !== focusNode) { - // but the actual statistics from the "root" node (bottom of the callstack). - child.selfTime = focusNode.selfTime; - child.totalTime = focusNode.totalTime; - child.numberOfCalls = focusNode.numberOfCalls; - } - - this.appendChild(child); - } - - var parent = ancestor.parent; - if (parent && parent.parent) { - nodeInfo.ancestor = parent; - child._remainingNodeInfos.push(nodeInfo); - } - } - - delete this._remainingNodeInfos; - }, - - _willHaveChildren: function(profileNode) - { - profileNode = profileNode || this.profileNode; - // In bottom up mode, our parents are our children since we display an inverted tree. - // However, we don't want to show the very top parent since it is redundant. - return !!(profileNode.parent && profileNode.parent.parent); - } -} - -WebInspector.BottomUpProfileDataGridNode.prototype.__proto__ = WebInspector.ProfileDataGridNode.prototype; - -WebInspector.BottomUpProfileDataGridTree = function(/*ProfileView*/ aProfileView, /*ProfileNode*/ aProfileNode) -{ - WebInspector.ProfileDataGridTree.call(this, aProfileView, aProfileNode); - - // Iterate each node in pre-order. - var profileNodeUIDs = 0; - var profileNodeGroups = [[], [aProfileNode]]; - var visitedProfileNodesForCallUID = {}; - - this._remainingNodeInfos = []; - - for (var profileNodeGroupIndex = 0; profileNodeGroupIndex < profileNodeGroups.length; ++profileNodeGroupIndex) { - var parentProfileNodes = profileNodeGroups[profileNodeGroupIndex]; - var profileNodes = profileNodeGroups[++profileNodeGroupIndex]; - var count = profileNodes.length; - - for (var index = 0; index < count; ++index) { - var profileNode = profileNodes[index]; - - if (!profileNode.UID) - profileNode.UID = ++profileNodeUIDs; - - if (profileNode.head && profileNode !== profileNode.head) { - // The total time of this ancestor is accounted for if we're in any form of recursive cycle. - var visitedNodes = visitedProfileNodesForCallUID[profileNode.callUID]; - var totalTimeAccountedFor = false; - - if (!visitedNodes) { - visitedNodes = {}; - visitedProfileNodesForCallUID[profileNode.callUID] = visitedNodes; - } else { - // The total time for this node has already been accounted for iff one of it's parents has already been visited. - // We can do this check in this style because we are traversing the tree in pre-order. - var parentCount = parentProfileNodes.length; - for (var parentIndex = 0; parentIndex < parentCount; ++parentIndex) { - if (visitedNodes[parentProfileNodes[parentIndex].UID]) { - totalTimeAccountedFor = true; - break; - } - } - } - - visitedNodes[profileNode.UID] = true; - - this._remainingNodeInfos.push({ ancestor:profileNode, focusNode:profileNode, totalTimeAccountedFor:totalTimeAccountedFor }); - } - - var children = profileNode.children; - if (children.length) { - profileNodeGroups.push(parentProfileNodes.concat([profileNode])); - profileNodeGroups.push(children); - } - } - } - - // Populate the top level nodes. - WebInspector.BottomUpProfileDataGridNode.prototype._populate.call(this); - - return this; -} - -WebInspector.BottomUpProfileDataGridTree.prototype = { - // When focusing, we keep the entire callstack up to this ancestor. - focus: function(/*ProfileDataGridNode*/ profileDataGridNode) - { - if (!profileDataGridNode) - return; - - this._save(); - - var currentNode = profileDataGridNode; - var focusNode = profileDataGridNode; - - while (currentNode.parent && (currentNode instanceof WebInspector.ProfileDataGridNode)) { - currentNode._takePropertiesFromProfileDataGridNode(profileDataGridNode); - - focusNode = currentNode; - currentNode = currentNode.parent; - - if (currentNode instanceof WebInspector.ProfileDataGridNode) - currentNode._keepOnlyChild(focusNode); - } - - this.children = [focusNode]; - this.totalTime = profileDataGridNode.totalTime; - }, - - exclude: function(/*ProfileDataGridNode*/ profileDataGridNode) - { - if (!profileDataGridNode) - return; - - this._save(); - - var excludedCallUID = profileDataGridNode.callUID; - var excludedTopLevelChild = this.childrenByCallUID[excludedCallUID]; - - // If we have a top level node that is excluded, get rid of it completely (not keeping children), - // since bottom up data relies entirely on the root node. - if (excludedTopLevelChild) - this.children.remove(excludedTopLevelChild); - - var children = this.children; - var count = children.length; - - for (var index = 0; index < count; ++index) - children[index]._exclude(excludedCallUID); - - if (this.lastComparator) - this.sort(this.lastComparator, true); - }, - - _sharedPopulate: WebInspector.BottomUpProfileDataGridNode.prototype._sharedPopulate -} - -WebInspector.BottomUpProfileDataGridTree.prototype.__proto__ = WebInspector.ProfileDataGridTree.prototype; - diff --git a/Source/WebInspectorUI/UserInterface/BoxModelDetailsSectionRow.css b/Source/WebInspectorUI/UserInterface/BoxModelDetailsSectionRow.css deleted file mode 100644 index 9ff4f9fbd..000000000 --- a/Source/WebInspectorUI/UserInterface/BoxModelDetailsSectionRow.css +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.details-section .row.box-model { - padding: 6px; - text-align: center; - white-space: nowrap; -} - -.details-section .row.box-model .label { - position: absolute; - color: black; - margin-left: 3px; - padding-left: 2px; - padding-right: 2px; -} - -.details-section .row.box-model .position { - border: 1px rgb(66%, 66%, 66%) dotted; - background-color: rgb(231, 231, 231); - display: inline-block; - text-align: center; - padding: 3px; - margin: 3px; -} - -.details-section .row.box-model .margin { - border: 1px dashed; - background-color: rgb(231, 231, 231); - display: inline-block; - text-align: center; - vertical-align: middle; - padding: 3px; - margin: 3px; -} - -.details-section .row.box-model .margin.active { - background-color: rgba(246, 178, 107, .66); -} - -.details-section .row.box-model .border { - border: 1px black solid; - background-color: rgb(231, 231, 231); - display: inline-block; - text-align: center; - vertical-align: middle; - padding: 3px; - margin: 3px; -} - -.details-section .row.box-model .border.active { - background-color: rgba(255, 229, 153, .66); -} - -.details-section .row.box-model .padding { - border: 1px grey dashed; - background-color: rgb(231, 231, 231); - display: inline-block; - text-align: center; - vertical-align: middle; - padding: 3px; - margin: 3px; -} - -.details-section .row.box-model .padding.active { - background-color: rgba(147, 196, 125, .55); -} - -.details-section .row.box-model .content { - position: static; - border: 1px gray solid; - background-color: rgb(231, 231, 231); - display: inline-block; - text-align: center; - vertical-align: middle; - padding: 3px; - margin: 3px; - min-width: 80px; - overflow: visible; -} - -.details-section .row.box-model .content.active { - background-color: rgba(111, 168, 220, .66); -} - -.details-section .row.box-model .content span { - display: inline-block; -} - -.details-section .row.box-model .editing { - position: relative; - z-index: 100; -} - -.details-section .row.box-model .left { - display: inline-block; - vertical-align: middle; -} - -.details-section .row.box-model .right { - display: inline-block; - vertical-align: middle; -} - -.details-section .row.box-model .top { - display: inline-block; -} - -.details-section .row.box-model .bottom { - display: inline-block; -} diff --git a/Source/WebInspectorUI/UserInterface/BoxModelDetailsSectionRow.js b/Source/WebInspectorUI/UserInterface/BoxModelDetailsSectionRow.js deleted file mode 100644 index d607cce87..000000000 --- a/Source/WebInspectorUI/UserInterface/BoxModelDetailsSectionRow.js +++ /dev/null @@ -1,428 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.BoxModelDetailsSectionRow = function() { - WebInspector.DetailsSectionRow.call(this, WebInspector.UIString("No Box Model Information")); - - this.element.classList.add(WebInspector.BoxModelDetailsSectionRow.StyleClassName); - - this._nodeStyles = null; -}; - -WebInspector.BoxModelDetailsSectionRow.StyleClassName = "box-model"; -WebInspector.BoxModelDetailsSectionRow.StyleValueDelimiters = " \xA0\t\n\"':;,/()"; -WebInspector.BoxModelDetailsSectionRow.CSSNumberRegex = /^(-?(?:\d+(?:\.\d+)?|\.\d+))$/; - -WebInspector.BoxModelDetailsSectionRow.prototype = { - constructor: WebInspector.BoxModelDetailsSectionRow, - - // Public - - get nodeStyles() - { - return this._nodeStyles; - }, - - set nodeStyles(nodeStyles) - { - this._nodeStyles = nodeStyles; - - this._refresh(); - }, - - // Private - - _refresh: function() - { - if (this._ignoreNextRefresh) { - delete this._ignoreNextRefresh; - return; - } - - this._updateMetrics(); - }, - - _getPropertyValueAsPx: function(style, propertyName) - { - return Number(style.propertyForName(propertyName).value.replace(/px$/, "") || 0); - }, - - _getBox: function(computedStyle, componentName) - { - var suffix = componentName === "border" ? "-width" : ""; - var left = this._getPropertyValueAsPx(computedStyle, componentName + "-left" + suffix); - var top = this._getPropertyValueAsPx(computedStyle, componentName + "-top" + suffix); - var right = this._getPropertyValueAsPx(computedStyle, componentName + "-right" + suffix); - var bottom = this._getPropertyValueAsPx(computedStyle, componentName + "-bottom" + suffix); - return { left: left, top: top, right: right, bottom: bottom }; - }, - - _highlightDOMNode: function(showHighlight, mode, event) - { - event.stopPropagation(); - - var nodeId = showHighlight ? this.nodeStyles.node.id : 0; - if (nodeId) { - if (this._highlightMode === mode) - return; - this._highlightMode = mode; - WebInspector.domTreeManager.highlightDOMNode(nodeId, mode); - } else { - delete this._highlightMode; - WebInspector.domTreeManager.hideDOMNodeHighlight(); - } - - for (var i = 0; this._boxElements && i < this._boxElements.length; ++i) { - var element = this._boxElements[i]; - if (nodeId && (mode === "all" || element._name === mode)) - element.classList.add("active"); - else - element.classList.remove("active"); - } - }, - - _updateMetrics: function() - { - // Updating with computed style. - var metricsElement = document.createElement("div"); - - var self = this; - var style = this._nodeStyles.computedStyle; - - function createElement(type, value, name, propertyName, style) - { - // Check if the value is a float and whether it should be rounded. - var floatValue = parseFloat(value); - var shouldRoundValue = (!isNaN(floatValue) && floatValue % 1 !== 0); - - var element = document.createElement(type); - element.textContent = shouldRoundValue ? ("~" + Math.round(floatValue * 100) / 100) : value; - if (shouldRoundValue) - element.title = value; - element.addEventListener("dblclick", this._startEditing.bind(this, element, name, propertyName, style), false); - return element; - } - - function createBoxPartElement(style, name, side, suffix) - { - var propertyName = (name !== "position" ? name + "-" : "") + side + suffix; - var value = style.propertyForName(propertyName).value; - if (value === "" || (name !== "position" && value === "0px")) - value = "\u2012"; - else if (name === "position" && value === "auto") - value = "\u2012"; - value = value.replace(/px$/, ""); - - var element = createElement.call(this, "div", value, name, propertyName, style); - element.className = side; - return element; - } - - function createContentAreaWidthElement(style) - { - var width = style.propertyForName("width").value.replace(/px$/, ""); - if (style.propertyForName("box-sizing").value === "border-box") { - var borderBox = self._getBox(style, "border"); - var paddingBox = self._getBox(style, "padding"); - - width = width - borderBox.left - borderBox.right - paddingBox.left - paddingBox.right; - } - - return createElement.call(this, "span", width, "width", "width", style); - } - - function createContentAreaHeightElement(style) - { - var height = style.propertyForName("height").value.replace(/px$/, ""); - if (style.propertyForName("box-sizing").value === "border-box") { - var borderBox = self._getBox(style, "border"); - var paddingBox = self._getBox(style, "padding"); - - height = height - borderBox.top - borderBox.bottom - paddingBox.top - paddingBox.bottom; - } - - return createElement.call(this, "span", height, "height", "height", style); - } - - // Display types for which margin is ignored. - var noMarginDisplayType = { - "table-cell": true, - "table-column": true, - "table-column-group": true, - "table-footer-group": true, - "table-header-group": true, - "table-row": true, - "table-row-group": true - }; - - // Display types for which padding is ignored. - var noPaddingDisplayType = { - "table-column": true, - "table-column-group": true, - "table-footer-group": true, - "table-header-group": true, - "table-row": true, - "table-row-group": true - }; - - // Position types for which top, left, bottom and right are ignored. - var noPositionType = { - "static": true - }; - - this._boxElements = []; - var boxes = ["content", "padding", "border", "margin", "position"]; - - if (!style.properties.length) { - this.showEmptyMessage(); - return; - } - - var previousBox = null; - for (var i = 0; i < boxes.length; ++i) { - var name = boxes[i]; - - if (name === "margin" && noMarginDisplayType[style.propertyForName("display").value]) - continue; - if (name === "padding" && noPaddingDisplayType[style.propertyForName("display").value]) - continue; - if (name === "position" && noPositionType[style.propertyForName("position").value]) - continue; - - var boxElement = document.createElement("div"); - boxElement.className = name; - boxElement._name = name; - boxElement.addEventListener("mouseover", this._highlightDOMNode.bind(this, true, name === "position" ? "all" : name), false); - this._boxElements.push(boxElement); - - if (name === "content") { - var widthElement = createContentAreaWidthElement.call(this, style); - var heightElement = createContentAreaHeightElement.call(this, style); - - boxElement.appendChild(widthElement); - boxElement.appendChild(document.createTextNode(" \u00D7 ")); - boxElement.appendChild(heightElement); - } else { - var suffix = (name === "border" ? "-width" : ""); - - var labelElement = document.createElement("div"); - labelElement.className = "label"; - labelElement.textContent = boxes[i]; - boxElement.appendChild(labelElement); - - boxElement.appendChild(createBoxPartElement.call(this, style, name, "top", suffix)); - boxElement.appendChild(document.createElement("br")); - boxElement.appendChild(createBoxPartElement.call(this, style, name, "left", suffix)); - - if (previousBox) - boxElement.appendChild(previousBox); - - boxElement.appendChild(createBoxPartElement.call(this, style, name, "right", suffix)); - boxElement.appendChild(document.createElement("br")); - boxElement.appendChild(createBoxPartElement.call(this, style, name, "bottom", suffix)); - } - - previousBox = boxElement; - } - - metricsElement.appendChild(previousBox); - metricsElement.addEventListener("mouseover", this._highlightDOMNode.bind(this, false, ""), false); - - this.hideEmptyMessage(); - this.element.appendChild(metricsElement); - }, - - _startEditing: function(targetElement, box, styleProperty, computedStyle) - { - if (WebInspector.isBeingEdited(targetElement)) - return; - - // If the target element has a title use it as the editing value - // since the current text is likely truncated/rounded. - if (targetElement.title) - targetElement.textContent = targetElement.title; - - var context = {box: box, styleProperty: styleProperty}; - var boundKeyDown = this._handleKeyDown.bind(this, context, styleProperty); - context.keyDownHandler = boundKeyDown; - targetElement.addEventListener("keydown", boundKeyDown, false); - - this._isEditingMetrics = true; - - var config = new WebInspector.EditingConfig(this._editingCommitted.bind(this), this._editingCancelled.bind(this), context); - WebInspector.startEditing(targetElement, config); - - window.getSelection().setBaseAndExtent(targetElement, 0, targetElement, 1); - }, - - _alteredFloatNumber: function(number, event) - { - var arrowKeyPressed = (event.keyIdentifier === "Up" || event.keyIdentifier === "Down"); - - // Jump by 10 when shift is down or jump by 0.1 when Alt/Option is down. - // Also jump by 10 for page up and down, or by 100 if shift is held with a page key. - var changeAmount = 1; - if (event.shiftKey && !arrowKeyPressed) - changeAmount = 100; - else if (event.shiftKey || !arrowKeyPressed) - changeAmount = 10; - else if (event.altKey) - changeAmount = 0.1; - - if (event.keyIdentifier === "Down" || event.keyIdentifier === "PageDown") - changeAmount *= -1; - - // Make the new number and constrain it to a precision of 6, this matches numbers the engine returns. - // Use the Number constructor to forget the fixed precision, so 1.100000 will print as 1.1. - var result = Number((number + changeAmount).toFixed(6)); - if (!String(result).match(WebInspector.BoxModelDetailsSectionRow.CSSNumberRegex)) - return null; - - return result; - }, - - _handleKeyDown: function(context, styleProperty, event) - { - if (!/^(?:Page)?(?:Up|Down)$/.test(event.keyIdentifier)) - return; - - var element = event.currentTarget; - - var selection = window.getSelection(); - if (!selection.rangeCount) - return; - - var selectionRange = selection.getRangeAt(0); - if (!selectionRange.commonAncestorContainer.isSelfOrDescendant(element)) - return; - - var originalValue = element.textContent; - var wordRange = selectionRange.startContainer.rangeOfWord(selectionRange.startOffset, WebInspector.BoxModelDetailsSectionRow.StyleValueDelimiters, element); - var wordString = wordRange.toString(); - - var matches = /(.*?)(-?(?:\d+(?:\.\d+)?|\.\d+))(.*)/.exec(wordString); - var replacementString; - if (matches && matches.length) { - var prefix = matches[1]; - var suffix = matches[3]; - var number = this._alteredFloatNumber(parseFloat(matches[2]), event); - if (number === null) { - // Need to check for null explicitly. - return; - } - - if (styleProperty !== "margin" && number < 0) - number = 0; - - replacementString = prefix + number + suffix; - } - - if (!replacementString) - return; - - var replacementTextNode = document.createTextNode(replacementString); - - wordRange.deleteContents(); - wordRange.insertNode(replacementTextNode); - - var finalSelectionRange = document.createRange(); - finalSelectionRange.setStart(replacementTextNode, 0); - finalSelectionRange.setEnd(replacementTextNode, replacementString.length); - - selection.removeAllRanges(); - selection.addRange(finalSelectionRange); - - event.handled = true; - event.preventDefault(); - - this._ignoreNextRefresh = true; - - this._applyUserInput(element, replacementString, originalValue, context, false); - }, - - _editingEnded: function(element, context) - { - delete this.originalPropertyData; - delete this.previousPropertyDataCandidate; - element.removeEventListener("keydown", context.keyDownHandler, false); - delete this._isEditingMetrics; - }, - - _editingCancelled: function(element, context) - { - this._editingEnded(element, context); - this._refresh(); - }, - - _applyUserInput: function(element, userInput, previousContent, context, commitEditor) - { - if (commitEditor && userInput === previousContent) - return this._editingCancelled(element, context); // nothing changed, so cancel - - if (context.box !== "position" && (!userInput || userInput === "\u2012")) - userInput = "0px"; - else if (context.box === "position" && (!userInput || userInput === "\u2012")) - userInput = "auto"; - - userInput = userInput.toLowerCase(); - // Append a "px" unit if the user input was just a number. - if (/^-?(?:\d+(?:\.\d+)?|\.\d+)$/.test(userInput)) - userInput += "px"; - - var styleProperty = context.styleProperty; - var computedStyle = this._nodeStyles.computedStyle; - - if (computedStyle.propertyForName("box-sizing").value === "border-box" && (styleProperty === "width" || styleProperty === "height")) { - if (!userInput.match(/px$/)) { - console.error("For elements with box-sizing: border-box, only absolute content area dimensions can be applied"); - return; - } - - var borderBox = this._getBox(computedStyle, "border"); - var paddingBox = this._getBox(computedStyle, "padding"); - var userValuePx = Number(userInput.replace(/px$/, "")); - if (isNaN(userValuePx)) - return; - if (styleProperty === "width") - userValuePx += borderBox.left + borderBox.right + paddingBox.left + paddingBox.right; - else - userValuePx += borderBox.top + borderBox.bottom + paddingBox.top + paddingBox.bottom; - - userInput = userValuePx + "px"; - } - - var property = this._nodeStyles.inlineStyle.propertyForName(context.styleProperty); - property.value = userInput; - property.add(); - }, - - _editingCommitted: function(element, userInput, previousContent, context) - { - this._editingEnded(element, context); - this._applyUserInput(element, userInput, previousContent, context, true); - } -}; - -WebInspector.BoxModelDetailsSectionRow.prototype.__proto__ = WebInspector.DetailsSectionRow.prototype; diff --git a/Source/WebInspectorUI/UserInterface/Branch.js b/Source/WebInspectorUI/UserInterface/Branch.js deleted file mode 100644 index 87e97c079..000000000 --- a/Source/WebInspectorUI/UserInterface/Branch.js +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.Branch = function(displayName, revisions, locked) -{ - WebInspector.Object.call(this); - - console.assert(displayName); - - this._displayName = displayName; - this._revisions = revisions instanceof Array ? revisions.slice() : []; - this._locked = locked || false; -}; - -WebInspector.Branch.prototype = { - constructor: WebInspector.Branch, - - // Public - - get displayName() - { - return this._displayName; - }, - - set displayName(displayName) - { - console.assert(displayName); - if (!displayName) - return; - - this._displayName = displayName; - }, - - get revisions() - { - return this._revisions; - }, - - get locked() - { - return this._locked; - }, - - revisionForRepresentedObject: function(representedObject, doNotCreateIfNeeded) - { - for (var i = 0; i < this._revisions.length; ++i) { - var revision = this._revisions[i]; - if (revision instanceof WebInspector.SourceCodeRevision && revision.sourceCode === representedObject) - return revision; - } - - if (doNotCreateIfNeeded) - return null; - - if (representedObject instanceof WebInspector.SourceCode) { - var revision = representedObject.originalRevision.copy(); - representedObject.currentRevision = revision; - this.addRevision(revision); - return revision; - } - - return null; - }, - - addRevision: function(revision) - { - console.assert(revision instanceof WebInspector.Revision); - - if (this._locked) - return; - - if (this._revisions.contains(revision)) - return; - - this._revisions.push(revision); - }, - - removeRevision: function(revision) - { - console.assert(revision instanceof WebInspector.Revision); - - if (this._locked) - return; - - this._revisions.remove(revision); - }, - - reset: function() - { - if (this._locked) - return; - - this._revisions = []; - }, - - fork: function(displayName) - { - var copiedRevisions = this._revisions.map(function(revision) { return revision.copy(); }); - return new WebInspector.Branch(displayName, copiedRevisions); - }, - - apply: function() - { - for (var i = 0; i < this._revisions.length; ++i) - this._revisions[i].apply(); - }, - - revert: function() - { - for (var i = this._revisions.length - 1; i >= 0; --i) - this._revisions[i].revert(); - }, - - lock: function() - { - console.assert(!this._locked); - this._locked = true; - }, - - unlock: function() - { - console.assert(this._locked); - this._locked = false; - } -}; - -WebInspector.Branch.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/BranchManager.js b/Source/WebInspectorUI/UserInterface/BranchManager.js deleted file mode 100644 index 39004c6bb..000000000 --- a/Source/WebInspectorUI/UserInterface/BranchManager.js +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.BranchManager = function() -{ - WebInspector.Object.call(this); - - WebInspector.Frame.addEventListener(WebInspector.Frame.Event.MainResourceDidChange, this._mainResourceDidChange, this); - - this.initialize(); -} - -WebInspector.BranchManager.prototype = { - constructor: WebInspector.BranchManager, - - // Public - - initialize: function() - { - this._originalBranch = new WebInspector.Branch(WebInspector.UIString("Original"), null, true); - this._currentBranch = this._originalBranch.fork(WebInspector.UIString("Working Copy")); - this._branches = [this._originalBranch, this._currentBranch]; - }, - - get branches() - { - return this._branches; - }, - - get currentBranch() - { - return this._currentBranch; - }, - - set currentBranch(branch) - { - console.assert(branch instanceof WebInspector.Branch); - if (!(branch instanceof WebInspector.Branch)) - return; - - this._currentBranch.revert(); - - this._currentBranch = branch; - - this._currentBranch.apply(); - }, - - createBranch: function(displayName, fromBranch) - { - if (!fromBranch) - fromBranch = this._originalBranch; - - console.assert(fromBranch instanceof WebInspector.Branch); - if (!(fromBranch instanceof WebInspector.Branch)) - return; - - var newBranch = fromBranch.fork(displayName); - this._branches.push(newBranch); - return newBranch; - }, - - deleteBranch: function(branch) - { - console.assert(branch instanceof WebInspector.Branch); - if (!(branch instanceof WebInspector.Branch)) - return; - - console.assert(branch !== this._originalBranch); - if (branch === this._originalBranch) - return; - - this._branches.remove(branch); - - if (branch === this._currentBranch) - this._currentBranch = this._originalBranch; - }, - - // Private - - _mainResourceDidChange: function(event) - { - console.assert(event.target instanceof WebInspector.Frame); - - if (!event.target.isMainFrame()) - return; - - this.initialize(); - } -}; - -WebInspector.BranchManager.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/Breakpoint.css b/Source/WebInspectorUI/UserInterface/Breakpoint.css deleted file mode 100644 index 909834a07..000000000 --- a/Source/WebInspectorUI/UserInterface/Breakpoint.css +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.popover .edit-breakpoint-popover-content { - width: 420px; - padding: 5px 15px; - - font-family: "Lucida Grande", Helvetica, sans-serif; - font-size: 11px; -} - -.popover .edit-breakpoint-popover-content.wide { - width: 460px; -} - -.popover .edit-breakpoint-popover-content > label.toggle { - color: black; - font-weight: bold; - text-overflow: ellipsis; - white-space: nowrap; -} - -.popover .edit-breakpoint-popover-content > table { - width: 100%; -} - -.popover .edit-breakpoint-popover-content > table > tr > th { - color: rgb(89, 89, 89); - font-weight: bold; - text-align: right; - width: 1px; /* Shrink to fit. */ - vertical-align: top; - line-height: 23px; -} - -.popover .edit-breakpoint-popover-content > table > tr > td { - padding-left: 5px; -} - -#edit-breakpoint-popover-condition { - width: 100%; -} - -#edit-breakpoint-popoover-auto-continue { - margin-left: 0; - margin-right: 4px; -} diff --git a/Source/WebInspectorUI/UserInterface/Breakpoint.js b/Source/WebInspectorUI/UserInterface/Breakpoint.js deleted file mode 100644 index 29073d911..000000000 --- a/Source/WebInspectorUI/UserInterface/Breakpoint.js +++ /dev/null @@ -1,566 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.Breakpoint = function(sourceCodeLocationOrInfo, disabled, condition) -{ - WebInspector.Object.call(this); - - if (sourceCodeLocationOrInfo instanceof WebInspector.SourceCodeLocation) { - var sourceCode = sourceCodeLocationOrInfo.sourceCode; - var url = sourceCode ? sourceCode.url : null; - var scriptIdentifier = sourceCode instanceof WebInspector.Script ? sourceCode.id : null; - var location = sourceCodeLocationOrInfo; - } else if (sourceCodeLocationOrInfo && typeof sourceCodeLocationOrInfo === "object") { - var url = sourceCodeLocationOrInfo.url; - var lineNumber = sourceCodeLocationOrInfo.lineNumber || 0; - var columnNumber = sourceCodeLocationOrInfo.columnNumber || 0; - var location = new WebInspector.SourceCodeLocation(null, lineNumber, columnNumber); - var autoContinue = sourceCodeLocationOrInfo.autoContinue || false; - var actions = sourceCodeLocationOrInfo.actions || []; - for (var i = 0; i < actions.length; ++i) - actions[i] = new WebInspector.BreakpointAction(this, actions[i]); - disabled = sourceCodeLocationOrInfo.disabled; - condition = sourceCodeLocationOrInfo.condition; - } else - console.error("Unexpected type passed to WebInspector.Breakpoint", sourceCodeLocationOrInfo); - - this._id = null; - this._url = url || null; - this._scriptIdentifier = scriptIdentifier || null; - this._disabled = disabled || false; - this._condition = condition || ""; - this._autoContinue = autoContinue || false; - this._actions = actions || []; - this._resolved = false; - - this._sourceCodeLocation = location; - this._sourceCodeLocation.addEventListener(WebInspector.SourceCodeLocation.Event.LocationChanged, this._sourceCodeLocationLocationChanged, this); - this._sourceCodeLocation.addEventListener(WebInspector.SourceCodeLocation.Event.DisplayLocationChanged, this._sourceCodeLocationDisplayLocationChanged, this); -}; - -WebInspector.Object.addConstructorFunctions(WebInspector.Breakpoint); - -WebInspector.Breakpoint.PopoverClassName = "edit-breakpoint-popover-content"; -WebInspector.Breakpoint.WidePopoverClassName = "wide"; -WebInspector.Breakpoint.PopoverConditionInputId = "edit-breakpoint-popover-condition"; -WebInspector.Breakpoint.PopoverOptionsAutoContinueInputId = "edit-breakpoint-popoover-auto-continue"; -WebInspector.Breakpoint.HiddenStyleClassName = "hidden"; - -WebInspector.Breakpoint.DefaultBreakpointActionType = WebInspector.BreakpointAction.Type.Log; - -WebInspector.Breakpoint.TypeIdentifier = "breakpoint"; -WebInspector.Breakpoint.URLCookieKey = "breakpoint-url"; -WebInspector.Breakpoint.LineNumberCookieKey = "breakpoint-line-number"; -WebInspector.Breakpoint.ColumnNumberCookieKey = "breakpoint-column-number"; - -WebInspector.Breakpoint.Event = { - DisabledStateDidChange: "breakpoint-disabled-state-did-change", - ResolvedStateDidChange: "breakpoint-resolved-state-did-change", - ConditionDidChange: "breakpoint-condition-did-change", - ActionsDidChange: "breakpoint-actions-did-change", - AutoContinueDidChange: "breakpoint-auto-continue-did-change", - LocationDidChange: "breakpoint-location-did-change", - DisplayLocationDidChange: "breakpoint-display-location-did-change", -}; - -WebInspector.Breakpoint.prototype = { - constructor: WebInspector.Breakpoint, - - // Public - - get id() - { - return this._id; - }, - - set id(id) - { - this._id = id || null; - }, - - get url() - { - return this._url; - }, - - get scriptIdentifier() - { - return this._scriptIdentifier; - }, - - get sourceCodeLocation() - { - return this._sourceCodeLocation; - }, - - get resolved() - { - return this._resolved && WebInspector.debuggerManager.breakpointsEnabled; - }, - - set resolved(resolved) - { - if (this._resolved === resolved) - return; - - this._resolved = resolved || false; - - this.dispatchEventToListeners(WebInspector.Breakpoint.Event.ResolvedStateDidChange); - }, - - get disabled() - { - return this._disabled; - }, - - set disabled(disabled) - { - if (this._disabled === disabled) - return; - - this._disabled = disabled || false; - - this.dispatchEventToListeners(WebInspector.Breakpoint.Event.DisabledStateDidChange); - }, - - get condition() - { - return this._condition; - }, - - set condition(condition) - { - if (this._condition === condition) - return; - - this._condition = condition; - - this.dispatchEventToListeners(WebInspector.Breakpoint.Event.ConditionDidChange); - }, - - get autoContinue() - { - return this._autoContinue; - }, - - set autoContinue(cont) - { - if (this._autoContinue === cont) - return; - - this._autoContinue = cont; - - this.dispatchEventToListeners(WebInspector.Breakpoint.Event.AutoContinueDidChange); - }, - - get actions() - { - return this._actions; - }, - - get options() - { - return { - condition: this._condition, - actions: this._serializableActions(), - autoContinue: this._autoContinue - }; - }, - - get info() - { - // The id, scriptIdentifier and resolved state are tied to the current session, so don't include them for serialization. - return { - url: this._url, - lineNumber: this._sourceCodeLocation.lineNumber, - columnNumber: this._sourceCodeLocation.columnNumber, - disabled: this._disabled, - condition: this._condition, - actions: this._serializableActions(), - autoContinue: this._autoContinue - }; - }, - - cycleToNextMode: function() - { - if (this.disabled) { - // When cycling, clear auto-continue when going from disabled to enabled. - this.autoContinue = false; - this.disabled = false; - return; - } - - if (this.autoContinue) { - this.disabled = true; - return; - } - - if (this.actions.length) { - this.autoContinue = true; - return; - } - - this.disabled = true; - }, - - appendContextMenuItems: function(contextMenu, breakpointDisplayElement) - { - console.assert(document.body.contains(breakpointDisplayElement), "breakpoint popover display element must be in the DOM"); - - var boundingClientRect = breakpointDisplayElement.getBoundingClientRect(); - - function editBreakpoint() - { - this._showEditBreakpointPopover(boundingClientRect); - } - - function removeBreakpoint() - { - WebInspector.debuggerManager.removeBreakpoint(this); - } - - function toggleBreakpoint() - { - this.disabled = !this.disabled; - } - - function toggleAutoContinue() - { - this.autoContinue = !this.autoContinue; - } - - function revealOriginalSourceCodeLocation() - { - WebInspector.resourceSidebarPanel.showOriginalOrFormattedSourceCodeLocation(this._sourceCodeLocation); - } - - if (WebInspector.debuggerManager.isBreakpointEditable(this)) - contextMenu.appendItem(WebInspector.UIString("Edit Breakpoint…"), editBreakpoint.bind(this)); - - if (this.autoContinue && !this.disabled) { - contextMenu.appendItem(WebInspector.UIString("Disable Breakpoint"), toggleBreakpoint.bind(this)); - contextMenu.appendItem(WebInspector.UIString("Cancel Automatic Continue"), toggleAutoContinue.bind(this)); - } else if (!this.disabled) - contextMenu.appendItem(WebInspector.UIString("Disable Breakpoint"), toggleBreakpoint.bind(this)); - else - contextMenu.appendItem(WebInspector.UIString("Enable Breakpoint"), toggleBreakpoint.bind(this)); - - if (!this.autoContinue && !this.disabled && this.actions.length) - contextMenu.appendItem(WebInspector.UIString("Set to Automatically Continue"), toggleAutoContinue.bind(this)); - - if (WebInspector.debuggerManager.isBreakpointRemovable(this)) { - contextMenu.appendSeparator(); - contextMenu.appendItem(WebInspector.UIString("Delete Breakpoint"), removeBreakpoint.bind(this)); - } - - if (this._sourceCodeLocation.hasMappedLocation()) { - contextMenu.appendSeparator(); - contextMenu.appendItem(WebInspector.UIString("Reveal in Original Resource"), revealOriginalSourceCodeLocation.bind(this)); - } - }, - - createAction: function(type, precedingAction) - { - var newAction = new WebInspector.BreakpointAction(this, type, null); - - if (!precedingAction) - this._actions.push(newAction); - else { - var index = this._actions.indexOf(precedingAction); - console.assert(index !== -1); - if (index === -1) - this._actions.push(newAction); - else - this._actions.splice(index + 1, 0, newAction); - } - - this.dispatchEventToListeners(WebInspector.Breakpoint.Event.ActionsDidChange); - - return newAction; - }, - - recreateAction: function(type, actionToReplace) - { - var newAction = new WebInspector.BreakpointAction(this, type, null); - - var index = this._actions.indexOf(actionToReplace); - console.assert(index !== -1); - if (index === -1) - return null; - - this._actions[index] = newAction; - - this.dispatchEventToListeners(WebInspector.Breakpoint.Event.ActionsDidChange); - - return newAction; - }, - - removeAction: function(action) - { - var index = this._actions.indexOf(action); - console.assert(index !== -1); - if (index === -1) - return; - - this._actions.splice(index, 1); - - if (!this._actions.length) - this.autoContinue = false; - - this.dispatchEventToListeners(WebInspector.Breakpoint.Event.ActionsDidChange); - }, - - saveIdentityToCookie: function(cookie) - { - cookie[WebInspector.Breakpoint.URLCookieKey] = this.url; - cookie[WebInspector.Breakpoint.LineNumberCookieKey] = this.sourceCodeLocation.lineNumber; - cookie[WebInspector.Breakpoint.ColumnNumberCookieKey] = this.sourceCodeLocation.columnNumber; - }, - - // Protected (Called by BreakpointAction) - - breakpointActionDidChange: function(action) - { - var index = this._actions.indexOf(action); - console.assert(index !== -1); - if (index === -1) - return; - - this.dispatchEventToListeners(WebInspector.Breakpoint.Event.ActionsDidChange); - }, - - // Private - - _serializableActions: function() - { - var actions = []; - for (var i = 0; i < this._actions.length; ++i) - actions.push(this._actions[i].info); - return actions; - }, - - _popoverToggleEnabledCheckboxChanged: function(event) - { - this.disabled = !event.target.checked; - }, - - _popoverConditionInputChanged: function(event) - { - this.condition = event.target.value; - }, - - _popoverToggleAutoContinueCheckboxChanged: function(event) - { - this.autoContinue = event.target.checked; - }, - - _popoverConditionInputKeyDown: function(event) - { - if (this._keyboardShortcutEsc.matchesEvent(event) || this._keyboardShortcutEnter.matchesEvent(event)) { - this._popover.dismiss(); - event.stopPropagation(); - event.preventDefault(); - } - }, - - _editBreakpointPopoverContentElement: function() - { - var content = this._popoverContentElement = document.createElement("div"); - content.className = WebInspector.Breakpoint.PopoverClassName; - - var checkboxElement = document.createElement("input"); - checkboxElement.type = "checkbox"; - checkboxElement.checked = !this._disabled; - checkboxElement.addEventListener("change", this._popoverToggleEnabledCheckboxChanged.bind(this)); - - var checkboxLabel = document.createElement("label"); - checkboxLabel.className = "toggle"; - checkboxLabel.appendChild(checkboxElement); - checkboxLabel.appendChild(document.createTextNode(this._sourceCodeLocation.displayLocationString())); - - var table = document.createElement("table"); - - var conditionRow = table.appendChild(document.createElement("tr")); - var conditionHeader = conditionRow.appendChild(document.createElement("th")); - var conditionData = conditionRow.appendChild(document.createElement("td")); - var conditionLabel = conditionHeader.appendChild(document.createElement("label")); - var conditionInput = conditionData.appendChild(document.createElement("input")); - conditionInput.id = WebInspector.Breakpoint.PopoverConditionInputId; - conditionInput.value = this._condition || ""; - conditionInput.spellcheck = false; - conditionInput.addEventListener("change", this._popoverConditionInputChanged.bind(this)); - conditionInput.addEventListener("keydown", this._popoverConditionInputKeyDown.bind(this)); - conditionInput.placeholder = WebInspector.UIString("Conditional expression"); - conditionLabel.setAttribute("for", conditionInput.id); - conditionLabel.textContent = WebInspector.UIString("Condition"); - - if (DebuggerAgent.setBreakpoint.supports("options")) { - var actionRow = table.appendChild(document.createElement("tr")); - var actionHeader = actionRow.appendChild(document.createElement("th")); - var actionData = this._actionsContainer = actionRow.appendChild(document.createElement("td")); - var actionLabel = actionHeader.appendChild(document.createElement("label")); - actionLabel.textContent = WebInspector.UIString("Action"); - - if (!this._actions.length) - this._popoverActionsCreateAddActionButton(); - else { - this._popoverContentElement.classList.add(WebInspector.Breakpoint.WidePopoverClassName); - for (var i = 0; i < this._actions.length; ++i) { - var breakpointActionView = new WebInspector.BreakpointActionView(this._actions[i], this, true); - this._popoverActionsInsertBreakpointActionView(breakpointActionView, i); - } - } - - var optionsRow = this._popoverOptionsRowElement = table.appendChild(document.createElement("tr")); - if (!this._actions.length) - optionsRow.classList.add(WebInspector.Breakpoint.HiddenStyleClassName); - var optionsHeader = optionsRow.appendChild(document.createElement("th")); - var optionsData = optionsRow.appendChild(document.createElement("td")); - var optionsLabel = optionsHeader.appendChild(document.createElement("label")); - var optionsCheckbox = this._popoverOptionsCheckboxElement = optionsData.appendChild(document.createElement("input")); - var optionsCheckboxLabel = optionsData.appendChild(document.createElement("label")); - optionsCheckbox.id = WebInspector.Breakpoint.PopoverOptionsAutoContinueInputId; - optionsCheckbox.type = "checkbox"; - optionsCheckbox.checked = this._autoContinue; - optionsCheckbox.addEventListener("change", this._popoverToggleAutoContinueCheckboxChanged.bind(this)); - optionsLabel.textContent = WebInspector.UIString("Options"); - optionsCheckboxLabel.setAttribute("for", optionsCheckbox.id); - optionsCheckboxLabel.textContent = WebInspector.UIString("Automatically continue after evaluating"); - } - - content.appendChild(checkboxLabel); - content.appendChild(table); - - return content; - }, - - _popoverActionsCreateAddActionButton: function() - { - this._popoverContentElement.classList.remove(WebInspector.Breakpoint.WidePopoverClassName); - this._actionsContainer.removeChildren(); - - var addActionButton = this._actionsContainer.appendChild(document.createElement("button")); - addActionButton.textContent = WebInspector.UIString("Add Action"); - addActionButton.addEventListener("click", this._popoverActionsAddActionButtonClicked.bind(this)); - }, - - _popoverActionsAddActionButtonClicked: function(event) - { - this._popoverContentElement.classList.add(WebInspector.Breakpoint.WidePopoverClassName); - this._actionsContainer.removeChildren(); - - var newAction = this.createAction(WebInspector.Breakpoint.DefaultBreakpointActionType); - var newBreakpointActionView = new WebInspector.BreakpointActionView(newAction, this); - this._popoverActionsInsertBreakpointActionView(newBreakpointActionView, -1); - this._popoverOptionsRowElement.classList.remove(WebInspector.Breakpoint.HiddenStyleClassName); - this._popover.update(); - }, - - _popoverActionsInsertBreakpointActionView: function(breakpointActionView, index) - { - if (index === -1) - this._actionsContainer.appendChild(breakpointActionView.element); - else { - var nextElement = this._actionsContainer.children[index + 1] || null; - this._actionsContainer.insertBefore(breakpointActionView.element, nextElement); - } - }, - - breakpointActionViewAppendActionView: function(breakpointActionView, newAction) - { - var newBreakpointActionView = new WebInspector.BreakpointActionView(newAction, this); - - var index = 0; - var children = this._actionsContainer.children; - for (var i = 0; children.length; ++i) { - if (children[i] === breakpointActionView.element) { - index = i; - break; - } - } - - this._popoverActionsInsertBreakpointActionView(newBreakpointActionView, index); - this._popoverOptionsRowElement.classList.remove(WebInspector.Breakpoint.HiddenStyleClassName); - - this._popover.update(); - }, - - breakpointActionViewRemoveActionView: function(breakpointActionView) - { - breakpointActionView.element.remove(); - - if (!this._actionsContainer.children.length) { - this._popoverActionsCreateAddActionButton(); - this._popoverOptionsRowElement.classList.add(WebInspector.Breakpoint.HiddenStyleClassName); - this._popoverOptionsCheckboxElement.checked = false; - } - - this._popover.update(); - }, - - breakpointActionViewResized: function(breakpointActionView) - { - this._popover.update(); - }, - - willDismissPopover: function(popover) - { - console.assert(this._popover === popover); - delete this._popoverContentElement; - delete this._popoverOptionsRowElement; - delete this._popoverOptionsCheckboxElement; - delete this._actionsContainer; - delete this._popover; - }, - - _showEditBreakpointPopover: function(boundingClientRect) - { - var bounds = WebInspector.Rect.rectFromClientRect(boundingClientRect); - bounds.origin.x -= 1; // Move the anchor left one pixel so it looks more centered. - - this._popover = this._popover || new WebInspector.Popover(this); - this._popover.content = this._editBreakpointPopoverContentElement(); - this._popover.present(bounds.pad(2), [WebInspector.RectEdge.MAX_Y]); - - if (!this._keyboardShortcutEsc) { - this._keyboardShortcutEsc = new WebInspector.KeyboardShortcut(null, WebInspector.KeyboardShortcut.Key.Escape); - this._keyboardShortcutEnter = new WebInspector.KeyboardShortcut(null, WebInspector.KeyboardShortcut.Key.Enter); - } - - document.getElementById(WebInspector.Breakpoint.PopoverConditionInputId).select(); - }, - - _sourceCodeLocationLocationChanged: function(event) - { - this.dispatchEventToListeners(WebInspector.Breakpoint.Event.LocationDidChange, event.data); - }, - - _sourceCodeLocationDisplayLocationChanged: function(event) - { - this.dispatchEventToListeners(WebInspector.Breakpoint.Event.DisplayLocationDidChange, event.data); - } -}; - -WebInspector.Breakpoint.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/BreakpointAction.js b/Source/WebInspectorUI/UserInterface/BreakpointAction.js deleted file mode 100644 index b9ff1b232..000000000 --- a/Source/WebInspectorUI/UserInterface/BreakpointAction.js +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.BreakpointAction = function(breakpoint, typeOrInfo, data) -{ - WebInspector.Object.call(this); - - console.assert(breakpoint); - console.assert(typeOrInfo); - - this._breakpoint = breakpoint; - - if (typeof typeOrInfo === "string") { - this._type = typeOrInfo; - this._data = data || null; - } else if (typeof typeOrInfo === "object") { - this._type = typeOrInfo.type; - this._data = typeOrInfo.data || null; - } else - console.error("Unexpected type passed to WebInspector.BreakpointAction"); - - console.assert(typeof this._type === "string"); -}; - -WebInspector.BreakpointAction.Type = { - Log: "log", - Evaluate: "evaluate", - Sound: "sound", - Probe: "probe" -} - -WebInspector.BreakpointAction.prototype = { - constructor: WebInspector.BreakpointAction, - - // Public - - get breakpoint() - { - return this._breakpoint; - }, - - get type() - { - return this._type; - }, - - get data() - { - return this._data; - }, - - set data(data) - { - if (this._data === data) - return; - - this._data = data; - - this._breakpoint.breakpointActionDidChange(this); - }, - - get info() - { - var obj = {type: this._type}; - if (this._data) - obj.data = this._data; - return obj; - } -}; - -WebInspector.BreakpointAction.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/BreakpointActionView.css b/Source/WebInspectorUI/UserInterface/BreakpointActionView.css deleted file mode 100644 index 8d81eab7a..000000000 --- a/Source/WebInspectorUI/UserInterface/BreakpointActionView.css +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.breakpoint-action-block-header { - margin-bottom: 3px; -} - -.breakpoint-action-append-button, -.breakpoint-action-remove-button { - border: 1px solid rgb(170, 170, 170); - border-radius: 10px; - background-size: 16px 16px; - background-origin: border-box; - width: 16px; - height: 16px; - float: right; - margin-left: 2px; - margin-top: 2px; -} - -.breakpoint-action-append-button:active, -.breakpoint-action-remove-button:active { - -webkit-filter: brightness(50%); -} - -.breakpoint-action-append-button { - background-image: url(Images/BreakpointActionAdd.svg), -webkit-linear-gradient(top, rgb(250, 250, 250), rgb(200, 200, 200)); -} - -.breakpoint-action-remove-button { - background-image: url(Images/BreakpointActionRemove.svg), -webkit-linear-gradient(top, rgb(250, 250, 250), rgb(200, 200, 200)); -} - -.breakpoint-action-block-body { - margin: 1px 2px 6px 2px; - padding: 8px; - width: 100%; - border-radius: 4px; - border: 1px solid rgb(190, 190, 190); - background-color: rgba(222, 222, 222, 0.95); - -webkit-box-shadow: inset 0 0 2px rgb(200, 200, 200); -} - -.breakpoint-action-block-body > input { - width: 100%; -} - -.breakpoint-action-eval-editor { - padding: 4px 0 2px 0; - -webkit-appearance: textfield; - border: 1px solid rgb(200, 200, 200); - background: white; -} - -.breakpoint-action-eval-editor > .CodeMirror { - width: 336px; /* NOTE: Fixed value, manually tuned to .edit-breakpoint-popover-content.wide width */ - height: auto; -} - -.breakpoint-action-eval-editor > .CodeMirror-scroll { - width: 336px; /* NOTE: Fixed value, manually tuned to .edit-breakpoint-popover-content.wide width */ - overflow: hidden; -} diff --git a/Source/WebInspectorUI/UserInterface/BreakpointActionView.js b/Source/WebInspectorUI/UserInterface/BreakpointActionView.js deleted file mode 100644 index eb54d37b6..000000000 --- a/Source/WebInspectorUI/UserInterface/BreakpointActionView.js +++ /dev/null @@ -1,202 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.BreakpointActionView = function(action, delegate, omitFocus) -{ - WebInspector.Object.call(this); - - console.assert(action); - console.assert(delegate); - console.assert(DebuggerAgent.BreakpointActionType); - - this._action = action; - this._delegate = delegate; - - this._element = document.createElement("div"); - this._element.className = "breakpoint-action-block"; - - var header = this._element.appendChild(document.createElement("div")); - header.className = "breakpoint-action-block-header"; - - var picker = header.appendChild(document.createElement("select")); - picker.addEventListener("change", this._pickerChanged.bind(this)); - - for (var key in WebInspector.BreakpointAction.Type) { - var type = WebInspector.BreakpointAction.Type[key]; - var option = document.createElement("option"); - option.textContent = WebInspector.BreakpointActionView.displayStringForType(type); - option.selected = this._action.type === type; - option.value = type; - picker.add(option); - } - - var appendActionButton = header.appendChild(document.createElement("button")); - appendActionButton.className = "breakpoint-action-append-button"; - appendActionButton.addEventListener("click", this._appendActionButtonClicked.bind(this)); - appendActionButton.title = WebInspector.UIString("Add new breakpoint action after this action"); - - var removeActionButton = header.appendChild(document.createElement("button")); - removeActionButton.className = "breakpoint-action-remove-button"; - removeActionButton.addEventListener("click", this._removeActionButtonClicked.bind(this)); - removeActionButton.title = WebInspector.UIString("Remove this breakpoint action"); - - this._bodyElement = this._element.appendChild(document.createElement("div")); - this._bodyElement.className = "breakpoint-action-block-body"; - - this._updateBody(omitFocus); -}; - -WebInspector.BreakpointActionView.displayStringForType = function(type) -{ - switch (type) { - case WebInspector.BreakpointAction.Type.Log: - return WebInspector.UIString("Log Message"); - case WebInspector.BreakpointAction.Type.Evaluate: - return WebInspector.UIString("Evaluate JavaScript"); - case WebInspector.BreakpointAction.Type.Sound: - return WebInspector.UIString("Play Sound"); - case WebInspector.BreakpointAction.Type.Probe: - return WebInspector.UIString("Probe Expression"); - default: - console.assert(false); - return ""; - } -} - -WebInspector.BreakpointActionView.prototype = { - constructor: WebInspector.BreakpointActionView, - - // Public - - get action() - { - return this._action; - }, - - get element() - { - return this._element; - }, - - // Private - - _pickerChanged: function(event) - { - var newType = event.target.value; - this._action = this._action.breakpoint.recreateAction(newType, this._action); - this._updateBody(); - this._delegate.breakpointActionViewResized(this); - }, - - _appendActionButtonClicked: function(event) - { - var newAction = this._action.breakpoint.createAction(WebInspector.Breakpoint.DefaultBreakpointActionType, this._action); - this._delegate.breakpointActionViewAppendActionView(this, newAction); - }, - - _removeActionButtonClicked: function(event) - { - this._action.breakpoint.removeAction(this._action); - this._delegate.breakpointActionViewRemoveActionView(this); - }, - - _updateBody: function(omitFocus) - { - this._bodyElement.removeChildren(); - - switch (this._action.type) { - case WebInspector.BreakpointAction.Type.Log: - this._bodyElement.hidden = false; - - var input = this._bodyElement.appendChild(document.createElement("input")); - input.placeholder = WebInspector.UIString("Message"); - input.addEventListener("change", this._logInputChanged.bind(this)); - input.value = this._action.data || ""; - input.spellcheck = false; - if (!omitFocus) - setTimeout(function() { input.focus(); }, 0); - - break; - - case WebInspector.BreakpointAction.Type.Evaluate: - case WebInspector.BreakpointAction.Type.Probe: - this._bodyElement.hidden = false; - - var editorElement = this._bodyElement.appendChild(document.createElement("div")); - editorElement.classList.add("breakpoint-action-eval-editor"); - editorElement.classList.add(WebInspector.SyntaxHighlightedStyleClassName); - - this._codeMirror = CodeMirror(editorElement, { - lineWrapping: true, - mode: "text/javascript", - indentWithTabs: true, - indentUnit: 4, - matchBrackets: true, - value: this._action.data || "", - }); - - this._codeMirror.on("viewportChange", this._codeMirrorViewportChanged.bind(this)); - this._codeMirror.on("blur", this._codeMirrorBlurred.bind(this)); - - var completionController = new WebInspector.CodeMirrorCompletionController(this._codeMirror); - completionController.addExtendedCompletionProvider("javascript", WebInspector.javaScriptRuntimeCompletionProvider); - - // CodeMirror needs a refresh after the popover displays, to layout, otherwise it doesn't appear. - setTimeout(function() { - this._codeMirror.refresh(); - if (!omitFocus) - this._codeMirror.focus(); - }.bind(this), 0); - - break; - - case WebInspector.BreakpointAction.Type.Sound: - this._bodyElement.hidden = true; - break; - - default: - console.assert(false); - this._bodyElement.hidden = true; - break; - } - }, - - _logInputChanged: function(event) - { - this._action.data = event.target.value; - }, - - _codeMirrorBlurred: function(event) - { - this._action.data = this._codeMirror.getValue(); - }, - - _codeMirrorViewportChanged: function(event) - { - this._delegate.breakpointActionViewResized(this); - } -}; - -WebInspector.BreakpointActionView.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/BreakpointIcons.css b/Source/WebInspectorUI/UserInterface/BreakpointIcons.css deleted file mode 100644 index b95d2e689..000000000 --- a/Source/WebInspectorUI/UserInterface/BreakpointIcons.css +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.breakpoint-generic-line-icon .icon { - content: url(Images/ResultLine.svg); -} - -.breakpoint-exception-icon .icon { - content: url(Images/Exception.svg); -} diff --git a/Source/WebInspectorUI/UserInterface/BreakpointTreeElement.css b/Source/WebInspectorUI/UserInterface/BreakpointTreeElement.css deleted file mode 100644 index 8e282e7e7..000000000 --- a/Source/WebInspectorUI/UserInterface/BreakpointTreeElement.css +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.item.breakpoint .status > .status-image { - width: 21px; - height: 12px; - content: url(Images/BreakpointInactiveButton.svg); - margin-top: 3px; -} - -.item.breakpoint .status > .status-image.resolved { - content: url(Images/BreakpointButton.svg); -} - -.item.breakpoint .status > .status-image.auto-continue { - opacity: 0.6; -} - -.item.breakpoint .status > .status-image.disabled { - opacity: 0.35; -} - -.item.breakpoint .subtitle.formatted-location { - font-style: italic; -} diff --git a/Source/WebInspectorUI/UserInterface/BreakpointTreeElement.js b/Source/WebInspectorUI/UserInterface/BreakpointTreeElement.js deleted file mode 100644 index da39cdbd9..000000000 --- a/Source/WebInspectorUI/UserInterface/BreakpointTreeElement.js +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.BreakpointTreeElement = function(breakpoint, className, title) -{ - console.assert(breakpoint instanceof WebInspector.Breakpoint); - - if (!className) - className = WebInspector.BreakpointTreeElement.GenericLineIconStyleClassName; - - WebInspector.GeneralTreeElement.call(this, [WebInspector.BreakpointTreeElement.StyleClassName, className], title, null, breakpoint, false); - - this._breakpoint = breakpoint; - - if (!title) - this._breakpoint.addEventListener(WebInspector.Breakpoint.Event.LocationDidChange, this._breakpointLocationDidChange, this); - this._breakpoint.addEventListener(WebInspector.Breakpoint.Event.DisabledStateDidChange, this._updateStatus, this); - this._breakpoint.addEventListener(WebInspector.Breakpoint.Event.AutoContinueDidChange, this._updateStatus, this); - this._breakpoint.addEventListener(WebInspector.Breakpoint.Event.ResolvedStateDidChange, this._updateStatus, this); - - this._statusImageElement = document.createElement("img"); - this._statusImageElement.className = WebInspector.BreakpointTreeElement.StatusImageElementStyleClassName; - this._statusImageElement.addEventListener("mousedown", this._statusImageElementMouseDown.bind(this)); - this._statusImageElement.addEventListener("click", this._statusImageElementClicked.bind(this)); - - if (!title) - this._updateTitles(); - this._updateStatus(); - - this.status = this._statusImageElement; - this.small = true; -}; - -WebInspector.BreakpointTreeElement.GenericLineIconStyleClassName = "breakpoint-generic-line-icon"; -WebInspector.BreakpointTreeElement.StyleClassName = "breakpoint"; -WebInspector.BreakpointTreeElement.StatusImageElementStyleClassName = "status-image"; -WebInspector.BreakpointTreeElement.StatusImageResolvedStyleClassName = "resolved"; -WebInspector.BreakpointTreeElement.StatusImageAutoContinueStyleClassName = "auto-continue"; -WebInspector.BreakpointTreeElement.StatusImageDisabledStyleClassName = "disabled"; -WebInspector.BreakpointTreeElement.FormattedLocationStyleClassName = "formatted-location"; - -WebInspector.BreakpointTreeElement.prototype = { - constructor: WebInspector.BreakpointTreeElement, - - // Public - - get breakpoint() - { - return this._breakpoint; - }, - - ondelete: function() - { - if (!WebInspector.debuggerManager.isBreakpointRemovable(this._breakpoint)) - return false; - - WebInspector.debuggerManager.removeBreakpoint(this._breakpoint); - return true; - }, - - onenter: function() - { - this._breakpoint.cycleToNextMode(); - return true; - }, - - onspace: function() - { - this._breakpoint.cycleToNextMode(); - return true; - }, - - oncontextmenu: function(event) - { - var contextMenu = new WebInspector.ContextMenu(event); - this._breakpoint.appendContextMenuItems(contextMenu, this._statusImageElement); - contextMenu.show(); - }, - - // Private - - _updateTitles: function() - { - var sourceCodeLocation = this._breakpoint.sourceCodeLocation; - - var displayLineNumber = sourceCodeLocation.displayLineNumber; - var displayColumnNumber = sourceCodeLocation.displayColumnNumber; - if (displayColumnNumber > 0) - this.mainTitle = WebInspector.UIString("Line %d:%d").format(displayLineNumber + 1, displayColumnNumber + 1); // The user visible line and column numbers are 1-based. - else - this.mainTitle = WebInspector.UIString("Line %d").format(displayLineNumber + 1); // The user visible line number is 1-based. - - if (sourceCodeLocation.hasMappedLocation()) { - this.subtitle = sourceCodeLocation.formattedLocationString(); - - if (sourceCodeLocation.hasFormattedLocation()) - this.subtitleElement.classList.add(WebInspector.BreakpointTreeElement.FormattedLocationStyleClassName); - else - this.subtitleElement.classList.remove(WebInspector.BreakpointTreeElement.FormattedLocationStyleClassName); - - this.tooltip = this.mainTitle + " \u2014 " + WebInspector.UIString("originally %s").format(sourceCodeLocation.originalLocationString()); - } - }, - - _updateStatus: function() - { - if (this._breakpoint.disabled) - this._statusImageElement.classList.add(WebInspector.BreakpointTreeElement.StatusImageDisabledStyleClassName); - else - this._statusImageElement.classList.remove(WebInspector.BreakpointTreeElement.StatusImageDisabledStyleClassName); - - if (this._breakpoint.autoContinue) - this._statusImageElement.classList.add(WebInspector.BreakpointTreeElement.StatusImageAutoContinueStyleClassName); - else - this._statusImageElement.classList.remove(WebInspector.BreakpointTreeElement.StatusImageAutoContinueStyleClassName); - - if (this._breakpoint.resolved) - this._statusImageElement.classList.add(WebInspector.BreakpointTreeElement.StatusImageResolvedStyleClassName); - else - this._statusImageElement.classList.remove(WebInspector.BreakpointTreeElement.StatusImageResolvedStyleClassName); - }, - - _breakpointLocationDidChange: function(event) - { - console.assert(event.target === this._breakpoint); - - // The Breakpoint has a new display SourceCode. The sidebar will remove us. Stop listening to the breakpoint. - if (event.data.oldDisplaySourceCode === this._breakpoint.displaySourceCode) { - this._breakpoint.addEventListener(WebInspector.Breakpoint.Event.LocationDidChange, this._breakpointLocationDidChange, this); - this._breakpoint.addEventListener(WebInspector.Breakpoint.Event.DisabledStateDidChange, this._updateStatus, this); - this._breakpoint.addEventListener(WebInspector.Breakpoint.Event.AutoContinueDidChange, this._updateStatus, this); - this._breakpoint.addEventListener(WebInspector.Breakpoint.Event.ResolvedStateDidChange, this._updateStatus, this); - return; - } - - this._updateTitles(); - }, - - _statusImageElementMouseDown: function(event) - { - // To prevent the tree element from selecting. - event.stopPropagation(); - }, - - _statusImageElementClicked: function(event) - { - this._breakpoint.cycleToNextMode(); - } -}; - -WebInspector.BreakpointTreeElement.prototype.__proto__ = WebInspector.GeneralTreeElement.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ButtonNavigationItem.css b/Source/WebInspectorUI/UserInterface/ButtonNavigationItem.css deleted file mode 100644 index c7d40a1d2..000000000 --- a/Source/WebInspectorUI/UserInterface/ButtonNavigationItem.css +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.navigation-bar .item.button { - width: 26px; -} - -.navigation-bar .item.button.text-only { - width: auto; - padding: 0 10px; - - text-shadow: rgba(255, 255, 255, 0.5) 0 1px 0; - font-family: "Lucida Grande", sans-serif; - font-size: 11px; - line-height: 20px; - - -webkit-justify-content: center; -} - -.navigation-bar .item.button > .glyph { - width: 100%; - height: 100%; - - background-repeat: no-repeat; - background-position: center center; -} - -body.window-inactive .navigation-bar .item.button:not(.suppress-emboss) > .glyph { - opacity: 0.65; -} - -.navigation-bar .item.button.disabled > .glyph { - opacity: 0.55 !important; -} - -body.window-inactive .navigation-bar .item.button.disabled:not(.suppress-emboss) > .glyph { - opacity: 0.35 !important; -} - -.navigation-bar .item.button.suppress-emboss > .glyph { - opacity: 0.7; -} - -.navigation-bar .item.button.suppress-emboss:active > .glyph { - opacity: 1; -} - -.navigation-bar .item.button.suppress-emboss.disabled > .glyph { - opacity: 0.3 !important; -} diff --git a/Source/WebInspectorUI/UserInterface/ButtonNavigationItem.js b/Source/WebInspectorUI/UserInterface/ButtonNavigationItem.js deleted file mode 100644 index 35ad4ce0f..000000000 --- a/Source/WebInspectorUI/UserInterface/ButtonNavigationItem.js +++ /dev/null @@ -1,208 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ButtonNavigationItem = function(identifier, toolTipOrLabel, image, imageWidth, imageHeight, suppressEmboss, role, label) { - WebInspector.NavigationItem.call(this, identifier); - - console.assert(identifier); - console.assert(toolTipOrLabel); - - this.toolTip = toolTipOrLabel; - - this._element.addEventListener("click", this._mouseClicked.bind(this)); - - this._element.setAttribute("role", role || "button"); - - if (label) - this._element.setAttribute("aria-label", label); - - this._imageWidth = imageWidth || 16; - this._imageHeight = imageHeight || 16; - this._suppressEmboss = suppressEmboss || false; - - if (suppressEmboss) - this._element.classList.add(WebInspector.ButtonNavigationItem.SuppressEmbossStyleClassName); - - if (image) - this.image = image; - else - this.label = toolTipOrLabel; -}; - -WebInspector.ButtonNavigationItem.StyleClassName = "button"; -WebInspector.ButtonNavigationItem.DisabledStyleClassName = "disabled"; -WebInspector.ButtonNavigationItem.SuppressBezelStyleClassName = "suppress-bezel"; -WebInspector.ButtonNavigationItem.SuppressEmbossStyleClassName = "suppress-emboss"; -WebInspector.ButtonNavigationItem.TextOnlyClassName = "text-only"; - -WebInspector.ButtonNavigationItem.States = {}; -WebInspector.ButtonNavigationItem.States.Normal = "normal"; -WebInspector.ButtonNavigationItem.States.Active = "active"; -WebInspector.ButtonNavigationItem.States.Focus = "focus"; -WebInspector.ButtonNavigationItem.States.ActiveFocus = "active-focus"; - -WebInspector.ButtonNavigationItem.Event = { - Clicked: "button-navigation-item-clicked" -}; - -WebInspector.ButtonNavigationItem.prototype = { - constructor: WebInspector.ButtonNavigationItem, - - // Public - - get toolTip() - { - return this._element.title; - }, - - set toolTip(newToolTip) - { - console.assert(newToolTip); - if (!newToolTip) - return; - - this._element.title = newToolTip; - }, - - get label() - { - return this._element.textContent; - }, - - set label(newLabel) - { - this._element.classList.add(WebInspector.ButtonNavigationItem.TextOnlyClassName); - this._element.textContent = newLabel || ""; - if (this.parentNavigationBar) - this.parentNavigationBar.updateLayout(); - }, - - get image() - { - return this._image; - }, - - set image(newImage) - { - if (!newImage) { - this._element.removeChildren(); - return; - } - - this._element.removeChildren(); - this._element.classList.remove(WebInspector.ButtonNavigationItem.TextOnlyClassName); - - this._image = newImage; - - this._glyphElement = document.createElement("div"); - this._glyphElement.className = "glyph"; - this._element.appendChild(this._glyphElement); - - this._updateImage(); - }, - - get enabled() - { - return !this._element.classList.contains(WebInspector.ButtonNavigationItem.DisabledStyleClassName); - }, - - set enabled(flag) - { - if (flag) - this._element.classList.remove(WebInspector.ButtonNavigationItem.DisabledStyleClassName); - else - this._element.classList.add(WebInspector.ButtonNavigationItem.DisabledStyleClassName); - }, - - get suppressBezel() - { - return this._element.classList.contains(WebInspector.ButtonNavigationItem.SuppressBezelStyleClassName); - }, - - set suppressBezel(flag) - { - if (flag) - this._element.classList.add(WebInspector.ButtonNavigationItem.SuppressBezelStyleClassName); - else - this._element.classList.remove(WebInspector.ButtonNavigationItem.SuppressBezelStyleClassName); - }, - - generateStyleText: function(parentSelector) - { - var classNames = this._classNames.join("."); - - if (this._suppressEmboss) - var styleText = parentSelector + " ." + classNames + " > .glyph { background-size: " + this._imageWidth + "px " + this._imageHeight + "px; }\n"; - else { - // Default state. - var styleText = parentSelector + " ." + classNames + " > .glyph { background-image: -webkit-canvas(" + this._canvasIdentifier() + "); background-size: " + this._imageWidth + "px " + this._imageHeight + "px; }\n"; - - // Pressed state. - styleText += parentSelector + " ." + classNames + ":not(.disabled):active > .glyph { background-image: -webkit-canvas(" + this._canvasIdentifier(WebInspector.ButtonNavigationItem.States.Active) + "); }\n"; - - // Focused state. - styleText += parentSelector + " ." + classNames + ":not(.disabled):focus > .glyph { background-image: -webkit-canvas(" + this._canvasIdentifier(WebInspector.ButtonNavigationItem.States.Focus) + "); }\n"; - } - - return styleText; - }, - - // Private - - _additionalClassNames: [WebInspector.ButtonNavigationItem.StyleClassName], - _embossedImageStates: WebInspector.ButtonNavigationItem.States, - _imageCacheable: true, - - _mouseClicked: function(event) - { - if (!this.enabled) - return; - this.dispatchEventToListeners(WebInspector.ButtonNavigationItem.Event.Clicked); - }, - - _canvasIdentifier: function(state) - { - console.assert(!this._suppressEmboss); - return "navigation-item-" + this._identifier + "-" + (state || WebInspector.ButtonNavigationItem.States.Normal); - }, - - _updateImage: function() - { - if (this._suppressEmboss) - this._glyphElement.style.backgroundImage = "url(" + this._image + ")"; - else - this._generateImages(); - }, - - _generateImages: function() - { - console.assert(!this._suppressEmboss); - if (this._suppressEmboss) - return; - generateEmbossedImages(this.image, this._imageWidth, this._imageHeight, this._embossedImageStates, this._canvasIdentifier.bind(this), !this._imageCacheable); - } -}; - -WebInspector.ButtonNavigationItem.prototype.__proto__ = WebInspector.NavigationItem.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ButtonToolbarItem.css b/Source/WebInspectorUI/UserInterface/ButtonToolbarItem.css deleted file mode 100644 index 0e7a8f9d1..000000000 --- a/Source/WebInspectorUI/UserInterface/ButtonToolbarItem.css +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.toolbar .item.button { - -webkit-align-items: center; - -webkit-justify-content: center; - - padding: 0 6px; -} - -.toolbar.icon-and-label-vertical .item.button { - -webkit-flex-direction: column; -} - -.toolbar.icon-and-label-horizontal .item.button { - -webkit-flex-direction: row; -} - -.toolbar .item.button > .glyph { - width: 32px; - height: 32px; - - background-size: 100% 100% !important; - - background-repeat: no-repeat; - background-position: center center; -} - -.toolbar.small-size .item.button > .glyph { - width: 24px; - height: 24px; -} - -.toolbar.label-only .item.button > .glyph { - display: none; -} - -.toolbar .item.button > .label { - font-size: 11px; - font-family: Lucida Grande, sans-serif; - text-align: center; - text-shadow: rgba(255, 255, 255, 0.5) 0 1px 0; - color: rgb(60, 60, 60); -} - -.toolbar.label-only .item.activate.button.activated > .label { - color: rgb(35, 125, 195); -} - -.toolbar.icon-and-label-horizontal .item.button > .label { - margin-left: 4px; -} - -.toolbar.icon-only .item.button > .label { - display: none; -} - -body.window-inactive .toolbar .item.button { - opacity: 0.65; -} - -.toolbar .item.button.disabled { - opacity: 0.55 !important; -} - -body.window-inactive .toolbar .item.button.disabled { - opacity: 0.35 !important; -} diff --git a/Source/WebInspectorUI/UserInterface/ButtonToolbarItem.js b/Source/WebInspectorUI/UserInterface/ButtonToolbarItem.js deleted file mode 100644 index 61c409e81..000000000 --- a/Source/WebInspectorUI/UserInterface/ButtonToolbarItem.js +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ButtonToolbarItem = function(identifier, toolTip, label, image, suppressEmboss, role) -{ - WebInspector.ButtonNavigationItem.call(this, identifier, toolTip, image, 32, 32, suppressEmboss, role); - - console.assert(label); - - this._labelElement = document.createElement("div"); - this._labelElement.className = WebInspector.ButtonToolbarItem.LabelStyleClassName; - this._element.appendChild(this._labelElement); - - this.label = label; -}; - -WebInspector.ButtonToolbarItem.LabelStyleClassName = "label"; - -WebInspector.ButtonToolbarItem.prototype = { - constructor: WebInspector.ButtonToolbarItem, - - // Public - - get label() - { - return this._labelElement.textContent; - }, - - set label(newLabel) - { - console.assert(newLabel); - if (!newLabel) - return; - - this._labelElement.textContent = newLabel; - } -}; - -WebInspector.ButtonToolbarItem.prototype.__proto__ = WebInspector.ButtonNavigationItem.prototype; diff --git a/Source/WebInspectorUI/UserInterface/CSSCompletions.js b/Source/WebInspectorUI/UserInterface/CSSCompletions.js deleted file mode 100644 index aef5e50f4..000000000 --- a/Source/WebInspectorUI/UserInterface/CSSCompletions.js +++ /dev/null @@ -1,272 +0,0 @@ -/* - * Copyright (C) 2010 Nikita Vasilyev. All rights reserved. - * Copyright (C) 2010 Joseph Pecoraro. All rights reserved. - * Copyright (C) 2010 Google Inc. All rights reserved. - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/** - * @constructor - */ -WebInspector.CSSCompletions = function(properties, acceptEmptyPrefix) -{ - this._values = []; - this._longhands = {}; - this._shorthands = {}; - - for (var i = 0; i < properties.length; ++i) { - // COMPATIBILITY (iOS 6): This used to be an array of strings, - // now it contains objects with a 'name' property. Support both here. - var property = properties[i]; - if (typeof property === "string") { - this._values.push(property); - continue; - } - - var propertyName = property.name; - this._values.push(propertyName); - - var longhands = property.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(); - - this._acceptEmptyPrefix = acceptEmptyPrefix; -} - - -/** - * @type {WebInspector.CSSCompletions} - */ -WebInspector.CSSCompletions.cssNameCompletions = null; - -WebInspector.CSSCompletions.requestCSSNameCompletions = function() -{ - function propertyNamesCallback(error, names) - { - if (error) - return; - - WebInspector.CSSCompletions.cssNameCompletions = new WebInspector.CSSCompletions(names, false); - - var propertyNamesForCodeMirror = {}; - var valueKeywordsForCodeMirror = {"inherit": true, "initial": true}; - var colorKeywordsForCodeMirror = {}; - - function nameForCodeMirror(name) - { - // CodeMirror parses the vendor prefix separate from the property or keyword name, - // so we need to strip vendor prefixes from our names. Also strip function parenthesis. - return name.replace(/^-[^-]+-/, "").replace(/\(\)$/, ""); - } - - function collectPropertyNameForCodeMirror(propertyName) - { - // Properties can also be value keywords, like when used in a transition. - // So we add them to both lists. - var codeMirrorPropertyName = nameForCodeMirror(propertyName); - propertyNamesForCodeMirror[codeMirrorPropertyName] = true; - valueKeywordsForCodeMirror[codeMirrorPropertyName] = true; - } - - for (var i = 0; i < names.length; ++i) { - // COMPATIBILITY (iOS 6): This used to be an array of strings, - // now it contains objects with a 'name' property. Support both here. - var property = names[i]; - if (typeof property === "string") - collectPropertyNameForCodeMirror(property); - else - collectPropertyNameForCodeMirror(property.name); - } - - for (var propertyName in WebInspector.CSSKeywordCompletions._propertyKeywordMap) { - var keywords = WebInspector.CSSKeywordCompletions._propertyKeywordMap[propertyName]; - for (var i = 0; i < keywords.length; ++i) { - // Skip numbers, like the ones defined for font-weight. - if (!isNaN(Number(keywords[i]))) - continue; - valueKeywordsForCodeMirror[nameForCodeMirror(keywords[i])] = true; - } - } - - WebInspector.CSSKeywordCompletions._colors.forEach(function(colorName) { - colorKeywordsForCodeMirror[nameForCodeMirror(colorName)] = true; - }); - - function updateCodeMirrorCSSMode(mimeType) - { - var modeSpec = CodeMirror.resolveMode(mimeType); - - console.assert(modeSpec.propertyKeywords); - console.assert(modeSpec.valueKeywords); - console.assert(modeSpec.colorKeywords); - - modeSpec.propertyKeywords = propertyNamesForCodeMirror; - modeSpec.valueKeywords = valueKeywordsForCodeMirror; - modeSpec.colorKeywords = colorKeywordsForCodeMirror; - - CodeMirror.defineMIME(mimeType, modeSpec); - } - - updateCodeMirrorCSSMode("text/css"); - updateCodeMirrorCSSMode("text/x-scss"); - } - - if (window.CSSAgent) - CSSAgent.getSupportedCSSProperties(propertyNamesCallback); -} - -WebInspector.CSSCompletions.prototype = { - get values() - { - return this._values; - }, - - 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; - }, - - firstStartsWith: function(prefix) - { - var foundIndex = this._firstIndexOfPrefix(prefix); - return (foundIndex === -1 ? "" : this._values[foundIndex]); - }, - - _firstIndexOfPrefix: function(prefix) - { - if (!this._values.length) - return -1; - if (!prefix) - return this._acceptEmptyPrefix ? 0 : -1; - - 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]; - }, - - isShorthandPropertyName: function(shorthand) - { - return shorthand in this._longhands; - }, - - isLonghandPropertyName: function(longhand) - { - return longhand in this._shorthands; - }, - - longhandsForShorthand: function(shorthand) - { - return this._longhands[shorthand] || []; - }, - - shorthandsForLonghand: function(longhand) - { - return this._shorthands[longhand] || []; - } -} diff --git a/Source/WebInspectorUI/UserInterface/CSSKeywordCompletions.js b/Source/WebInspectorUI/UserInterface/CSSKeywordCompletions.js deleted file mode 100644 index 18d0b4940..000000000 --- a/Source/WebInspectorUI/UserInterface/CSSKeywordCompletions.js +++ /dev/null @@ -1,902 +0,0 @@ -/* - * Copyright (C) 2011 Google Inc. All rights reserved. - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.CSSKeywordCompletions = {}; - -WebInspector.CSSKeywordCompletions.forProperty = function(propertyName) -{ - var acceptedKeywords = ["initial"]; - var isNotPrefixed = propertyName.charAt(0) !== "-"; - - if (propertyName in WebInspector.CSSKeywordCompletions._propertyKeywordMap) - acceptedKeywords = acceptedKeywords.concat(WebInspector.CSSKeywordCompletions._propertyKeywordMap[propertyName]); - else if (isNotPrefixed && ("-webkit-" + propertyName) in WebInspector.CSSKeywordCompletions._propertyKeywordMap) - acceptedKeywords = acceptedKeywords.concat(WebInspector.CSSKeywordCompletions._propertyKeywordMap["-webkit-" + propertyName]); - - if (propertyName in WebInspector.CSSKeywordCompletions._colorAwareProperties) - acceptedKeywords = acceptedKeywords.concat(WebInspector.CSSKeywordCompletions._colors); - else if (isNotPrefixed && ("-webkit-" + propertyName) in WebInspector.CSSKeywordCompletions._colorAwareProperties) - acceptedKeywords = acceptedKeywords.concat(WebInspector.CSSKeywordCompletions._colors); - - // Only suggest "inherit" on inheritable properties even though it is valid on all properties. - if (propertyName in WebInspector.CSSKeywordCompletions.InheritedProperties) - acceptedKeywords.push("inherit"); - else if (isNotPrefixed && ("-webkit-" + propertyName) in WebInspector.CSSKeywordCompletions.InheritedProperties) - acceptedKeywords.push("inherit"); - - if (acceptedKeywords.contains(WebInspector.CSSKeywordCompletions.AllPropertyNamesPlaceholder)) { - acceptedKeywords.remove(WebInspector.CSSKeywordCompletions.AllPropertyNamesPlaceholder); - acceptedKeywords = acceptedKeywords.concat(WebInspector.CSSCompletions.cssNameCompletions.values); - } - - return new WebInspector.CSSCompletions(acceptedKeywords, true); -} - -WebInspector.CSSKeywordCompletions.isColorAwareProperty = function(propertyName) -{ - return WebInspector.CSSKeywordCompletions._colorAwareProperties[propertyName] === true; -} - -WebInspector.CSSKeywordCompletions.AllPropertyNamesPlaceholder = "__all-properties__"; - -WebInspector.CSSKeywordCompletions.InheritedProperties = [ - "azimuth", "border-collapse", "border-spacing", "caption-side", "clip-rule", "color", "color-interpolation", - "color-interpolation-filters", "color-rendering", "cursor", "direction", "elevation", "empty-cells", "fill", - "fill-opacity", "fill-rule", "font", "font-family", "font-size", "font-style", "font-variant", "font-weight", - "glyph-orientation-horizontal", "glyph-orientation-vertical", "image-rendering", "kerning", "letter-spacing", - "line-height", "list-style", "list-style-image", "list-style-position", "list-style-type", "marker", "marker-end", - "marker-mid", "marker-start", "orphans", "pitch", "pitch-range", "pointer-events", "quotes", "resize", "richness", - "shape-rendering", "speak", "speak-header", "speak-numeral", "speak-punctuation", "speech-rate", "stress", "stroke", - "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", - "stroke-width", "tab-size", "text-align", "text-anchor", "text-decoration", "text-indent", "text-rendering", - "text-shadow", "text-transform", "visibility", "voice-family", "volume", "white-space", "widows", "word-break", - "word-spacing", "word-wrap", "writing-mode", "-webkit-aspect-ratio", "-webkit-border-horizontal-spacing", - "-webkit-border-vertical-spacing", "-webkit-box-direction", "-webkit-color-correction", "-webkit-font-feature-settings", - "-webkit-font-kerning", "-webkit-font-smoothing", "-webkit-font-variant-ligatures", "-webkit-highlight", - "-webkit-hyphenate-character", "-webkit-hyphenate-limit-after", "-webkit-hyphenate-limit-before", - "-webkit-hyphenate-limit-lines", "-webkit-hyphens", "-webkit-line-align", "-webkit-line-box-contain", - "-webkit-line-break", "-webkit-line-grid", "-webkit-line-snap", "-webkit-locale", "-webkit-nbsp-mode", - "-webkit-print-color-adjust", "-webkit-rtl-ordering", "-webkit-text-combine", "-webkit-text-decorations-in-effect", - "-webkit-text-emphasis", "-webkit-text-emphasis-color", "-webkit-text-emphasis-position", "-webkit-text-emphasis-style", - "-webkit-text-fill-color", "-webkit-text-orientation", "-webkit-text-security", "-webkit-text-size-adjust", - "-webkit-text-stroke", "-webkit-text-stroke-color", "-webkit-text-stroke-width", "-webkit-user-modify", - "-webkit-user-select", "-webkit-writing-mode", "-webkit-cursor-visibility", "image-orientation", "image-resolution", - "overflow-wrap", "-webkit-text-align-last", "-webkit-text-justify", "-webkit-ruby-position", "-webkit-text-decoration-line", - - // iOS Properties - "-webkit-overflow-scrolling", "-webkit-touch-callout", "-webkit-tap-highlight-color" -].keySet(); - -WebInspector.CSSKeywordCompletions._colors = [ - "aqua", "black", "blue", "fuchsia", "gray", "green", "lime", "maroon", "navy", "olive", "orange", "purple", "red", - "silver", "teal", "white", "yellow", "transparent", "currentcolor", "grey", "aliceblue", "antiquewhite", - "aquamarine", "azure", "beige", "bisque", "blanchedalmond", "blueviolet", "brown", "burlywood", "cadetblue", - "chartreuse", "chocolate", "coral", "cornflowerblue", "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", - "darkgoldenrod", "darkgray", "darkgreen", "darkgrey", "darkkhaki", "darkmagenta", "darkolivegreen", "darkorange", - "darkorchid", "darkred", "darksalmon", "darkseagreen", "darkslateblue", "darkslategray", "darkslategrey", - "darkturquoise", "darkviolet", "deeppink", "deepskyblue", "dimgray", "dimgrey", "dodgerblue", "firebrick", - "floralwhite", "forestgreen", "gainsboro", "ghostwhite", "gold", "goldenrod", "greenyellow", "honeydew", "hotpink", - "indianred", "indigo", "ivory", "khaki", "lavender", "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", - "lightcoral", "lightcyan", "lightgoldenrodyellow", "lightgray", "lightgreen", "lightgrey", "lightpink", - "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray", "lightslategrey", "lightsteelblue", "lightyellow", - "limegreen", "linen", "magenta", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple", "mediumseagreen", - "mediumslateblue", "mediumspringgreen", "mediumturquoise", "mediumvioletred", "midnightblue", "mintcream", - "mistyrose", "moccasin", "navajowhite", "oldlace", "olivedrab", "orangered", "orchid", "palegoldenrod", "palegreen", - "paleturquoise", "palevioletred", "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue", "rosybrown", - "royalblue", "saddlebrown", "salmon", "sandybrown", "seagreen", "seashell", "sienna", "skyblue", "slateblue", - "slategray", "slategrey", "snow", "springgreen", "steelblue", "tan", "thistle", "tomato", "turquoise", "violet", - "wheat", "whitesmoke", "yellowgreen", "rgb()", "rgba()", "hsl()", "hsla()" -]; - -WebInspector.CSSKeywordCompletions._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-line-through", "text-line-through-color", "text-overline", "text-overline-color", - "text-shadow", "text-underline", "text-underline-color", "-webkit-box-shadow", "-webkit-column-rule", "-webkit-column-rule-color", - "-webkit-text-emphasis", "-webkit-text-emphasis-color", "-webkit-text-fill-color", "-webkit-text-stroke", "-webkit-text-stroke-color", - "-webkit-text-decoration-color", - - // iOS Properties - "-webkit-tap-highlight-color" -].keySet(); - -WebInspector.CSSKeywordCompletions._propertyKeywordMap = { - "table-layout": [ - "auto", "fixed" - ], - "visibility": [ - "hidden", "visible", "collapse" - ], - "background-repeat": [ - "repeat", "repeat-x", "repeat-y", "no-repeat", "space", "round" - ], - "text-underline": [ - "none", "dotted", "dashed", "solid", "double", "dot-dash", "dot-dot-dash", "wave" - ], - "content": [ - "list-item", "close-quote", "no-close-quote", "no-open-quote", "open-quote", "attr()", "counter()", "counters()", "url()", "linear-gradient()", "radial-gradient()", "repeating-linear-gradient()", "repeating-radial-gradient()", "-webkit-canvas()", "-webkit-cross-fade()", "-webkit-image-set()" - ], - "list-style-image": [ - "none", "url()", "linear-gradient()", "radial-gradient()", "repeating-linear-gradient()", "repeating-radial-gradient()", "-webkit-canvas()", "-webkit-cross-fade()", "-webkit-image-set()" - ], - "clear": [ - "none", "left", "right", "both" - ], - "stroke-linejoin": [ - "round", "miter", "bevel" - ], - "baseline-shift": [ - "baseline", "sub", "super" - ], - "border-bottom-width": [ - "medium", "thick", "thin", "calc()", "-webkit-calc()" - ], - "margin-top-collapse": [ - "collapse", "separate", "discard" - ], - "-webkit-box-orient": [ - "horizontal", "vertical", "inline-axis", "block-axis" - ], - "font-stretch": [ - "normal", "wider", "narrower", "ultra-condensed", "extra-condensed", "condensed", "semi-condensed", - "semi-expanded", "expanded", "extra-expanded", "ultra-expanded" - ], - "-webkit-color-correction": [ - "default", "srgb" - ], - "border-left-width": [ - "medium", "thick", "thin", "calc()", "-webkit-calc()" - ], - "-webkit-writing-mode": [ - "lr", "rl", "tb", "lr-tb", "rl-tb", "tb-rl", "horizontal-tb", "vertical-rl", "vertical-lr", "horizontal-bt" - ], - "text-line-through-mode": [ - "continuous", "skip-white-space" - ], - "text-overline-mode": [ - "continuous", "skip-white-space" - ], - "text-underline-mode": [ - "continuous", "skip-white-space" - ], - "text-line-through-style": [ - "none", "dotted", "dashed", "solid", "double", "dot-dash", "dot-dot-dash", "wave" - ], - "text-overline-style": [ - "none", "dotted", "dashed", "solid", "double", "dot-dash", "dot-dot-dash", "wave" - ], - "text-underline-style": [ - "none", "dotted", "dashed", "solid", "double", "dot-dash", "dot-dot-dash", "wave" - ], - "border-collapse": [ - "collapse", "separate" - ], - "border-top-width": [ - "medium", "thick", "thin", "calc()", "-webkit-calc()" - ], - "outline-color": [ - "invert", "-webkit-focus-ring-color" - ], - "outline-style": [ - "none", "hidden", "inset", "groove", "ridge", "outset", "dotted", "dashed", "solid", "double", "auto" - ], - "cursor": [ - "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", "url()", "-webkit-image-set()" - ], - "border-width": [ - "medium", "thick", "thin", "calc()", "-webkit-calc()" - ], - "size": [ - "a3", "a4", "a5", "b4", "b5", "landscape", "ledger", "legal", "letter", "portrait" - ], - "background-image": [ - "url()", "linear-gradient()", "radial-gradient()", "repeating-linear-gradient()", "repeating-radial-gradient()", "-webkit-canvas()", "-webkit-cross-fade()", "-webkit-image-set()" - ], - "background-size": [ - "contain", "cover" - ], - "direction": [ - "ltr", "rtl" - ], - "enable-background": [ - "accumulate", "new" - ], - "float": [ - "none", "left", "right" - ], - "overflow-x": [ - "hidden", "auto", "visible", "overlay", "scroll", "marquee" - ], - "overflow-y": [ - "hidden", "auto", "visible", "overlay", "scroll", "marquee", "-webkit-paged-x", "-webkit-paged-y" - ], - "overflow": [ - "hidden", "auto", "visible", "overlay", "scroll", "marquee", "-webkit-paged-x", "-webkit-paged-y" - ], - "margin-bottom-collapse": [ - "collapse", "separate", "discard" - ], - "-webkit-box-reflect": [ - "none", "left", "right", "above", "below" - ], - "text-rendering": [ - "auto", "optimizeSpeed", "optimizeLegibility", "geometricPrecision" - ], - "text-align": [ - "-webkit-auto", "left", "right", "center", "justify", "-webkit-left", "-webkit-right", "-webkit-center", "-webkit-match-parent", "start", "end" - ], - "list-style-position": [ - "outside", "inside" - ], - "margin-bottom": [ - "auto" - ], - "color-interpolation": [ - "linearrgb" - ], - "background-origin": [ - "border-box", "content-box", "padding-box" - ], - "word-wrap": [ - "normal", "break-word" - ], - "font-weight": [ - "normal", "bold", "bolder", "lighter", "100", "200", "300", "400", "500", "600", "700", "800", "900" - ], - "margin-before-collapse": [ - "collapse", "separate", "discard" - ], - "text-overline-width": [ - "normal", "medium", "auto", "thick", "thin", "calc()", "-webkit-calc()" - ], - "text-transform": [ - "none", "capitalize", "uppercase", "lowercase" - ], - "border-right-style": [ - "none", "hidden", "inset", "groove", "ridge", "outset", "dotted", "dashed", "solid", "double" - ], - "border-left-style": [ - "none", "hidden", "inset", "groove", "ridge", "outset", "dotted", "dashed", "solid", "double" - ], - "font-style": [ - "italic", "oblique", "normal" - ], - "speak": [ - "none", "normal", "spell-out", "digits", "literal-punctuation", "no-punctuation" - ], - "text-line-through": [ - "none", "dotted", "dashed", "solid", "double", "dot-dash", "dot-dot-dash", "wave", "continuous", - "skip-white-space" - ], - "color-rendering": [ - "auto", "optimizeSpeed", "optimizeQuality" - ], - "list-style-type": [ - "none", "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": [ - "none", "horizontal" - ], - "outline": [ - "none", "hidden", "inset", "groove", "ridge", "outset", "dotted", "dashed", "solid", "double" - ], - "font": [ - "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", "-webkit-system-font", "-apple-system-headline", - "-apple-system-body", "-apple-system-subheadline", "-apple-system-footnote", "-apple-system-caption1", - "-apple-system-caption2", "-apple-system-short-headline", "-apple-system-short-body", - "-apple-system-short-subheadline", "-apple-system-short-footnote", "-apple-system-short-caption1", - "-apple-system-tall-body" - ], - "dominant-baseline": [ - "middle", "auto", "central", "text-before-edge", "text-after-edge", "ideographic", "alphabetic", "hanging", - "mathematical", "use-script", "no-change", "reset-size" - ], - "display": [ - "none", "inline", "block", "list-item", "run-in", "compact", "inline-block", "table", "inline-table", - "table-row-group", "table-header-group", "table-footer-group", "table-row", "table-column-group", - "table-column", "table-cell", "table-caption", "-webkit-box", "-webkit-inline-box", "-wap-marquee", - "-webkit-flex", "-webkit-inline-flex", "-webkit-grid", "-webkit-inline-grid" - ], - "image-rendering": [ - "auto", "optimizeSpeed", "optimizeQuality", "-webkit-crisp-edges", "-webkit-optimize-contrast" - ], - "alignment-baseline": [ - "baseline", "middle", "auto", "before-edge", "after-edge", "central", "text-before-edge", "text-after-edge", - "ideographic", "alphabetic", "hanging", "mathematical" - ], - "outline-width": [ - "medium", "thick", "thin", "calc()", "-webkit-calc()" - ], - "text-line-through-width": [ - "normal", "medium", "auto", "thick", "thin" - ], - "box-align": [ - "baseline", "center", "stretch", "start", "end" - ], - "box-shadow": [ - "none" - ], - "text-shadow": [ - "none" - ], - "-webkit-box-shadow": [ - "none" - ], - "border-right-width": [ - "medium", "thick", "thin" - ], - "border-top-style": [ - "none", "hidden", "inset", "groove", "ridge", "outset", "dotted", "dashed", "solid", "double" - ], - "line-height": [ - "normal" - ], - "counter-increment": [ - "none" - ], - "counter-reset": [ - "none" - ], - "text-overflow": [ - "clip", "ellipsis" - ], - "-webkit-box-direction": [ - "normal", "reverse" - ], - "margin-after-collapse": [ - "collapse", "separate", "discard" - ], - "page-break-after": [ - "left", "right", "auto", "always", "avoid" - ], - "page-break-before": [ - "left", "right", "auto", "always", "avoid" - ], - "page-break-inside": [ - "auto", "avoid" - ], - "-webkit-column-break-after": [ - "left", "right", "auto", "always", "avoid" - ], - "-webkit-column-break-before": [ - "left", "right", "auto", "always", "avoid" - ], - "-webkit-column-break-inside": [ - "auto", "avoid" - ], - "-webkit-hyphens": [ - "none", "auto", "manual" - ], - "border-image": [ - "repeat", "stretch", "url()", "linear-gradient()", "radial-gradient()", "repeating-linear-gradient()", "repeating-radial-gradient()", "-webkit-canvas()", "-webkit-cross-fade()", "-webkit-image-set()" - ], - "border-image-repeat": [ - "repeat", "stretch", "space", "round" - ], - "-webkit-mask-box-image-repeat": [ - "repeat", "stretch", "space", "round" - ], - "position": [ - "absolute", "fixed", "relative", "static", "-webkit-sticky" - ], - "font-family": [ - "serif", "sans-serif", "cursive", "fantasy", "monospace", "-webkit-body", "-webkit-pictograph", "-webkit-system-font" - ], - "text-overflow-mode": [ - "clip", "ellipsis" - ], - "border-bottom-style": [ - "none", "hidden", "inset", "groove", "ridge", "outset", "dotted", "dashed", "solid", "double" - ], - "unicode-bidi": [ - "normal", "bidi-override", "embed", "-webkit-plaintext", "-webkit-isolate", "-webkit-isolate-override" - ], - "clip-rule": [ - "nonzero", "evenodd" - ], - "margin-left": [ - "auto" - ], - "margin-top": [ - "auto" - ], - "zoom": [ - "normal", "document", "reset" - ], - "z-index": [ - "auto" - ], - "width": [ - "intrinsic", "min-intrinsic", "-webkit-min-content", "-webkit-max-content", "-webkit-fill-available", "-webkit-fit-content", "calc()", "-webkit-calc()" - ], - "height": [ - "intrinsic", "min-intrinsic", "calc()", "-webkit-calc()" - ], - "max-width": [ - "none", "intrinsic", "min-intrinsic", "-webkit-min-content", "-webkit-max-content", "-webkit-fill-available", "-webkit-fit-content", "calc()", "-webkit-calc()" - ], - "min-width": [ - "intrinsic", "min-intrinsic", "-webkit-min-content", "-webkit-max-content", "-webkit-fill-available", "-webkit-fit-content", "calc()", "-webkit-calc()" - ], - "max-height": [ - "none", "intrinsic", "min-intrinsic", "calc()", "-webkit-calc()" - ], - "min-height": [ - "intrinsic", "min-intrinsic", "calc()", "-webkit-calc()" - ], - "-webkit-logical-width": [ - "intrinsic", "min-intrinsic", "-webkit-min-content", "-webkit-max-content", "-webkit-fill-available", "-webkit-fit-content", "calc()", "-webkit-calc()" - ], - "-webkit-logical-height": [ - "intrinsic", "min-intrinsic", "calc()", "-webkit-calc()" - ], - "-webkit-max-logical-width": [ - "none", "intrinsic", "min-intrinsic", "-webkit-min-content", "-webkit-max-content", "-webkit-fill-available", "-webkit-fit-content", "calc()", "-webkit-calc()" - ], - "-webkit-min-logical-width": [ - "intrinsic", "min-intrinsic", "-webkit-min-content", "-webkit-max-content", "-webkit-fill-available", "-webkit-fit-content", "calc()", "-webkit-calc()" - ], - "-webkit-max-logical-height": [ - "none", "intrinsic", "min-intrinsic", "calc()", "-webkit-calc()" - ], - "-webkit-min-logical-height": [ - "intrinsic", "min-intrinsic", "calc()", "-webkit-calc()" - ], - "empty-cells": [ - "hide", "show" - ], - "pointer-events": [ - "none", "all", "auto", "visible", "visiblepainted", "visiblefill", "visiblestroke", "painted", "fill", "stroke" - ], - "letter-spacing": [ - "normal", "calc()", "-webkit-calc()" - ], - "word-spacing": [ - "normal", "calc()", "-webkit-calc()" - ], - "background-clip": [ - "border-box", "content-box", "padding-box" - ], - "-webkit-font-kerning": [ - "auto", "normal", "none" - ], - "-webkit-font-smoothing": [ - "none", "auto", "antialiased", "subpixel-antialiased" - ], - "border": [ - "none", "hidden", "inset", "groove", "ridge", "outset", "dotted", "dashed", "solid", "double" - ], - "font-size": [ - "xx-small", "x-small", "small", "medium", "large", "x-large", "xx-large", "-webkit-xxx-large", "smaller", - "larger" - ], - "font-variant": [ - "small-caps", "normal" - ], - "vertical-align": [ - "baseline", "middle", "sub", "super", "text-top", "text-bottom", "top", "bottom", "-webkit-baseline-middle" - ], - "white-space": [ - "normal", "nowrap", "pre", "pre-line", "pre-wrap" - ], - "word-break": [ - "normal", "break-all", "break-word" - ], - "text-underline-width": [ - "normal", "medium", "auto", "thick", "thin", "calc()", "-webkit-calc()" - ], - "text-indent": [ - "-webkit-each-line", "-webkit-hanging" - ], - "-webkit-box-lines": [ - "single", "multiple" - ], - "clip": [ - "auto", "rect()" - ], - "clip-path": [ - "none", "url()", "rectangle()", "circle()", "ellipse()", "polygon()", "inset-rectangle()" - ], - "orphans": [ - "auto" - ], - "widows": [ - "auto" - ], - "margin": [ - "auto" - ], - "page": [ - "auto" - ], - "-webkit-marquee-increment": [ - "small", "large", "medium" - ], - "-webkit-marquee-direction": [ - "left", "right", "auto", "reverse", "forwards", "backwards", "ahead", "up", "down" - ], - "-webkit-marquee-style": [ - "none", "scroll", "slide", "alternate" - ], - "-webkit-marquee-repetition": [ - "infinite" - ], - "-webkit-marquee-speed": [ - "normal", "slow", "fast" - ], - "margin-right": [ - "auto" - ], - "marquee-speed": [ - "normal", "slow", "fast" - ], - "-webkit-text-emphasis": [ - "circle", "filled", "open", "dot", "double-circle", "triangle", "sesame" - ], - "-webkit-text-emphasis-style": [ - "circle", "filled", "open", "dot", "double-circle", "triangle", "sesame" - ], - "-webkit-text-emphasis-position": [ - "over", "under" - ], - "-webkit-transform": [ - "none", - "scale()", "scaleX()", "scaleY()", "scale3d()", "rotate()", "rotateX()", "rotateY()", "rotateZ()", "rotate3d()", "skew()", "skewX()", "skewY()", - "translate()", "translateX()", "translateY()", "translateZ()", "translate3d()", "matrix()", "matrix3d()", "perspective()" - ], - "-webkit-cursor-visibility": [ - "auto", "auto-hide" - ], - "text-decoration": [ - "none", "underline", "overline", "line-through", "blink" - ], - "-webkit-text-decorations-in-effect": [ - "none", "underline", "overline", "line-through", "blink", - ], - "-webkit-text-decoration-line": [ - "none", "underline", "overline", "line-through", "blink", - ], - "-webkit-text-decoration-style": [ - "solid", "double", "dotted", "dashed", "wavy" - ], - "-webkit-text-underline-position": [ - "auto", "alphabetic", "under" - ], - "image-resolution": [ - "from-image", "snap" - ], - "-webkit-blend-mode": [ - "normal", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "hue", "saturation", "color", "luminosity", - ], - "-webkit-background-blend-mode": [ - "normal", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "hue", "saturation", "color", "luminosity", - ], - "mix": [ - "auto", - "normal", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "hue", "saturation", "color", "luminosity", - "clear", "copy", "destination", "source-over", "destination-over", "source-in", "destination-in", "source-out", "destination-out", "source-atop", "destination-atop", "xor" - ], - "geometry": [ - "detached", "attached", "grid()" - ], - "overflow-wrap": [ - "normal", "break-word" - ], - "transition": [ - "none", "ease", "linear", "ease-in", "ease-out", "ease-in-out", "step-start", "step-end", "steps()", "cubic-bezier()", "all", WebInspector.CSSKeywordCompletions.AllPropertyNamesPlaceholder - ], - "transition-timing-function": [ - "ease", "linear", "ease-in", "ease-out", "ease-in-out", "step-start", "step-end", "steps()", "cubic-bezier()" - ], - "transition-property": [ - "all", "none", WebInspector.CSSKeywordCompletions.AllPropertyNamesPlaceholder - ], - "-webkit-column-progression": [ - "normal", "reverse" - ], - "-webkit-box-decoration-break": [ - "slice", "clone" - ], - "-webkit-align-content": [ - "flex-start", "flex-end", "center", "space-between", "space-around", "stretch" - ], - "-webkit-align-items": [ - "flex-start", "flex-end", "center", "baseline", "stretch" - ], - "-webkit-align-self": [ - "auto", "flex-start", "flex-end", "center", "baseline", "stretch" - ], - "-webkit-justify-content": [ - "flex-start", "flex-end", "center", "space-between", "space-around" - ], - "-webkit-flex-direction": [ - "row", "row-reverse", "column", "column-reverse" - ], - "-webkit-flex-wrap": [ - "nowrap", "wrap", "wrap-reverse" - ], - "-webkit-flex-flow": [ - "row", "row-reverse", "column", "column-reverse", - "nowrap", "wrap", "wrap-reverse" - ], - "-webkit-flex": [ - "none" - ], - "-webkit-flex-basis": [ - "auto" - ], - "-webkit-grid-after": [ - "auto" - ], - "-webkit-grid-before": [ - "auto" - ], - "-webkit-grid-end": [ - "auto" - ], - "-webkit-grid-start": [ - "auto" - ], - "-webkit-grid-auto-flow": [ - "none", "rows", "columns" - ], - "-webkit-grid-column": [ - "auto" - ], - "-webkit-grid-row": [ - "auto" - ], - "-webkit-grid-columns": [ - "auto", "-webkit-max-content", "-webkit-min-content" - ], - "-webkit-grid-rows": [ - "auto", "-webkit-max-content", "-webkit-min-content" - ], - "-webkit-ruby-position": [ - "after", "before" - ], - "-webkit-text-align-last": [ - "auto", "start", "end", "left", "right", "center", "justify" - ], - "-webkit-text-justify": [ - "auto", "none", "inter-word", "inter-ideograph", "inter-cluster", "distribute", "kashida" - ], - "max-zoom": [ - "auto" - ], - "min-zoom": [ - "auto" - ], - "orientation": [ - "auto", "portait", "landscape" - ], - "user-zoom": [ - "zoom", "fixed" - ], - "-webkit-app-region": [ - "drag", "no-drag" - ], - "-webkit-line-break": [ - "auto", "loose", "normal", "strict", "after-white-space" - ], - "-webkit-background-composite": [ - "clear", "copy", "source-over", "source-in", "source-out", "source-atop", "destination-over", "destination-in", "destination-out", "destination-atop", "xor", "plus-darker", "plus-lighter" - ], - "-webkit-mask-composite": [ - "clear", "copy", "source-over", "source-in", "source-out", "source-atop", "destination-over", "destination-in", "destination-out", "destination-atop", "xor", "plus-darker", "plus-lighter" - ], - "-webkit-animation-direction": [ - "normal", "alternate", "reverse", "alternate-reverse" - ], - "-webkit-animation-fill-mode": [ - "none", "forwards", "backwards", "both" - ], - "-webkit-animation-iteration-count": [ - "infinite" - ], - "-webkit-animation-play-state": [ - "paused", "running" - ], - "-webkit-animation-timing-function": [ - "ease", "linear", "ease-in", "ease-out", "ease-in-out", "step-start", "step-end", "steps()", "cubic-bezier()" - ], - "-webkit-column-span": [ - "all", "none", "calc()", "-webkit-calc()" - ], - "-webkit-region-break-after": [ - "auto", "always", "avoid", "left", "right" - ], - "-webkit-region-break-before": [ - "auto", "always", "avoid", "left", "right" - ], - "-webkit-region-break-inside": [ - "auto", "avoid" - ], - "-webkit-region-overflow": [ - "auto", "break" - ], - "-webkit-wrap-flow": [ - "auto", "both", "start", "end", "maximum", "clear" - ], - "-webkit-wrap-through": [ - "wrap", "none" - ], - "-webkit-backface-visibility": [ - "visible", "hidden" - ], - "resize": [ - "none", "both", "horizontal", "vertical", "auto" - ], - "caption-side": [ - "top", "bottom", "left", "right" - ], - "box-sizing": [ - "border-box", "content-box" - ], - "-webkit-border-fit": [ - "border", "lines" - ], - "-webkit-line-align": [ - "none", "edges" - ], - "-webkit-line-snap": [ - "none", "baseline", "contain" - ], - "-webkit-nbsp-mode": [ - "normal", "space" - ], - "-webkit-print-color-adjust": [ - "exact", "economy" - ], - "-webkit-rtl-ordering": [ - "logical", "visual" - ], - "-webkit-text-security": [ - "disc", "circle", "square", "none" - ], - "-webkit-transform-style": [ - "flat", "preserve-3d" - ], - "-webkit-user-drag": [ - "auto", "none", "element" - ], - "-webkit-user-modify": [ - "read-only", "read-write", "read-write-plaintext-only" - ], - "-webkit-text-stroke-width": [ - "medium", "thick", "thin", "calc()", "-webkit-calc()" - ], - "-webkit-border-start-width": [ - "medium", "thick", "thin", "calc()", "-webkit-calc()" - ], - "-webkit-border-end-width": [ - "medium", "thick", "thin", "calc()", "-webkit-calc()" - ], - "-webkit-border-before-width": [ - "medium", "thick", "thin", "calc()", "-webkit-calc()" - ], - "-webkit-border-after-width": [ - "medium", "thick", "thin", "calc()", "-webkit-calc()" - ], - "-webkit-column-rule-width": [ - "medium", "thick", "thin", "calc()", "-webkit-calc()" - ], - "-webkit-aspect-ratio": [ - "none" - ], - "-webkit-filter": [ - "none", "grayscale()", "sepia()", "saturate()", "hue-rotate()", "invert()", "opacity()", "brightness()", "contrast()", "blur()", "drop-shadow()", "custom()" - ], - "-webkit-perspective": [ - "none" - ], - "-webkit-column-count": [ - "auto", "calc()", "-webkit-calc()" - ], - "-webkit-column-gap": [ - "normal", "calc()", "-webkit-calc()" - ], - "-webkit-column-axis": [ - "horizontal", "vertical", "auto" - ], - "-webkit-column-width": [ - "auto", "calc()", "-webkit-calc()" - ], - "-webkit-highlight": [ - "none" - ], - "-webkit-hyphenate-character": [ - "none" - ], - "-webkit-hyphenate-limit-after": [ - "auto" - ], - "-webkit-hyphenate-limit-before": [ - "auto" - ], - "-webkit-hyphenate-limit-lines": [ - "no-limit" - ], - "-webkit-line-grid": [ - "none" - ], - "-webkit-locale": [ - "auto" - ], - "-webkit-text-orientation": [ - "sideways", "sideways-right", "vertical-right", "upright" - ], - "-webkit-line-box-contain": [ - "block", "inline", "font", "glyphs", "replaced", "inline-box", "none", "initial" - ], - "-webkit-font-feature-settings": [ - "normal" - ], - "-webkit-font-variant-ligatures": [ - "normal", "common-ligatures", "no-common-ligatures", "discretionary-ligatures", "no-discretionary-ligatures", "historical-ligatures", "no-historical-ligatures" - ], - /* - "-webkit-appearance": [ - "none", "checkbox", "radio", "push-button", "square-button", "button", "button-bevel", "default-button", "inner-spin-button", "-webkit-input-speech-button", "listbox", "listitem", "media-enter-fullscreen-button", "media-exit-fullscreen-button", "media-fullscreen-volume-slider", "media-fullscreen-volume-slider-thumb", "media-mute-button", "media-play-button", "media-overlay-play-button", "media-seek-back-button", "media-seek-forward-button", "media-rewind-button", "media-return-to-realtime-button", "media-toggle-closed-captions-button", "media-slider", "media-sliderthumb", "media-volume-slider-container", "media-volume-slider", "media-volume-sliderthumb", "media-volume-slider-mute-button", "media-controls-background", "media-controls-fullscreen-background", "media-current-time-display", "media-time-remaining-display", "menulist", "menulist-button", "menulist-text", "menulist-textfield", "meter", "progress-bar", "progress-bar-value", "slider-horizontal", "slider-vertical", "sliderthumb-horizontal", "sliderthumb-vertical", "caret", "searchfield", "searchfield-decoration", "searchfield-results-decoration", "searchfield-results-button", "searchfield-cancel-button", "snapshotted-plugin-overlay", "textfield", "relevancy-level-indicator", "continuous-capacity-level-indicator", "discrete-capacity-level-indicator", "rating-level-indicator", "textarea" - ], - */ - - // iOS Properties - "-webkit-text-size-adjust": [ - "none", "auto" - ], - "-webkit-touch-callout": [ - "default", "none" - ], - "-webkit-overflow-scrolling": [ - "auto", "touch" - ] -}; diff --git a/Source/WebInspectorUI/UserInterface/CSSMedia.js b/Source/WebInspectorUI/UserInterface/CSSMedia.js deleted file mode 100644 index 6e4a4eb89..000000000 --- a/Source/WebInspectorUI/UserInterface/CSSMedia.js +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.CSSMedia = function(type, text, sourceCodeLocation) -{ - WebInspector.Object.call(this); - - this._type = type || null; - this._text = text || ""; - this._sourceCodeLocation = sourceCodeLocation || null; -}; - -WebInspector.Object.addConstructorFunctions(WebInspector.CSSMedia); - -WebInspector.CSSMedia.Type = { - MediaRule: "css-media-type-media-rule", - ImportRule: "css-media-type-import-rule", - LinkedStyleSheet: "css-media-type-linked-stylesheet", - InlineStyleSheet: "css-media-type-inline-stylesheet" -}; - -WebInspector.CSSMedia.prototype = { - constructor: WebInspector.CSSMedia, - - // Public - - get type() - { - return this._type; - }, - - get text() - { - return this._text; - }, - - get sourceCodeLocation() - { - return this._sourceCodeLocation; - } -}; - -WebInspector.CSSMedia.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/CSSObserver.js b/Source/WebInspectorUI/UserInterface/CSSObserver.js deleted file mode 100644 index a4b7360cd..000000000 --- a/Source/WebInspectorUI/UserInterface/CSSObserver.js +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.CSSObserver = function() -{ - WebInspector.Object.call(this); -}; - -WebInspector.CSSObserver.prototype = { - constructor: WebInspector.CSSObserver, - - // Events defined by the "CSS" domain. - - mediaQueryResultChanged: function() - { - WebInspector.cssStyleManager.mediaQueryResultChanged(); - }, - - styleSheetChanged: function(styleSheetId) - { - WebInspector.cssStyleManager.styleSheetChanged(styleSheetId); - }, - - styleSheetAdded: function(header) - { - // FIXME: Not implemented. - }, - - styleSheetRemoved: function(header) - { - // FIXME: Not implemented. - }, - - namedFlowCreated: function(namedFlow) - { - WebInspector.domTreeManager.namedFlowCreated(namedFlow); - }, - - namedFlowRemoved: function(documentNodeId, flowName) - { - WebInspector.domTreeManager.namedFlowRemoved(documentNodeId, flowName); - }, - - regionLayoutUpdated: function(namedFlow) - { - WebInspector.domTreeManager.regionLayoutUpdated(namedFlow); - }, - - regionOversetChanged: function(namedFlow) - { - WebInspector.domTreeManager.regionOversetChanged(namedFlow); - }, - - registeredNamedFlowContentElement: function(documentNodeId, flowName, contentNodeId, nextContentElementNodeId) - { - WebInspector.domTreeManager.registeredNamedFlowContentElement(documentNodeId, flowName, contentNodeId, nextContentElementNodeId); - }, - - unregisteredNamedFlowContentElement: function(documentNodeId, flowName, contentNodeId) - { - WebInspector.domTreeManager.unregisteredNamedFlowContentElement(documentNodeId, flowName, contentNodeId); - } -}; - -WebInspector.CSSObserver.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/CSSProperty.js b/Source/WebInspectorUI/UserInterface/CSSProperty.js deleted file mode 100644 index fefb4ee8f..000000000 --- a/Source/WebInspectorUI/UserInterface/CSSProperty.js +++ /dev/null @@ -1,454 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.CSSProperty = function(index, text, name, value, priority, enabled, overridden, implicit, anonymous, valid, styleSheetTextRange, styleDeclarationTextRange) -{ - WebInspector.Object.call(this); - - this._ownerStyle = null; - this._index = index; - - this.update(text, name, value, priority, enabled, overridden, implicit, anonymous, valid, styleSheetTextRange, styleDeclarationTextRange, true); -}; - -WebInspector.Object.addConstructorFunctions(WebInspector.CSSProperty); - -WebInspector.CSSProperty.Event = { - Changed: "css-property-changed", - OverriddenStatusChanged: "css-property-overridden-status-changed" -}; - -WebInspector.CSSProperty.prototype = { - constructor: WebInspector.CSSProperty, - - // Public - - get ownerStyle() - { - return this._ownerStyle; - }, - - set ownerStyle(ownerStyle) - { - this._ownerStyle = ownerStyle || null; - }, - - get index() - { - return this._index; - }, - - set index(index) - { - this._index = index; - }, - - update: function(text, name, value, priority, enabled, overridden, implicit, anonymous, valid, styleSheetTextRange, styleDeclarationTextRange, dontFireEvents) - { - text = text || ""; - name = name || ""; - value = value || ""; - priority = priority || ""; - enabled = enabled || false; - overridden = overridden || false; - implicit = implicit || false; - anonymous = anonymous || false; - valid = valid || false; - - var changed = false; - - if (!dontFireEvents) { - changed = this._name !== name || this._value !== value || this._priority !== priority || - this._enabled !== enabled || this._implicit !== implicit || this._anonymous !== anonymous || this._valid !== valid; - } - - // Use the setter for overridden if we want to fire events since the - // OverriddenStatusChanged event coalesces changes before it fires. - if (!dontFireEvents) - this.overridden = overridden; - else - this._overridden = overridden; - - this._text = text; - this._name = name; - this._value = value; - this._priority = priority; - this._enabled = enabled; - this._implicit = implicit; - this._anonymous = anonymous; - this._inherited = name in WebInspector.CSSKeywordCompletions.InheritedProperties; - this._valid = valid; - this._styleSheetTextRange = styleSheetTextRange || null; - - if (styleDeclarationTextRange) - this._styleDeclarationTextRange = styleDeclarationTextRange; - else - delete this._styleDeclarationTextRange; - - this._relatedShorthandProperty = null; - this._relatedLonghandProperties = []; - - delete this._canonicalName; - delete this._hasOtherVendorNameOrKeyword; - - if (!this._updatePropertySoonTimeout) { - delete this._pendingName; - delete this._pendingValue; - delete this._pendingPriority; - } - - if (changed) - this.dispatchEventToListeners(WebInspector.CSSProperty.Event.Changed); - }, - - get synthesizedText() - { - var name = this.name; - if (!name) - return ""; - - var priority = this.priority; - return name + ": " + this.value.trim() + (priority ? " !" + priority : "") + ";"; - }, - - get text() - { - return this._text || this.synthesizedText; - }, - - set text(text) - { - if (!this._ownerStyle || !this._ownerStyle.editable) - return; - - if (this._text === text) - return; - - if (isNaN(this._index)) { - this._text = text || ""; - - // Clear the name, value and priority since they might not match the text now. - this._name = ""; - this._value = ""; - this._priority = ""; - - // Ditto for the canonical and pending properties. - delete this._canonicalName; - delete this._pendingName; - delete this._pendingValue; - delete this._pendingPriority; - - return; - } - - this._cancelPendingUpdate(); - this._ownerStyle.nodeStyles.changePropertyText(this, text); - }, - - get name() - { - if (isNaN(this._index)) - return this._pendingName || this._name; - return this._name; - }, - - set name(name) - { - if (!this._ownerStyle || !this._ownerStyle.editable) - return; - - if (this._name === name) - return; - - if (isNaN(this._index)) { - this._name = name; - this._text = ""; - - delete this._canonicalName; - } else { - this._pendingName = name; - this._updatePropertySoon(); - } - }, - - get canonicalName() - { - if (this._canonicalName) - return this._canonicalName; - - this._canonicalName = WebInspector.cssStyleManager.canonicalNameForPropertyName(this.name); - - return this._canonicalName; - }, - - get value() - { - if (isNaN(this._index)) - return this._pendingValue || this._value; - return this._value; - }, - - set value(value) - { - if (!this._ownerStyle || !this._ownerStyle.editable) - return; - - if (this._value === value) - return; - - if (isNaN(this._index)) { - this._value = value; - this._text = ""; - } else { - this._pendingValue = value; - this._updatePropertySoon(); - } - }, - - get important() - { - return this.priority === "important"; - }, - - set important(important) - { - this.priority = important ? "important" : ""; - }, - - get priority() - { - if (isNaN(this._index)) - return this._pendingPriority || this._priority; - return this._priority; - }, - - set priority(priority) - { - if (!this._ownerStyle || !this._ownerStyle.editable) - return; - - if (this._priority === priority) - return; - - if (isNaN(this._index)) { - this._priority = priority; - this._text = ""; - } else { - this._pendingPriority = priority; - this._updatePropertySoon(); - } - }, - - get enabled() - { - return this._enabled && this._ownerStyle && (!isNaN(this._index) || this._ownerStyle.type === WebInspector.CSSStyleDeclaration.Type.Computed); - }, - - set enabled(enabled) - { - if (!this._ownerStyle || !this._ownerStyle.editable) - return; - - this._ownerStyle.nodeStyles.changePropertyEnabledState(this, enabled); - }, - - get overridden() - { - return this._overridden; - }, - - set overridden(overridden) - { - overridden = overridden || false; - - if (this._overridden === overridden) - return; - - var previousOverridden = this._overridden; - - this._overridden = overridden; - - if (this._overriddenStatusChangedTimeout) - return; - - function delayed() - { - delete this._overriddenStatusChangedTimeout; - - if (this._overridden === previousOverridden) - return; - - this.dispatchEventToListeners(WebInspector.CSSProperty.Event.OverriddenStatusChanged); - } - - this._overriddenStatusChangedTimeout = setTimeout(delayed.bind(this), 0); - }, - - get implicit() - { - return this._implicit; - }, - - get anonymous() - { - return this._anonymous; - }, - - get inherited() - { - return this._inherited; - }, - - get valid() - { - return this._valid; - }, - - get styleSheetTextRange() - { - return this._styleSheetTextRange; - }, - - get styleDeclarationTextRange() - { - if ("_styleDeclarationTextRange" in this) - return this._styleDeclarationTextRange; - - if (!this._ownerStyle || !this._styleSheetTextRange) - return null; - - var styleTextRange = this._ownerStyle.styleSheetTextRange; - if (!styleTextRange) - return null; - - var startLine = this._styleSheetTextRange.startLine - styleTextRange.startLine; - var endLine = this._styleSheetTextRange.endLine - styleTextRange.startLine; - - var startColumn = this._styleSheetTextRange.startColumn; - if (!startLine) - startColumn -= styleTextRange.startColumn; - - var endColumn = this._styleSheetTextRange.endColumn; - if (!endLine) - endColumn -= styleTextRange.startColumn; - - this._styleDeclarationTextRange = new WebInspector.TextRange(startLine, startColumn, endLine, endColumn); - - return this._styleDeclarationTextRange; - }, - - get relatedShorthandProperty() - { - return this._relatedShorthandProperty; - }, - - set relatedShorthandProperty(property) - { - this._relatedShorthandProperty = property || null; - }, - - get relatedLonghandProperties() - { - return this._relatedLonghandProperties; - }, - - addRelatedLonghandProperty: function(property) - { - this._relatedLonghandProperties.push(property); - }, - - clearRelatedLonghandProperties: function(property) - { - this._relatedLonghandProperties = []; - }, - - hasOtherVendorNameOrKeyword: function() - { - if ("_hasOtherVendorNameOrKeyword" in this) - return this._hasOtherVendorNameOrKeyword; - - this._hasOtherVendorNameOrKeyword = WebInspector.cssStyleManager.propertyNameHasOtherVendorPrefix(this.name) || WebInspector.cssStyleManager.propertyValueHasOtherVendorKeyword(this.value); - - return this._hasOtherVendorNameOrKeyword; - }, - - add: function() - { - // We can only add if the index is NaN. Return early otherwise. - if (!this._ownerStyle || !this._ownerStyle.editable || !isNaN(this._index)) - return; - - this._cancelPendingUpdate(); - this._ownerStyle.addProperty(this); - }, - - remove: function() - { - // We can only remove if the index is not NaN. Return early otherwise. - if (!this._ownerStyle || !this._ownerStyle.editable || isNaN(this._index)) - return; - - this._cancelPendingUpdate(); - this._ownerStyle.removeProperty(this); - }, - - // Private - - _updatePropertySoon: function() - { - if (!this._ownerStyle || isNaN(this._index) || this._updatePropertySoonTimeout) - return; - - function performUpdate() - { - delete this._updatePropertySoonTimeout; - - if (!this._ownerStyle || isNaN(this._index)) - return; - - var name = "_pendingName" in this ? this._pendingName : this._name; - var value = "_pendingValue" in this ? this._pendingValue : this._value; - var priority = "_pendingPriority" in this ? this._pendingPriority : this._priority; - - delete this._pendingName; - delete this._pendingValue; - delete this._pendingPriority; - - this._ownerStyle.nodeStyles.changeProperty(this, name, value, priority); - } - - this._updatePropertySoonTimeout = setTimeout(performUpdate.bind(this), 0); - }, - - _cancelPendingUpdate: function() - { - if (!this._updatePropertySoonTimeout) - return; - clearTimeout(this._updatePropertySoonTimeout); - delete this._updatePropertySoonTimeout; - } -}; - -WebInspector.CSSProperty.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/CSSRule.js b/Source/WebInspectorUI/UserInterface/CSSRule.js deleted file mode 100644 index 8866cb012..000000000 --- a/Source/WebInspectorUI/UserInterface/CSSRule.js +++ /dev/null @@ -1,204 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.CSSRule = function(nodeStyles, ownerStyleSheet, id, type, sourceCodeLocation, selectorText, selectors, matchedSelectorIndices, style, mediaList) -{ - WebInspector.Object.call(this); - - console.assert(nodeStyles); - this._nodeStyles = nodeStyles; - - this._ownerStyleSheet = ownerStyleSheet || null; - this._id = id || null; - this._type = type || null; - - this.update(sourceCodeLocation, selectorText, selectors, matchedSelectorIndices, style, mediaList, true); -}; - -WebInspector.Object.addConstructorFunctions(WebInspector.CSSRule); - -WebInspector.CSSRule.Event = { - Changed: "css-rule-changed" -}; - -WebInspector.CSSRule.Type = { - Author: "css-rule-type-author", - User: "css-rule-type-user", - UserAgent: "css-rule-type-user-agent", - Inspector: "css-rule-type-inspector" -}; - -WebInspector.CSSRule.prototype = { - constructor: WebInspector.CSSRule, - - // Public - - get id() - { - return this._id; - }, - - get ownerStyleSheet() - { - return this._ownerStyleSheet; - }, - - get editable() - { - return !!this._id && (this._type === WebInspector.CSSRule.Type.Author || this._type === WebInspector.CSSRule.Type.Inspector); - }, - - update: function(sourceCodeLocation, selectorText, selectors, matchedSelectorIndices, style, mediaList, dontFireEvents) - { - sourceCodeLocation = sourceCodeLocation || null; - selectorText = selectorText || ""; - selectors = selectors || []; - matchedSelectorIndices = matchedSelectorIndices || []; - style = style || null; - mediaList = mediaList || []; - - var changed = false; - if (!dontFireEvents) { - changed = this._selectorText !== selectorText || !Object.shallowEqual(this._selectors, selectors) || - !Object.shallowEqual(this._matchedSelectorIndices, matchedSelectorIndices) || this._style !== style || - !!this._sourceCodeLocation !== !!sourceCodeLocation || this._mediaList.length !== mediaList.length; - // FIXME: Look for differences in the media list arrays. - } - - if (this._style) - this._style.ownerRule = null; - - this._sourceCodeLocation = sourceCodeLocation; - this._selectorText = selectorText; - this._selectors = selectors; - this._matchedSelectorIndices = matchedSelectorIndices; - this._style = style; - this._mediaList = mediaList; - - delete this._matchedSelectors; - delete this._matchedSelectorText; - - if (this._style) - this._style.ownerRule = this; - - if (changed) - this.dispatchEventToListeners(WebInspector.CSSRule.Event.Changed); - }, - - get type() - { - return this._type; - }, - - get sourceCodeLocation() - { - return this._sourceCodeLocation; - }, - - get selectorText() - { - return this._selectorText; - }, - - set selectorText(selectorText) - { - console.assert(this.editable); - if (!this.editable) - return; - - if (this._selectorText === selectorText) - return; - - this._nodeStyles.changeRuleSelector(this, selectorText); - }, - - get selectors() - { - return this._selectors; - }, - - set selectors(selectors) - { - this.selectorText = (selectors || []).join(", "); - }, - - get matchedSelectorIndices() - { - return this._matchedSelectorIndices; - }, - - get matchedSelectors() - { - // COMPATIBILITY (iOS 6): The selectors array is always empty, so just return an empty array. - if (!this._selectors.length) { - console.assert(!this._matchedSelectorIndices.length); - return []; - } - - if (this._matchedSelectors) - return this._matchedSelectors; - - this._matchedSelectors = this._selectors.filter(function(element, index) { - return this._matchedSelectorIndices.contains(index); - }, this); - - return this._matchedSelectors; - }, - - get matchedSelectorText() - { - // COMPATIBILITY (iOS 6): The selectors array is always empty, so just return the whole selector. - if (!this._selectors.length) { - console.assert(!this._matchedSelectorIndices.length); - return this._selectorText; - } - - if ("_matchedSelectorText" in this) - return this._matchedSelectorText; - - this._matchedSelectorText = this.matchedSelectors.join(", "); - - return this._matchedSelectorText; - }, - - get style() - { - return this._style; - }, - - get mediaList() - { - return this._mediaList; - }, - - // Protected - - get nodeStyles() - { - return this._nodeStyles; - } -}; - -WebInspector.CSSRule.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/CSSStyleDeclaration.js b/Source/WebInspectorUI/UserInterface/CSSStyleDeclaration.js deleted file mode 100644 index eaab18787..000000000 --- a/Source/WebInspectorUI/UserInterface/CSSStyleDeclaration.js +++ /dev/null @@ -1,310 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.CSSStyleDeclaration = function(nodeStyles, ownerStyleSheet, id, type, node, inherited, text, properties, styleSheetTextRange) -{ - WebInspector.Object.call(this); - - console.assert(nodeStyles); - this._nodeStyles = nodeStyles; - - this._ownerRule = null; - - this._ownerStyleSheet = ownerStyleSheet || null; - this._id = id || null; - this._type = type || null; - this._node = node || null; - this._inherited = inherited || false; - - this._pendingProperties = []; - this._propertyNameMap = {}; - - this.update(text, properties, styleSheetTextRange, true); -}; - -WebInspector.Object.addConstructorFunctions(WebInspector.CSSStyleDeclaration); - -WebInspector.CSSStyleDeclaration.Event = { - PropertiesChanged: "css-style-declaration-properties-changed" -}; - -WebInspector.CSSStyleDeclaration.Type = { - Rule: "css-style-declaration-type-rule", - Inline: "css-style-declaration-type-inline", - Attribute: "css-style-declaration-type-attribute", - Computed: "css-style-declaration-type-computed" -}; - -WebInspector.CSSStyleDeclaration.prototype = { - constructor: WebInspector.CSSStyleDeclaration, - - // Public - - get id() - { - return this._id; - }, - - get ownerStyleSheet() - { - return this._ownerStyleSheet; - }, - - get type() - { - return this._type; - }, - - get inherited() - { - return this._inherited; - }, - - get node() - { - return this._node; - }, - - get editable() - { - return !!this._id && ((this._type === WebInspector.CSSStyleDeclaration.Type.Rule && this._ownerRule && this._ownerRule.editable) || this._type === WebInspector.CSSStyleDeclaration.Type.Inline); - }, - - update: function(text, properties, styleSheetTextRange, dontFireEvents) - { - text = text || ""; - properties = properties || []; - - var oldProperties = this._properties || []; - var oldText = this._text; - - this._text = text; - this._properties = properties; - this._styleSheetTextRange = styleSheetTextRange; - this._propertyNameMap = {}; - - delete this._visibleProperties; - - var editable = this.editable; - - for (var i = 0; i < this._properties.length; ++i) { - var property = this._properties[i]; - property.ownerStyle = this; - - // Store the property in a map if we arn't editable. This - // allows for quick lookup for computed style. Editable - // styles don't use the map since they need to account for - // overridden properties. - if (!editable) - this._propertyNameMap[property.name] = property; - else { - // Remove from pendingProperties (if it was pending). - this._pendingProperties.remove(property); - } - } - - var removedProperties = []; - for (var i = 0; i < oldProperties.length; ++i) { - var oldProperty = oldProperties[i]; - - if (!this._properties.contains(oldProperty)) { - // Clear the index, since it is no longer valid. - oldProperty.index = NaN; - - removedProperties.push(oldProperty); - - // Keep around old properties in pending in case they - // are needed again during editing. - if (editable) - this._pendingProperties.push(oldProperty); - } - } - - if (dontFireEvents) - return; - - var addedProperties = []; - for (var i = 0; i < this._properties.length; ++i) { - if (!oldProperties.contains(this._properties[i])) - addedProperties.push(this._properties[i]); - } - - // Don't fire the event if there is text and it hasn't changed. - if (oldText && this._text && oldText === this._text) { - // We shouldn't have any added or removed properties in this case. - console.assert(!addedProperties.length && !removedProperties.length); - if (!addedProperties.length && !removedProperties.length) - return; - } - - function delayed() - { - this.dispatchEventToListeners(WebInspector.CSSStyleDeclaration.Event.PropertiesChanged, {addedProperties: addedProperties, removedProperties: removedProperties}); - } - - // Delay firing the PropertiesChanged event so DOMNodeStyles has a chance to mark overridden and associated properties. - setTimeout(delayed.bind(this), 0); - }, - - get ownerRule() - { - return this._ownerRule; - }, - - set ownerRule(rule) - { - this._ownerRule = rule || null; - }, - - get text() - { - return this._text; - }, - - set text(text) - { - if (this._text === text) - return; - - this._nodeStyles.changeStyleText(this, text); - }, - - get properties() - { - return this._properties; - }, - - get visibleProperties() - { - if (this._visibleProperties) - return this._visibleProperties; - - this._visibleProperties = this._properties.filter(function(property) { - return !!property.styleDeclarationTextRange; - }); - - return this._visibleProperties; - }, - - get pendingProperties() - { - return this._pendingProperties; - }, - - get styleSheetTextRange() - { - return this._styleSheetTextRange; - }, - - propertyForName: function(name, dontCreateIfMissing) - { - console.assert(name); - if (!name) - return null; - - if (!this.editable) - return this._propertyNameMap[name] || null; - - // Editable styles don't use the map since they need to - // account for overridden properties. - - function findMatch(properties) - { - for (var i = 0; i < properties.length; ++i) { - var property = properties[i]; - if (property.canonicalName !== name && property.name !== name) - continue; - if (bestMatchProperty && !bestMatchProperty.overridden && property.overridden) - continue; - bestMatchProperty = property; - } - } - - var bestMatchProperty = null; - - findMatch(this._properties); - - if (bestMatchProperty) - return bestMatchProperty; - - if (dontCreateIfMissing || !this.editable) - return null; - - findMatch(this._pendingProperties, true); - - if (bestMatchProperty) - return bestMatchProperty; - - var newProperty = new WebInspector.CSSProperty(NaN, null, name); - newProperty.ownerStyle = this; - - this._pendingProperties.push(newProperty); - - return newProperty; - }, - - addProperty: function(property) - { - console.assert(property); - if (!property) - return; - - console.assert(property.ownerStyle === this); - if (property.ownerStyle !== this) - return; - - console.assert(this.editable); - if (!this.editable) - return; - - this._nodeStyles.addProperty(property); - }, - - removeProperty: function(property) - { - console.assert(property); - if (!property) - return; - - console.assert(property.ownerStyle === this); - if (property.ownerStyle !== this) - return; - - console.assert(this.editable); - if (!this.editable) - return; - - this._nodeStyles.removeProperty(property); - }, - - // Protected - - get nodeStyles() - { - return this._nodeStyles; - } -}; - -WebInspector.CSSStyleDeclaration.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/CSSStyleDeclarationSection.css b/Source/WebInspectorUI/UserInterface/CSSStyleDeclarationSection.css deleted file mode 100644 index 434b1c2a7..000000000 --- a/Source/WebInspectorUI/UserInterface/CSSStyleDeclarationSection.css +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.style-declaration-section { - display: -webkit-flex; - -webkit-flex-direction: column; - - padding: 5px; - - background-color: white; -} - -.style-declaration-section + .style-declaration-section { - border-top: 1px solid rgb(210, 210, 210); -} - -.style-declaration-section.last-in-group { - margin-bottom: 15px; - - box-shadow: rgba(0, 0, 0, 0.3) 0 2px 2px 0; -} - -.style-declaration-section.last-in-group + .style-declaration-section { - margin-top: 15px; - - border-top: none; - - box-shadow: rgba(0, 0, 0, 0.3) 0 0 2px 0; -} - -.style-declaration-section:first-child, -div:not(.style-declaration-section) + .style-declaration-section, -.style-declaration-section.last-in-group + .style-declaration-section.last-in-group, -.style-declaration-section.last-in-group + .style-declaration-section:last-child { - box-shadow: rgba(0, 0, 0, 0.3) 0 1px 3px 1px; -} - -.style-declaration-section:last-child { - margin-bottom: 0 !important; -} - -.style-declaration-section > .header { - position: relative; - - padding: 4px 5px 3px 25px; - - font-size: 11px; - line-height: 12px; -} - -.style-declaration-section > .header > .icon { - position: absolute; - - top: 2px; - left: 4px; - - width: 16px; - height: 16px; -} - -.style-declaration-section > .header > .selector { - font-family: Menlo, monospace; - color: rgb(128, 128, 128); - - outline: none; - - cursor: text; - - word-wrap: break-word; - - -webkit-user-select: text; - -webkit-user-modify: read-write-plaintext-only; -} - -.style-declaration-section > .header > .selector:empty { - /* This prevents the cursor from disappearing when empty. */ - display: inline-block; - min-width: 1px; -} - -.style-declaration-section > .header > .selector:empty::before { - /* This prevents the cursor from positioning badly when empty. */ - content: ""; -} - -.style-declaration-section > .header > .selector:focus { - color: black; -} - -.style-declaration-section.locked > .header > .selector, -.style-declaration-section.selector-locked > .header > .selector { - -webkit-user-modify: read-only; -} - -.style-declaration-section.locked > .header::before { - float: right; - - content: ""; - - width: 8px; - height: 10px; - - background-image: -webkit-canvas(style-lock-normal); - background-repeat: no-repeat; - background-position: center; - background-size: 8px 10px; - - margin-left: 5px; -} - -.style-declaration-section > .header > .selector > .matched { - color: black; -} - -.style-declaration-section > .header > .origin { - line-height: 10px; - font-family: "Lucida Grande", sans-serif; - - color: rgb(128, 128, 128); - - word-wrap: break-word; - white-space: nowrap; -} - -.style-declaration-section > .header > .origin a { - white-space: normal; -} - -.style-declaration-section > .header > .origin > .go-to-link { - color: inherit !important; -} diff --git a/Source/WebInspectorUI/UserInterface/CSSStyleDeclarationSection.js b/Source/WebInspectorUI/UserInterface/CSSStyleDeclarationSection.js deleted file mode 100644 index af0d9c505..000000000 --- a/Source/WebInspectorUI/UserInterface/CSSStyleDeclarationSection.js +++ /dev/null @@ -1,261 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.CSSStyleDeclarationSection = function(style) -{ - WebInspector.Object.call(this); - - console.assert(style); - this._style = style || null; - - this._element = document.createElement("div"); - this._element.className = WebInspector.CSSStyleDeclarationSection.StyleClassName; - - this._headerElement = document.createElement("div"); - this._headerElement.className = WebInspector.CSSStyleDeclarationSection.HeaderElementStyleClassName; - - this._iconElement = document.createElement("img"); - this._iconElement.className = WebInspector.CSSStyleDeclarationSection.IconElementStyleClassName; - this._headerElement.appendChild(this._iconElement); - - this._selectorElement = document.createElement("span"); - this._selectorElement.className = WebInspector.CSSStyleDeclarationSection.SelectorElementStyleClassName; - this._selectorElement.setAttribute("spellcheck", "false"); - this._headerElement.appendChild(this._selectorElement); - - this._originElement = document.createElement("span"); - this._originElement.className = WebInspector.CSSStyleDeclarationSection.OriginElementStyleClassName; - this._headerElement.appendChild(this._originElement); - - this._propertiesElement = document.createElement("div"); - this._propertiesElement.className = WebInspector.CSSStyleDeclarationSection.PropertiesElementStyleClassName; - - this._propertiesTextEditor = new WebInspector.CSSStyleDeclarationTextEditor(this, style); - this._propertiesElement.appendChild(this._propertiesTextEditor.element); - - this._element.appendChild(this._headerElement); - this._element.appendChild(this._propertiesElement); - - var iconClassName; - switch (style.type) { - case WebInspector.CSSStyleDeclaration.Type.Rule: - console.assert(style.ownerRule); - - if (style.inherited) - iconClassName = WebInspector.CSSStyleDeclarationSection.InheritedStyleRuleIconStyleClassName; - else if (style.ownerRule.type === WebInspector.CSSRule.Type.Author) - iconClassName = WebInspector.CSSStyleDeclarationSection.AuthorStyleRuleIconStyleClassName; - else if (style.ownerRule.type === WebInspector.CSSRule.Type.User) - iconClassName = WebInspector.CSSStyleDeclarationSection.UserStyleRuleIconStyleClassName; - else if (style.ownerRule.type === WebInspector.CSSRule.Type.UserAgent) - iconClassName = WebInspector.CSSStyleDeclarationSection.UserAgentStyleRuleIconStyleClassName; - else if (style.ownerRule.type === WebInspector.CSSRule.Type.Inspector) - iconClassName = WebInspector.CSSStyleDeclarationSection.InspectorStyleRuleIconStyleClassName; - break; - - case WebInspector.CSSStyleDeclaration.Type.Inline: - case WebInspector.CSSStyleDeclaration.Type.Attribute: - if (style.inherited) - iconClassName = WebInspector.CSSStyleDeclarationSection.InheritedElementStyleRuleIconStyleClassName; - else - iconClassName = WebInspector.DOMTreeElementPathComponent.DOMElementIconStyleClassName; - break; - } - - console.assert(iconClassName); - this._element.classList.add(iconClassName); - - if (!style.editable) - this._element.classList.add(WebInspector.CSSStyleDeclarationSection.LockedStyleClassName); - else if (style.ownerRule) { - this._commitSelectorKeyboardShortcut = new WebInspector.KeyboardShortcut(null, WebInspector.KeyboardShortcut.Key.Enter, this._commitSelector.bind(this), this._selectorElement); - this._selectorElement.addEventListener("blur", this._commitSelector.bind(this)); - } else - this._element.classList.add(WebInspector.CSSStyleDeclarationSection.SelectorLockedStyleClassName); - - if (!WebInspector.CSSStyleDeclarationSection._generatedLockImages) { - WebInspector.CSSStyleDeclarationSection._generatedLockImages = true; - - var specifications = {"style-lock-normal": {fillColor: [0, 0, 0, 0.5]}}; - generateColoredImagesForCSS("Images/Locked.svg", specifications, 8, 10); - } - - this.refresh(); -}; - -WebInspector.CSSStyleDeclarationSection.StyleClassName = "style-declaration-section"; -WebInspector.CSSStyleDeclarationSection.LockedStyleClassName = "locked"; -WebInspector.CSSStyleDeclarationSection.SelectorLockedStyleClassName = "selector-locked"; -WebInspector.CSSStyleDeclarationSection.LastInGroupStyleClassName = "last-in-group"; -WebInspector.CSSStyleDeclarationSection.HeaderElementStyleClassName = "header"; -WebInspector.CSSStyleDeclarationSection.IconElementStyleClassName = "icon"; -WebInspector.CSSStyleDeclarationSection.SelectorElementStyleClassName = "selector"; -WebInspector.CSSStyleDeclarationSection.OriginElementStyleClassName = "origin"; -WebInspector.CSSStyleDeclarationSection.PropertiesElementStyleClassName = "properties"; -WebInspector.CSSStyleDeclarationSection.MatchedSelectorElementStyleClassName = "matched"; - -WebInspector.CSSStyleDeclarationSection.AuthorStyleRuleIconStyleClassName = "author-style-rule-icon"; -WebInspector.CSSStyleDeclarationSection.UserStyleRuleIconStyleClassName = "user-style-rule-icon"; -WebInspector.CSSStyleDeclarationSection.UserAgentStyleRuleIconStyleClassName = "user-agent-style-rule-icon"; -WebInspector.CSSStyleDeclarationSection.InspectorStyleRuleIconStyleClassName = "inspector-style-rule-icon"; -WebInspector.CSSStyleDeclarationSection.InheritedStyleRuleIconStyleClassName = "inherited-style-rule-icon"; -WebInspector.CSSStyleDeclarationSection.InheritedElementStyleRuleIconStyleClassName = "inherited-element-style-rule-icon"; - -WebInspector.CSSStyleDeclarationSection.prototype = { - constructor: WebInspector.CSSStyleDeclarationSection, - - // Public - - get element() - { - return this._element; - }, - - get style() - { - return this._style; - }, - - get lastInGroup() - { - return this._element.classList.contains(WebInspector.CSSStyleDeclarationSection.LastInGroupStyleClassName); - }, - - set lastInGroup(last) - { - if (last) - this._element.classList.add(WebInspector.CSSStyleDeclarationSection.LastInGroupStyleClassName); - else - this._element.classList.remove(WebInspector.CSSStyleDeclarationSection.LastInGroupStyleClassName); - }, - - get focused() - { - return this._propertiesTextEditor.focused; - }, - - focus: function() - { - this._propertiesTextEditor.focus(); - }, - - refresh: function() - { - this._selectorElement.removeChildren(); - this._originElement.removeChildren(); - - this._originElement.appendChild(document.createTextNode(" \u2014 ")); - - function appendSelector(selectorText, matched) - { - var selectorElement = document.createElement("span"); - if (matched) - selectorElement.className = WebInspector.CSSStyleDeclarationSection.MatchedSelectorElementStyleClassName; - selectorElement.textContent = selectorText; - this._selectorElement.appendChild(selectorElement); - } - - switch (this._style.type) { - case WebInspector.CSSStyleDeclaration.Type.Rule: - console.assert(this._style.ownerRule); - - var selectors = this._style.ownerRule.selectors; - var matchedSelectorIndices = this._style.ownerRule.matchedSelectorIndices; - if (selectors.length && matchedSelectorIndices.length) { - for (var i = 0; i < selectors.length; ++i) { - appendSelector.call(this, selectors[i], matchedSelectorIndices.contains(i)); - if (i < selectors.length - 1) - this._selectorElement.appendChild(document.createTextNode(", ")); - } - } else - appendSelector.call(this, this._style.ownerRule.selectorText, true); - - if (this._style.ownerRule.sourceCodeLocation) { - var sourceCodeLink = WebInspector.createSourceCodeLocationLink(this._style.ownerRule.sourceCodeLocation, true); - this._originElement.appendChild(sourceCodeLink); - } else { - var originString; - switch (this._style.ownerRule.type) { - case WebInspector.CSSRule.Type.Author: - originString = WebInspector.UIString("Author Stylesheet"); - break; - - case WebInspector.CSSRule.Type.User: - originString = WebInspector.UIString("User Stylesheet"); - break; - - case WebInspector.CSSRule.Type.UserAgent: - originString = WebInspector.UIString("User Agent Stylesheet"); - break; - - case WebInspector.CSSRule.Type.Inspector: - originString = WebInspector.UIString("Web Inspector"); - break; - } - - console.assert(originString); - if (originString) - this._originElement.appendChild(document.createTextNode(originString)); - } - - break; - - case WebInspector.CSSStyleDeclaration.Type.Inline: - appendSelector.call(this, WebInspector.displayNameForNode(this._style.node), true); - this._originElement.appendChild(document.createTextNode(WebInspector.UIString("Style Attribute"))); - break; - - case WebInspector.CSSStyleDeclaration.Type.Attribute: - appendSelector.call(this, WebInspector.displayNameForNode(this._style.node), true); - this._originElement.appendChild(document.createTextNode(WebInspector.UIString("HTML Attributes"))); - break; - } - }, - - updateLayout: function() - { - this._propertiesTextEditor.updateLayout(); - }, - - // Private - - _commitSelector: function(mutations) - { - console.assert(this._style.ownerRule); - if (!this._style.ownerRule) - return; - - var newSelectorText = this._selectorElement.textContent.trim(); - if (!newSelectorText) { - // Revert to the current selector (by doing a refresh) since the new selector is empty. - this.refresh(); - return; - } - - this._style.ownerRule.selectorText = newSelectorText; - } -}; - -WebInspector.CSSStyleDeclarationSection.prototype.__proto__ = WebInspector.StyleDetailsPanel.prototype; diff --git a/Source/WebInspectorUI/UserInterface/CSSStyleDeclarationTextEditor.css b/Source/WebInspectorUI/UserInterface/CSSStyleDeclarationTextEditor.css deleted file mode 100644 index f001641ff..000000000 --- a/Source/WebInspectorUI/UserInterface/CSSStyleDeclarationTextEditor.css +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.css-style-text-editor { - background-color: white; - padding: 2px 0; -} - -.css-style-text-editor > .CodeMirror { - height: auto; -} - -.css-style-text-editor > .CodeMirror-scroll { - overflow: hidden; -} - -.css-style-text-editor > .CodeMirror .CodeMirror-placeholder { - font-family: "Lucida Grande", sans-serif; - color: rgb(128, 128, 128); - padding: 0 5px 0 39px; - text-indent: -14px; -} - -.css-style-text-editor > .CodeMirror pre { - padding: 1px 5px 1px 39px; - text-indent: -35px; -} - -.css-style-text-editor > .CodeMirror pre * { - text-indent: 0; -} - -.css-style-text-editor.read-only > .CodeMirror pre { - /* Compensate for the missing checkboxes so properties line up with editable styles that have checkboxes. */ - text-indent: -14px; -} - -.css-style-text-editor.read-only > .CodeMirror .CodeMirror-cursor { - display: none; -} - -.css-style-text-editor > .CodeMirror .CodeMirror-lines pre span:not(.css-style-declaration-property):not(.CodeMirror-widget):not(.cm-comment):not(.cm-tab), -.css-style-text-editor > .CodeMirror .CodeMirror-lines .css-style-declaration-property.disabled, -.css-style-text-editor > .CodeMirror .CodeMirror-lines .css-style-declaration-property.invalid, -.css-style-text-editor > .CodeMirror .CodeMirror-lines .css-style-declaration-property.other-vendor, -.css-style-text-editor > .CodeMirror .CodeMirror-lines .css-style-declaration-property.not-inherited, -.css-style-text-editor > .CodeMirror .CodeMirror-lines .css-style-declaration-property.overridden { - text-decoration: line-through; - -webkit-text-stroke-width: 0.000000000000001px; /* A hack to get a different line-through color. */ - -webkit-text-stroke-color: rgba(0, 0, 0, 0.6); -} - -.css-style-text-editor > .CodeMirror .CodeMirror-lines pre span:not(.css-style-declaration-property):not(.CodeMirror-widget):not(.cm-comment):not(.cm-tab), -.css-style-text-editor > .CodeMirror .CodeMirror-lines .css-style-declaration-property.invalid { - -webkit-text-stroke-color: rgba(255, 0, 0, 0.6); -} - -.css-style-text-editor > .CodeMirror .CodeMirror-lines .css-style-declaration-property.implicit, -.css-style-text-editor > .CodeMirror .CodeMirror-lines .css-style-declaration-property.not-inherited { - opacity: 0.5; -} - -.css-style-text-editor > .CodeMirror .CodeMirror-lines .editing-line .css-style-declaration-property.disabled, -.css-style-text-editor > .CodeMirror .CodeMirror-lines .editing-line .css-style-declaration-property.other-vendor, -.css-style-text-editor > .CodeMirror .CodeMirror-lines .editing-line .css-style-declaration-property.not-inherited, -.css-style-text-editor > .CodeMirror .CodeMirror-lines .editing-line .css-style-declaration-property.overridden { - -webkit-text-stroke-color: rgba(0, 0, 0, 0.3); -} - -.css-style-text-editor > .CodeMirror .CodeMirror-lines .editing-line span:not(.css-style-declaration-property):not(.CodeMirror-widget):not(.cm-comment):not(.cm-tab), -.css-style-text-editor > .CodeMirror .CodeMirror-lines .editing-line .css-style-declaration-property.invalid { - text-decoration: none; -} - -.css-style-text-editor > .CodeMirror .CodeMirror-lines input[type=checkbox] { - width: 10px; - height: 10px; - vertical-align: middle; - margin: 0 8px 0 3px; - visibility: hidden; -} - -.css-style-text-editor > .CodeMirror .CodeMirror-lines .checkbox-placeholder { - display: inline-block; - width: 21px; -} - -.css-style-text-editor > .CodeMirror .CodeMirror-lines input[type=checkbox]:not(:checked), -.css-style-text-editor > .CodeMirror.CodeMirror-focused .CodeMirror-lines input[type=checkbox], -.css-style-text-editor:hover > .CodeMirror .CodeMirror-lines input[type=checkbox] { - visibility: visible; -} - -.css-style-text-editor > .CodeMirror .CodeMirror-lines .color-swatch { - display: inline-block; - - margin-right: 3px; - vertical-align: -2px; - - width: 1em; - height: 1em; - - position: relative; - - /* Make a checkered background for transparent colors to show against. */ - background-image: -webkit-linear-gradient(top, rgb(204, 204, 204), rgb(204, 204, 204)), - -webkit-linear-gradient(top, rgb(204, 204, 204), rgb(204, 204, 204)); - background-color: white; - background-size: calc(50% + 1px); - background-position: top left, bottom right; - background-repeat: no-repeat; - - cursor: default; -} - -.css-style-text-editor > .CodeMirror .CodeMirror-lines .color-swatch > span { - position: absolute; - top: 0; - left: 0; - right: 0; - bottom: 0; - - border: 1px solid rgba(64, 64, 64, 0.4); -} - -.css-style-text-editor > .CodeMirror .CodeMirror-lines .color-swatch:hover > span { - border: 1px solid rgba(64, 64, 64, 0.8); -} - -.css-style-text-editor > .CodeMirror .CodeMirror-lines .color-swatch:active > span { - border: 1px solid rgba(64, 64, 64, 1); -} - -.css-style-text-editor > .CodeMirror .cm-link { - /* Style url(...) links as if they are strings. */ - color: rgb(196, 26, 22); - text-decoration: inherit; - cursor: inherit; -} diff --git a/Source/WebInspectorUI/UserInterface/CSSStyleDeclarationTextEditor.js b/Source/WebInspectorUI/UserInterface/CSSStyleDeclarationTextEditor.js deleted file mode 100644 index fc5e3ef70..000000000 --- a/Source/WebInspectorUI/UserInterface/CSSStyleDeclarationTextEditor.js +++ /dev/null @@ -1,1006 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.CSSStyleDeclarationTextEditor = function(delegate, style, element) -{ - WebInspector.Object.call(this); - - this._element = element || document.createElement("div"); - this._element.classList.add(WebInspector.CSSStyleDeclarationTextEditor.StyleClassName); - this._element.classList.add(WebInspector.SyntaxHighlightedStyleClassName); - - this._showsImplicitProperties = true; - this._alwaysShowPropertyNames = {}; - this._sortProperties = false; - - this._prefixWhitespace = ""; - this._suffixWhitespace = ""; - this._linePrefixWhitespace = ""; - - this._delegate = delegate || null; - - this._codeMirror = CodeMirror(this.element, { - readOnly: true, - lineWrapping: true, - mode: "css-rule", - electricChars: false, - indentWithTabs: true, - indentUnit: 4, - smartIndent: false, - matchBrackets: true, - autoCloseBrackets: true - }); - - this._codeMirror.on("change", this._contentChanged.bind(this)); - this._codeMirror.on("blur", this._editorBlured.bind(this)); - - this._completionController = new WebInspector.CodeMirrorCompletionController(this._codeMirror, this); - this._tokenTrackingController = new WebInspector.CodeMirrorTokenTrackingController(this._codeMirror, this); - - this._jumpToSymbolTrackingModeEnabled = false; - this._tokenTrackingController.classNameForHighlightedRange = WebInspector.CodeMirrorTokenTrackingController.JumpToSymbolHighlightStyleClassName; - this._tokenTrackingController.mouseOverDelayDuration = 0; - this._tokenTrackingController.mouseOutReleaseDelayDuration = 0; - this._tokenTrackingController.mode = WebInspector.CodeMirrorTokenTrackingController.Mode.NonSymbolTokens; - - this.style = style; -}; - -WebInspector.Object.addConstructorFunctions(WebInspector.CSSStyleDeclarationTextEditor); - -WebInspector.CSSStyleDeclarationTextEditor.StyleClassName = "css-style-text-editor"; -WebInspector.CSSStyleDeclarationTextEditor.ReadOnlyStyleClassName = "read-only"; -WebInspector.CSSStyleDeclarationTextEditor.ColorSwatchElementStyleClassName = "color-swatch"; -WebInspector.CSSStyleDeclarationTextEditor.CheckboxPlaceholderElementStyleClassName = "checkbox-placeholder"; -WebInspector.CSSStyleDeclarationTextEditor.EditingLineStyleClassName = "editing-line"; -WebInspector.CSSStyleDeclarationTextEditor.CommitCoalesceDelay = 250; -WebInspector.CSSStyleDeclarationTextEditor.RemoveEditingLineClassesDelay = 2000; - -WebInspector.CSSStyleDeclarationTextEditor.prototype = { - constructor: WebInspector.CSSStyleDeclarationTextEditor, - - // Public - - get element() - { - return this._element; - }, - - get delegate() - { - return this._delegate; - }, - - set delegate(delegate) - { - this._delegate = delegate || null; - }, - - get style() - { - return this._style; - }, - - set style(style) - { - if (this._style === style) - return; - - if (this._style) { - this._style.removeEventListener(WebInspector.CSSStyleDeclaration.Event.PropertiesChanged, this._propertiesChanged, this); - if (this._style.ownerRule && this._style.ownerRule.sourceCodeLocation) - WebInspector.notifications.removeEventListener(WebInspector.Notification.GlobalModifierKeysDidChange, this._updateJumpToSymbolTrackingMode, this); - } - - this._style = style || null; - - if (this._style) { - this._style.addEventListener(WebInspector.CSSStyleDeclaration.Event.PropertiesChanged, this._propertiesChanged, this); - if (this._style.ownerRule && this._style.ownerRule.sourceCodeLocation) - WebInspector.notifications.addEventListener(WebInspector.Notification.GlobalModifierKeysDidChange, this._updateJumpToSymbolTrackingMode, this); - } - - this._updateJumpToSymbolTrackingMode(); - - this._resetContent(); - }, - - get focused() - { - return this._codeMirror.getWrapperElement().classList.contains("CodeMirror-focused"); - }, - - get alwaysShowPropertyNames() - { - return Object.keys(this._alwaysShowPropertyNames); - }, - - set alwaysShowPropertyNames(alwaysShowPropertyNames) - { - this._alwaysShowPropertyNames = (alwaysShowPropertyNames || []).keySet(); - - this._resetContent(); - }, - - get showsImplicitProperties() - { - return this._showsImplicitProperties; - }, - - set showsImplicitProperties(showsImplicitProperties) - { - if (this._showsImplicitProperties === showsImplicitProperties) - return; - - this._showsImplicitProperties = showsImplicitProperties; - - this._resetContent(); - }, - - get sortProperties() - { - return this._sortProperties; - }, - - set sortProperties(sortProperties) - { - if (this._sortProperties === sortProperties) - return; - - this._sortProperties = sortProperties; - - this._resetContent(); - }, - - focus: function() - { - this._codeMirror.focus(); - }, - - refresh: function() - { - this._resetContent(); - }, - - updateLayout: function(force) - { - this._codeMirror.refresh(); - }, - - // Protected - - didDismissPopover: function(popover) - { - if (popover === this._colorPickerPopover) - delete this._colorPickerPopover; - }, - - completionControllerCompletionsHidden: function(completionController) - { - var styleText = this._style.text; - var currentText = this._formattedContent(); - - // If the style text and the current editor text differ then we need to commit. - // Otherwise we can just update the properties that got skipped because a completion - // was pending the last time _propertiesChanged was called. - if (styleText !== currentText) - this._commitChanges(); - else - this._propertiesChanged(); - }, - - // Private - - _clearRemoveEditingLineClassesTimeout: function() - { - if (!this._removeEditingLineClassesTimeout) - return; - - clearTimeout(this._removeEditingLineClassesTimeout); - delete this._removeEditingLineClassesTimeout; - }, - - _removeEditingLineClasses: function() - { - this._clearRemoveEditingLineClassesTimeout(); - - function removeEditingLineClasses() - { - var lineCount = this._codeMirror.lineCount(); - for (var i = 0; i < lineCount; ++i) - this._codeMirror.removeLineClass(i, "wrap", WebInspector.CSSStyleDeclarationTextEditor.EditingLineStyleClassName); - } - - this._codeMirror.operation(removeEditingLineClasses.bind(this)); - }, - - _removeEditingLineClassesSoon: function() - { - if (this._removeEditingLineClassesTimeout) - return; - this._removeEditingLineClassesTimeout = setTimeout(this._removeEditingLineClasses.bind(this), WebInspector.CSSStyleDeclarationTextEditor.RemoveEditingLineClassesDelay); - }, - - _formattedContent: function() - { - // Start with the prefix whitespace we stripped. - var content = this._prefixWhitespace; - - // Get each line and add the line prefix whitespace and newlines. - var lineCount = this._codeMirror.lineCount(); - for (var i = 0; i < lineCount; ++i) { - var lineContent = this._codeMirror.getLine(i); - content += this._linePrefixWhitespace + lineContent; - if (i !== lineCount - 1) - content += "\n"; - } - - // Add the suffix whitespace we stripped. - content += this._suffixWhitespace; - - return content; - }, - - _commitChanges: function() - { - if (this._commitChangesTimeout) { - clearTimeout(this._commitChangesTimeout); - delete this._commitChangesTimeout; - } - - this._style.text = this._formattedContent(); - }, - - _editorBlured: function(codeMirror) - { - // Clicking a suggestion causes the editor to blur. We don't want to reset content in this case. - if (this._completionController.isHandlingClickEvent()) - return; - - // Reset the content on blur since we stop accepting external changes while the the editor is focused. - // This causes us to pick up any change that was suppressed while the editor was focused. - this._resetContent(); - }, - - _contentChanged: function(codeMirror, change) - { - // Return early if the style isn't editable. This still can be called when readOnly is set because - // clicking on a color swatch modifies the text. - if (!this._style || !this._style.editable || this._ignoreCodeMirrorContentDidChangeEvent) - return; - - this._markLinesWithCheckboxPlaceholder(); - - this._clearRemoveEditingLineClassesTimeout(); - this._codeMirror.addLineClass(change.from.line, "wrap", WebInspector.CSSStyleDeclarationTextEditor.EditingLineStyleClassName); - - // When the change is a completion change, create color swatches now since the changes - // will not go through _propertiesChanged until completionControllerCompletionsHidden happens. - // This way any auto completed colors get swatches right away. - if (this._completionController.isCompletionChange(change)) - this._createColorSwatches(false, change.from.line); - - // Use a short delay for user input to coalesce more changes before committing. Other actions like - // undo, redo and paste are atomic and work better with a zero delay. CodeMirror identifies changes that - // get coalesced in the undo stack with a "+" prefix on the origin. Use that to set the delay for our coalescing. - const delay = change.origin && change.origin.charAt(0) === "+" ? WebInspector.CSSStyleDeclarationTextEditor.CommitCoalesceDelay : 0; - - // Reset the timeout so rapid changes coalesce after a short delay. - if (this._commitChangesTimeout) - clearTimeout(this._commitChangesTimeout); - this._commitChangesTimeout = setTimeout(this._commitChanges.bind(this), delay); - }, - - _updateTextMarkers: function(nonatomic) - { - function update() - { - this._clearTextMarkers(true); - - var styleText = this._style.text; - - this._iterateOverProperties(true, function(property) { - var styleTextRange = property.styleDeclarationTextRange; - console.assert(styleTextRange); - if (!styleTextRange) - return; - - var from = {line: styleTextRange.startLine, ch: styleTextRange.startColumn}; - var to = {line: styleTextRange.endLine, ch: styleTextRange.endColumn}; - - // Adjust the line position for the missing prefix line. - if (this._prefixWhitespace) { - --from.line; - --to.line; - } - - // Adjust the column for the stripped line prefix whitespace. - from.ch -= this._linePrefixWhitespace.length; - to.ch -= this._linePrefixWhitespace.length; - - this._createTextMarkerForPropertyIfNeeded(from, to, property); - }); - - if (!this._codeMirror.getOption("readOnly")) { - // Matches a comment like: /* -webkit-foo: bar; */ - const commentedPropertyRegex = /\/\*\s*[-\w]+\s*:\s*[^;]+;?\s*\*\//g; - - // Look for comments that look like properties and add checkboxes in front of them. - var lineCount = this._codeMirror.lineCount(); - for (var i = 0; i < lineCount; ++i) { - var lineContent = this._codeMirror.getLine(i); - - var match = commentedPropertyRegex.exec(lineContent); - while (match) { - var checkboxElement = document.createElement("input"); - checkboxElement.type = "checkbox"; - checkboxElement.checked = false; - checkboxElement.addEventListener("change", this._propertyCommentCheckboxChanged.bind(this)); - - var from = {line: i, ch: match.index}; - var to = {line: i, ch: match.index + match[0].length}; - - var checkboxMarker = this._codeMirror.setUniqueBookmark(from, checkboxElement); - checkboxMarker.__propertyCheckbox = true; - - var commentTextMarker = this._codeMirror.markText(from, to); - - checkboxElement.__commentTextMarker = commentTextMarker; - - match = commentedPropertyRegex.exec(lineContent); - } - } - } - - // Look for colors and make swatches. - this._createColorSwatches(true); - - this._markLinesWithCheckboxPlaceholder(); - } - - if (nonatomic) - update.call(this); - else - this._codeMirror.operation(update.bind(this)); - }, - - _createColorSwatches: function(nonatomic, lineNumber) - { - function update() - { - // Look for color strings and add swatches in front of them. - this._codeMirror.createColorMarkers(lineNumber, function(marker, color, colorString) { - var swatchElement = document.createElement("span"); - swatchElement.title = WebInspector.UIString("Click to open a colorpicker. Shift-click to change color format."); - swatchElement.className = WebInspector.CSSStyleDeclarationTextEditor.ColorSwatchElementStyleClassName; - swatchElement.addEventListener("click", this._colorSwatchClicked.bind(this)); - - var swatchInnerElement = document.createElement("span"); - swatchInnerElement.style.backgroundColor = colorString; - swatchElement.appendChild(swatchInnerElement); - - var codeMirrorTextMarker = marker.codeMirrorTextMarker; - var swatchMarker = this._codeMirror.setUniqueBookmark(codeMirrorTextMarker.find().from, swatchElement); - - swatchInnerElement.__colorTextMarker = codeMirrorTextMarker; - swatchInnerElement.__color = color; - }.bind(this)); - } - - if (nonatomic) - update.call(this); - else - this._codeMirror.operation(update.bind(this)); - }, - - _updateTextMarkerForPropertyIfNeeded: function(property) - { - var textMarker = property.__propertyTextMarker; - console.assert(textMarker); - if (!textMarker) - return; - - var range = textMarker.find(); - console.assert(range); - if (!range) - return; - - this._createTextMarkerForPropertyIfNeeded(range.from, range.to, property); - }, - - _createTextMarkerForPropertyIfNeeded: function(from, to, property) - { - if (!this._codeMirror.getOption("readOnly")) { - // Create a new checkbox element and marker. - - console.assert(property.enabled); - - var checkboxElement = document.createElement("input"); - checkboxElement.type = "checkbox"; - checkboxElement.checked = true; - checkboxElement.addEventListener("change", this._propertyCheckboxChanged.bind(this)); - checkboxElement.__cssProperty = property; - - var checkboxMarker = this._codeMirror.setUniqueBookmark(from, checkboxElement); - checkboxMarker.__propertyCheckbox = true; - } - - var classNames = ["css-style-declaration-property"]; - - if (property.overridden) - classNames.push("overridden"); - - if (property.implicit) - classNames.push("implicit"); - - if (this._style.inherited && !property.inherited) - classNames.push("not-inherited"); - - if (!property.valid && property.hasOtherVendorNameOrKeyword()) - classNames.push("other-vendor"); - else if (!property.valid) - classNames.push("invalid"); - - if (!property.enabled) - classNames.push("disabled"); - - var classNamesString = classNames.join(" "); - - // If there is already a text marker and it's in the same document, then try to avoid recreating it. - // FIXME: If there are multiple CSSStyleDeclarationTextEditors for the same style then this will cause - // both editors to fight and always recreate their text markers. This isn't really common. - if (property.__propertyTextMarker && property.__propertyTextMarker.doc.cm === this._codeMirror && property.__propertyTextMarker.find()) { - // If the class name is the same then we don't need to make a new marker. - if (property.__propertyTextMarker.className === classNamesString) - return; - - property.__propertyTextMarker.clear(); - } - - var propertyTextMarker = this._codeMirror.markText(from, to, {className: classNamesString}); - - propertyTextMarker.__cssProperty = property; - property.__propertyTextMarker = propertyTextMarker; - - property.addEventListener(WebInspector.CSSProperty.Event.OverriddenStatusChanged, this._propertyOverriddenStatusChanged, this); - - this._removeCheckboxPlaceholder(from.line); - }, - - _clearTextMarkers: function(nonatomic, all) - { - function clear() - { - var markers = this._codeMirror.getAllMarks(); - for (var i = 0; i < markers.length; ++i) { - var textMarker = markers[i]; - - if (!all && textMarker.__checkboxPlaceholder) { - var position = textMarker.find(); - - // Only keep checkbox placeholders if they are in the first column. - if (position && !position.ch) - continue; - } - - if (textMarker.__cssProperty) { - textMarker.__cssProperty.removeEventListener(null, null, this); - - delete textMarker.__cssProperty.__propertyTextMarker; - delete textMarker.__cssProperty; - } - - textMarker.clear(); - } - } - - if (nonatomic) - clear.call(this); - else - this._codeMirror.operation(clear.bind(this)); - }, - - _iterateOverProperties: function(onlyVisibleProperties, callback) - { - var properties = onlyVisibleProperties ? this._style.visibleProperties : this._style.properties; - - if (!onlyVisibleProperties) { - // Filter based on options only when all properties are used. - properties = properties.filter((function(property) { - return !property.implicit || this._showsImplicitProperties || property.canonicalName in this._alwaysShowPropertyNames; - }).bind(this)); - - if (this._sortProperties) - properties.sort(function(a, b) { return a.name.localeCompare(b.name) }); - } - - for (var i = 0; i < properties.length; ++i) { - if (callback.call(this, properties[i], i === properties.length - 1)) - break; - } - }, - - _propertyCheckboxChanged: function(event) - { - var property = event.target.__cssProperty; - console.assert(property); - if (!property) - return; - - var textMarker = property.__propertyTextMarker; - console.assert(textMarker); - if (!textMarker) - return; - - // Check if the property has been removed already, like from double-clicking - // the checkbox and calling this event listener multiple times. - var range = textMarker.find(); - if (!range) - return; - - var text = this._codeMirror.getRange(range.from, range.to); - - function update() - { - // Replace the text with a commented version. - this._codeMirror.replaceRange("/* " + text + " */", range.from, range.to); - - // Update the line for any color swatches that got removed. - this._createColorSwatches(true, range.from.line); - } - - this._codeMirror.operation(update.bind(this)); - }, - - _propertyCommentCheckboxChanged: function(event) - { - var commentTextMarker = event.target.__commentTextMarker; - console.assert(commentTextMarker); - if (!commentTextMarker) - return; - - // Check if the comment has been removed already, like from double-clicking - // the checkbox and calling event listener multiple times. - var range = commentTextMarker.find(); - if (!range) - return; - - var text = this._codeMirror.getRange(range.from, range.to); - - // Remove the comment prefix and suffix. - text = text.replace(/^\/\*\s*/, "").replace(/\s*\*\/$/, ""); - - // Add a semicolon if there isn't one already. - if (text.length && text.charAt(text.length - 1) !== ";") - text += ";"; - - function update() - { - this._codeMirror.addLineClass(range.from.line, "wrap", WebInspector.CSSStyleDeclarationTextEditor.EditingLineStyleClassName); - this._codeMirror.replaceRange(text, range.from, range.to); - - // Update the line for any color swatches that got removed. - this._createColorSwatches(true, range.from.line); - } - - this._codeMirror.operation(update.bind(this)); - }, - - _colorSwatchClicked: function(event) - { - if (this._colorPickerPopover) - return; - - var swatch = event.target; - - var color = swatch.__color; - console.assert(color); - if (!color) - return; - - var colorTextMarker = swatch.__colorTextMarker; - console.assert(colorTextMarker); - if (!colorTextMarker) - return; - - var range = colorTextMarker.find(); - console.assert(range); - if (!range) - return; - - function updateCodeMirror(newColorText) - { - function update() - { - // The original text marker might have been cleared by a style update, - // in this case we need to find the new color text marker so we know - // the right range for the new style color text. - if (!colorTextMarker || !colorTextMarker.find()) { - colorTextMarker = null; - - var marks = this._codeMirror.findMarksAt(range.from); - if (!marks.length) - return; - - for (var i = 0; i < marks.length; ++i) { - var mark = marks[i]; - if (!mark.__markedColor) - continue; - colorTextMarker = mark; - break; - } - } - - if (!colorTextMarker) - return; - - // Sometimes we still might find a stale text marker with findMarksAt. - var newRange = colorTextMarker.find(); - if (!newRange) - return; - - range = newRange; - - colorTextMarker.clear(); - - this._codeMirror.replaceRange(newColorText, range.from, range.to); - - // The color's text format could have changed, so we need to update the "range" - // variable to anticipate a different "range.to" property. - range.to.ch = range.from.ch + newColorText.length; - - colorTextMarker = this._codeMirror.markText(range.from, range.to); - colorTextMarker.__markedColor = true; - - swatch.__colorTextMarker = colorTextMarker; - } - - this._codeMirror.operation(update.bind(this)); - } - - if (event.shiftKey) { - var nextFormat = color.nextFormat(); - console.assert(nextFormat); - if (!nextFormat) - return; - color.format = nextFormat; - - var newColorText = color.toString(); - - // Ignore the change so we don't commit the format change. However, any future user - // edits will commit the color format. - this._ignoreCodeMirrorContentDidChangeEvent = true; - updateCodeMirror.call(this, newColorText); - delete this._ignoreCodeMirrorContentDidChangeEvent; - } else { - this._colorPickerPopover = new WebInspector.Popover(this); - - var colorPicker = new WebInspector.ColorPicker; - - colorPicker.addEventListener(WebInspector.ColorPicker.Event.ColorChanged, function(event) { - updateCodeMirror.call(this, event.data.color.toString()); - }.bind(this)); - - var bounds = WebInspector.Rect.rectFromClientRect(swatch.getBoundingClientRect()); - - this._colorPickerPopover.content = colorPicker.element; - this._colorPickerPopover.present(bounds.pad(2), [WebInspector.RectEdge.MIN_X]); - - colorPicker.color = color; - } - }, - - _propertyOverriddenStatusChanged: function(event) - { - this._updateTextMarkerForPropertyIfNeeded(event.target); - }, - - _propertiesChanged: function(event) - { - // Don't try to update the document while completions are showing. Doing so will clear - // the completion hint and prevent further interaction with the completion. - if (this._completionController.isShowingCompletions()) - return; - - // Reset the content if the text is different and we are not focused. - if (!this.focused && this._style.text !== this._formattedContent()) { - this._resetContent(); - return; - } - - this._removeEditingLineClassesSoon(); - - this._updateTextMarkers(); - }, - - _markLinesWithCheckboxPlaceholder: function() - { - if (this._codeMirror.getOption("readOnly")) - return; - - var linesWithPropertyCheckboxes = {}; - var linesWithCheckboxPlaceholders = {}; - - var markers = this._codeMirror.getAllMarks(); - for (var i = 0; i < markers.length; ++i) { - var textMarker = markers[i]; - if (textMarker.__propertyCheckbox) { - var position = textMarker.find(); - if (position) - linesWithPropertyCheckboxes[position.line] = true; - } else if (textMarker.__checkboxPlaceholder) { - var position = textMarker.find(); - if (position) - linesWithCheckboxPlaceholders[position.line] = true; - } - } - - var lineCount = this._codeMirror.lineCount(); - - for (var i = 0; i < lineCount; ++i) { - if (i in linesWithPropertyCheckboxes || i in linesWithCheckboxPlaceholders) - continue; - - var position = {line: i, ch: 0}; - - var placeholderElement = document.createElement("div"); - placeholderElement.className = WebInspector.CSSStyleDeclarationTextEditor.CheckboxPlaceholderElementStyleClassName; - - var placeholderMark = this._codeMirror.setUniqueBookmark(position, placeholderElement); - placeholderMark.__checkboxPlaceholder = true; - } - }, - - _removeCheckboxPlaceholder: function(lineNumber) - { - var marks = this._codeMirror.findMarksAt({line: lineNumber, ch: 0}); - for (var i = 0; i < marks.length; ++i) { - var mark = marks[i]; - if (!mark.__checkboxPlaceholder) - continue; - - mark.clear(); - return; - } - }, - - _resetContent: function() - { - if (this._commitChangesTimeout) { - clearTimeout(this._commitChangesTimeout); - delete this._commitChangesTimeout; - } - - this._removeEditingLineClasses(); - - // Only allow editing if we have a style, it is editable and we have text range in the stylesheet. - var readOnly = !this._style || !this._style.editable || !this._style.styleSheetTextRange; - this._codeMirror.setOption("readOnly", readOnly); - - if (readOnly) { - this.element.classList.add(WebInspector.CSSStyleDeclarationTextEditor.ReadOnlyStyleClassName); - this._codeMirror.setOption("placeholder", WebInspector.UIString("No Properties")); - } else { - this.element.classList.remove(WebInspector.CSSStyleDeclarationTextEditor.ReadOnlyStyleClassName); - this._codeMirror.setOption("placeholder", WebInspector.UIString("No Properties \u2014 Click to Edit")); - } - - if (!this._style) { - this._ignoreCodeMirrorContentDidChangeEvent = true; - - this._clearTextMarkers(false, true); - - this._codeMirror.setValue(""); - this._codeMirror.clearHistory(); - this._codeMirror.markClean(); - - delete this._ignoreCodeMirrorContentDidChangeEvent; - - return; - } - - function update() - { - // Remember the cursor position/selection. - var selectionAnchor = this._codeMirror.getCursor("anchor"); - var selectionHead = this._codeMirror.getCursor("head"); - - function countNewLineCharacters(text) - { - var matches = text.match(/\n/g); - return matches ? matches.length : 0; - } - - var styleText = this._style.text; - - // Pretty print the content if there are more properties than there are lines. - // This could be an option exposed to the user; however, it is almost always - // desired in this case. - - if (styleText && this._style.visibleProperties.length <= countNewLineCharacters(styleText.trim()) + 1) { - // This style has formatted text content, so use it for a high-fidelity experience. - - var prefixWhitespaceMatch = styleText.match(/^[ \t]*\n/); - this._prefixWhitespace = prefixWhitespaceMatch ? prefixWhitespaceMatch[0] : ""; - - var suffixWhitespaceMatch = styleText.match(/\n[ \t]*$/); - this._suffixWhitespace = suffixWhitespaceMatch ? suffixWhitespaceMatch[0] : ""; - - this._codeMirror.setValue(styleText); - - if (this._prefixWhitespace) - this._codeMirror.removeLine(0); - - if (this._suffixWhitespace) { - var lineCount = this._codeMirror.lineCount(); - this._codeMirror.replaceRange("", {line: lineCount - 2}, {line: lineCount - 1}); - } - - this._linePrefixWhitespace = ""; - - var linesToStrip = []; - - // Remember the whitespace so it can be restored on commit. - var lineCount = this._codeMirror.lineCount(); - for (var i = 0; i < lineCount; ++i) { - var lineContent = this._codeMirror.getLine(i); - - var prefixWhitespaceMatch = lineContent.match(/^\s+/); - if (!prefixWhitespaceMatch) - continue; - - linesToStrip.push(i); - - // Only remember the shortest whitespace so we don't loose any of the - // original author's whitespace if their indentation lengths differed. - // Using the shortest also makes the adjustment work in _updateTextMarkers. - - // FIXME: This messes up if there is a mix of spaces and tabs. One tab - // will be shorter than 4 or 8 spaces, but will look the same visually. - if (!this._linePrefixWhitespace || prefixWhitespaceMatch[0].length < this._linePrefixWhitespace.length) - this._linePrefixWhitespace = prefixWhitespaceMatch[0]; - } - - // Strip the whitespace from the beginning of each line. - for (var i = 0; i < linesToStrip.length; ++i) { - var lineNumber = linesToStrip[i]; - var from = {line: lineNumber, ch: 0}; - var to = {line: lineNumber, ch: this._linePrefixWhitespace.length}; - this._codeMirror.replaceRange("", from, to); - } - - // Update all the text markers. - this._updateTextMarkers(true); - } else { - // This style does not have text content or it is minified, so we want to synthesize the text content. - - this._prefixWhitespace = ""; - this._suffixWhitespace = ""; - this._linePrefixWhitespace = ""; - - this._codeMirror.setValue(""); - - var lineNumber = 0; - - // Iterate only visible properties if we have original style text. That way we known we only syntesize - // what was originaly in the style text. - this._iterateOverProperties(styleText ? true : false, function(property) { - // Some property text can have line breaks, so consider that in the ranges below. - var propertyText = property.synthesizedText; - var propertyLineCount = countNewLineCharacters(propertyText); - - var from = {line: lineNumber, ch: 0}; - var to = {line: lineNumber + propertyLineCount}; - - this._codeMirror.replaceRange((lineNumber ? "\n" : "") + propertyText, from); - this._createTextMarkerForPropertyIfNeeded(from, to, property); - - lineNumber += propertyLineCount + 1; - }); - - // Look for colors and make swatches. - this._createColorSwatches(true); - } - - this._markLinesWithCheckboxPlaceholder(); - - // Restore the cursor position/selection. - this._codeMirror.setSelection(selectionAnchor, selectionHead); - - // Reset undo history since undo past the reset is wrong when the content was empty before - // or the content was representing a previous style object. - this._codeMirror.clearHistory(); - - // Mark the editor as clean (unedited state). - this._codeMirror.markClean(); - } - - // This needs to be done first and as a separate operation to avoid an exception in CodeMirror. - this._clearTextMarkers(false, true); - - this._ignoreCodeMirrorContentDidChangeEvent = true; - this._codeMirror.operation(update.bind(this)); - delete this._ignoreCodeMirrorContentDidChangeEvent; - }, - - _updateJumpToSymbolTrackingMode: function() - { - var oldJumpToSymbolTrackingModeEnabled = this._jumpToSymbolTrackingModeEnabled; - - if (!this._style || !this._style.ownerRule || !this._style.ownerRule.sourceCodeLocation) - this._jumpToSymbolTrackingModeEnabled = false; - else - this._jumpToSymbolTrackingModeEnabled = WebInspector.modifierKeys.metaKey && !WebInspector.modifierKeys.altKey && !WebInspector.modifierKeys.shiftKey; - - if (oldJumpToSymbolTrackingModeEnabled !== this._jumpToSymbolTrackingModeEnabled) { - if (this._jumpToSymbolTrackingModeEnabled) { - this._tokenTrackingController.highlightLastHoveredRange(); - this._tokenTrackingController.enabled = !this._codeMirror.getOption("readOnly"); - } else { - this._tokenTrackingController.removeHighlightedRange(); - this._tokenTrackingController.enabled = false; - } - } - }, - - tokenTrackingControllerHighlightedRangeWasClicked: function(tokenTrackingController) - { - console.assert(this._style.ownerRule.sourceCodeLocation); - if (!this._style.ownerRule.sourceCodeLocation) - return; - - // Special case command clicking url(...) links. - var token = this._tokenTrackingController.candidate.hoveredToken; - if (/\blink\b/.test(token.type)) { - var url = token.string; - var baseURL = this._style.ownerRule.sourceCodeLocation.sourceCode.url; - WebInspector.openURL(absoluteURL(url, baseURL)); - return; - } - - // Jump to the rule if we can't find a property. - // Find a better source code location from the property that was clicked. - var sourceCodeLocation = this._style.ownerRule.sourceCodeLocation; - var marks = this._codeMirror.findMarksAt(this._tokenTrackingController.candidate.hoveredTokenRange.start); - for (var i = 0; i < marks.length; ++i) { - var mark = marks[i]; - var property = mark.__cssProperty; - if (property) { - var sourceCode = sourceCodeLocation.sourceCode; - var styleSheetTextRange = property.styleSheetTextRange; - sourceCodeLocation = sourceCode.createSourceCodeLocation(styleSheetTextRange.startLine, styleSheetTextRange.startColumn); - } - } - - WebInspector.resourceSidebarPanel.showSourceCodeLocation(sourceCodeLocation); - }, - - tokenTrackingControllerNewHighlightCandidate: function(tokenTrackingController, candidate) - { - this._tokenTrackingController.highlightRange(candidate.hoveredTokenRange); - } -}; - -WebInspector.CSSStyleDeclarationTextEditor.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/CSSStyleDetailsSidebarPanel.css b/Source/WebInspectorUI/UserInterface/CSSStyleDetailsSidebarPanel.css deleted file mode 100644 index df62c2e47..000000000 --- a/Source/WebInspectorUI/UserInterface/CSSStyleDetailsSidebarPanel.css +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.sidebar > .panel.details.css-style > .navigation-bar { - position: absolute; - top: 0; - left: 0; - right: 0; -} - -.sidebar > .panel.details.css-style > .content { - position: absolute; - top: 22px; - left: 0; - right: 0; - bottom: 0; - - overflow-y: auto; - overflow-x: hidden; -} - -.sidebar > .panel.details.css-style > .content > .pseudo-classes { - font-size: 11px; - font-family: "Lucida Grande", sans-serif; - - padding: 10px; - - display: -webkit-flex; - -webkit-flex-flow: row wrap; - -webkit-justify-content: space-around; -} - -.sidebar > .panel.details.css-style > .content > .pseudo-classes > .group { - display: -webkit-inline-flex; - -webkit-flex-flow: row wrap; - -webkit-justify-content: space-around; - -webkit-flex: 1; -} - -.sidebar > .panel.details.css-style > .content > .pseudo-classes > .group > label { - color: rgb(96, 96, 96); - text-shadow: white 0 1px 0; - - margin: 0 5px; - min-width: 55px; - - display: inline-block; - white-space: nowrap; -} diff --git a/Source/WebInspectorUI/UserInterface/CSSStyleDetailsSidebarPanel.js b/Source/WebInspectorUI/UserInterface/CSSStyleDetailsSidebarPanel.js deleted file mode 100644 index f5ebeb4ab..000000000 --- a/Source/WebInspectorUI/UserInterface/CSSStyleDetailsSidebarPanel.js +++ /dev/null @@ -1,240 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.CSSStyleDetailsSidebarPanel = function() -{ - WebInspector.DOMDetailsSidebarPanel.call(this, "css-style", WebInspector.UIString("Styles"), WebInspector.UIString("Style"), "Images/NavigationItemBrushAndRuler.svg", "4"); - - this._selectedPanel = null; - - this._navigationBar = new WebInspector.NavigationBar(null, null, "tablist"); - this._navigationBar.addEventListener(WebInspector.NavigationBar.Event.NavigationItemSelected, this._navigationItemSelected, this); - this.element.appendChild(this._navigationBar.element); - - this._contentElement = document.createElement("div"); - this._contentElement.className = WebInspector.CSSStyleDetailsSidebarPanel.ContentStyleClassName; - - this._forcedPseudoClassCheckboxes = {}; - - if (WebInspector.cssStyleManager.canForcePseudoClasses()) { - this._forcedPseudoClassContainer = document.createElement("div"); - this._forcedPseudoClassContainer.className = WebInspector.CSSStyleDetailsSidebarPanel.PseudoClassesElementStyleClassName; - - var groupElement = null; - - WebInspector.CSSStyleManager.ForceablePseudoClasses.forEach(function(pseudoClass) { - // We don't localize the label since it is a CSS pseudo-class from the CSS standard. - var label = pseudoClass.capitalize(); - - var labelElement = document.createElement("label"); - - var checkboxElement = document.createElement("input"); - checkboxElement.addEventListener("change", this._forcedPseudoClassCheckboxChanged.bind(this, pseudoClass)); - checkboxElement.type = "checkbox"; - - this._forcedPseudoClassCheckboxes[pseudoClass] = checkboxElement; - - labelElement.appendChild(checkboxElement); - labelElement.appendChild(document.createTextNode(label)); - - if (!groupElement || groupElement.children.length === 2) { - groupElement = document.createElement("div"); - groupElement.className = WebInspector.CSSStyleDetailsSidebarPanel.PseudoClassesGroupElementStyleClassName; - this._forcedPseudoClassContainer.appendChild(groupElement); - } - - groupElement.appendChild(labelElement); - }.bind(this)); - - this._contentElement.appendChild(this._forcedPseudoClassContainer); - } - - this.element.appendChild(this._contentElement); - - this._computedStyleDetailsPanel = new WebInspector.ComputedStyleDetailsPanel; - this._rulesStyleDetailsPanel = new WebInspector.RulesStyleDetailsPanel; - this._metricsStyleDetailsPanel = new WebInspector.MetricsStyleDetailsPanel; - - this._panels = [this._computedStyleDetailsPanel, this._rulesStyleDetailsPanel, this._metricsStyleDetailsPanel]; - - this._navigationBar.addNavigationItem(this._computedStyleDetailsPanel.navigationItem); - this._navigationBar.addNavigationItem(this._rulesStyleDetailsPanel.navigationItem); - this._navigationBar.addNavigationItem(this._metricsStyleDetailsPanel.navigationItem); - - this._lastSelectedSectionSetting = new WebInspector.Setting("last-selected-style-details-panel", this._rulesStyleDetailsPanel.navigationItem.identifier); - - // This will cause the selected panel to be set in _navigationItemSelected. - this._navigationBar.selectedNavigationItem = this._lastSelectedSectionSetting.value; -}; - -WebInspector.CSSStyleDetailsSidebarPanel.ContentStyleClassName = "content"; -WebInspector.CSSStyleDetailsSidebarPanel.PseudoClassesElementStyleClassName = "pseudo-classes"; -WebInspector.CSSStyleDetailsSidebarPanel.PseudoClassesGroupElementStyleClassName = "group"; -WebInspector.CSSStyleDetailsSidebarPanel.NoForcedPseudoClassesScrollOffset = 38; // Default height of the forced pseudo classes container. Updated in widthDidChange. - -WebInspector.CSSStyleDetailsSidebarPanel.prototype = { - constructor: WebInspector.CSSStyleDetailsSidebarPanel, - - // Public - - supportsDOMNode: function(nodeToInspect) - { - return nodeToInspect.nodeType() === Node.ELEMENT_NODE; - }, - - refresh: function() - { - var domNode = this.domNode; - if (!domNode) - return; - - this._contentElement.scrollTop = this._initialScrollOffset; - - for (var i = 0; i < this._panels.length; ++i) { - delete this._panels[i].element._savedScrollTop; - this._panels[i].markAsNeedsRefresh(domNode); - } - - this._updatePseudoClassCheckboxes(); - }, - - visibilityDidChange: function() - { - WebInspector.SidebarPanel.prototype.visibilityDidChange.call(this); - - if (!this._selectedPanel) - return; - - if (!this.visible) { - this._selectedPanel.hidden(); - return; - } - - this._navigationBar.updateLayout(); - - this._updateNoForcedPseudoClassesScrollOffset(); - - this._selectedPanel.shown(); - this._selectedPanel.markAsNeedsRefresh(this.domNode); - }, - - widthDidChange: function() - { - this._updateNoForcedPseudoClassesScrollOffset(); - - if (this._selectedPanel) - this._selectedPanel.widthDidChange(); - }, - - // Protected - - addEventListeners: function() - { - this.domNode.addEventListener(WebInspector.DOMNode.Event.EnabledPseudoClassesChanged, this._updatePseudoClassCheckboxes, this); - }, - - removeEventListeners: function() - { - this.domNode.removeEventListener(null, null, this); - }, - - // Private - - get _initialScrollOffset() - { - if (!WebInspector.cssStyleManager.canForcePseudoClasses()) - return 0; - return this.domNode && this.domNode.enabledPseudoClasses.length ? 0 : WebInspector.CSSStyleDetailsSidebarPanel.NoForcedPseudoClassesScrollOffset; - }, - - _updateNoForcedPseudoClassesScrollOffset: function() - { - if (this._forcedPseudoClassContainer) - WebInspector.CSSStyleDetailsSidebarPanel.NoForcedPseudoClassesScrollOffset = this._forcedPseudoClassContainer.offsetHeight; - }, - - _navigationItemSelected: function(event) - { - console.assert(event.target.selectedNavigationItem); - if (!event.target.selectedNavigationItem) - return; - - var selectedNavigationItem = event.target.selectedNavigationItem; - - var selectedPanel = null; - for (var i = 0; i < this._panels.length; ++i) { - if (this._panels[i].navigationItem !== selectedNavigationItem) - continue; - selectedPanel = this._panels[i]; - break; - } - - console.assert(selectedPanel); - - if (this._selectedPanel) { - this._selectedPanel.hidden(); - this._selectedPanel.element._savedScrollTop = this._contentElement.scrollTop; - this._selectedPanel.element.remove(); - } - - this._selectedPanel = selectedPanel; - - if (this._selectedPanel) { - this._contentElement.appendChild(this._selectedPanel.element); - - if (typeof this._selectedPanel.element._savedScrollTop === "number") - this._contentElement.scrollTop = this._selectedPanel.element._savedScrollTop; - else - this._contentElement.scrollTop = this._initialScrollOffset; - - this._selectedPanel.shown(); - } - - this._lastSelectedSectionSetting.value = selectedNavigationItem.identifier; - }, - - _forcedPseudoClassCheckboxChanged: function(pseudoClass, event) - { - if (!this.domNode) - return; - - this.domNode.setPseudoClassEnabled(pseudoClass, event.target.checked); - }, - - _updatePseudoClassCheckboxes: function() - { - if (!this.domNode) - return; - - var enabledPseudoClasses = this.domNode.enabledPseudoClasses; - - for (var pseudoClass in this._forcedPseudoClassCheckboxes) { - var checkboxElement = this._forcedPseudoClassCheckboxes[pseudoClass]; - checkboxElement.checked = enabledPseudoClasses.contains(pseudoClass); - } - } -}; - -WebInspector.CSSStyleDetailsSidebarPanel.prototype.__proto__ = WebInspector.DOMDetailsSidebarPanel.prototype; diff --git a/Source/WebInspectorUI/UserInterface/CSSStyleManager.js b/Source/WebInspectorUI/UserInterface/CSSStyleManager.js deleted file mode 100644 index d8f049a5b..000000000 --- a/Source/WebInspectorUI/UserInterface/CSSStyleManager.js +++ /dev/null @@ -1,367 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.CSSStyleManager = function() -{ - WebInspector.Object.call(this); - - if (window.CSSAgent) - CSSAgent.enable(); - - WebInspector.Frame.addEventListener(WebInspector.Frame.Event.MainResourceDidChange, this._mainResourceDidChange, this); - WebInspector.Frame.addEventListener(WebInspector.Frame.Event.ResourceWasAdded, this._resourceAdded, this); - WebInspector.Resource.addEventListener(WebInspector.SourceCode.Event.ContentDidChange, this._resourceContentDidChange, this); - WebInspector.Resource.addEventListener(WebInspector.Resource.Event.TypeDidChange, this._resourceTypeDidChange, this); - - WebInspector.DOMNode.addEventListener(WebInspector.DOMNode.Event.AttributeModified, this._nodeAttributesDidChange, this); - WebInspector.DOMNode.addEventListener(WebInspector.DOMNode.Event.AttributeRemoved, this._nodeAttributesDidChange, this); - WebInspector.DOMNode.addEventListener(WebInspector.DOMNode.Event.EnabledPseudoClassesChanged, this._nodePseudoClassesDidChange, this); - - this._colorFormatSetting = new WebInspector.Setting("default-color-format", WebInspector.Color.Format.Original); - - this._styleSheetIdentifierMap = {}; - this._styleSheetFrameURLMap = {}; - this._nodeStylesMap = {}; -} - -WebInspector.CSSStyleManager.ForceablePseudoClasses = ["active", "focus", "hover", "visited"]; - -WebInspector.CSSStyleManager.prototype = { - constructor: WebInspector.CSSStyleManager, - - // Public - - get preferredColorFormat() - { - return this._colorFormatSetting.value; - }, - - canForcePseudoClasses: function() - { - return window.CSSAgent && !!CSSAgent.forcePseudoState; - }, - - propertyNameHasOtherVendorPrefix: function(name) - { - if (!name || name.length < 4 || name.charAt(0) !== "-") - return false; - - var match = name.match(/^(?:-moz-|-ms-|-o-|-epub-)/); - if (!match) - return false; - - return true; - }, - - propertyValueHasOtherVendorKeyword: function(value) - { - var match = value.match(/(?:-moz-|-ms-|-o-|-epub-)[-\w]+/); - if (!match) - return false; - - return true; - }, - - canonicalNameForPropertyName: function(name) - { - if (!name || name.length < 8 || name.charAt(0) !== "-") - return name; - - var match = name.match(/^(?:-webkit-|-khtml-|-apple-)(.+)/); - if (!match) - return name; - - return match[1]; - }, - - styleSheetForIdentifier: function(id) - { - if (id in this._styleSheetIdentifierMap) - return this._styleSheetIdentifierMap[id]; - - var styleSheet = new WebInspector.CSSStyleSheet(id); - this._styleSheetIdentifierMap[id] = styleSheet; - return styleSheet; - }, - - stylesForNode: function(node) - { - if (node.id in this._nodeStylesMap) - return this._nodeStylesMap[node.id]; - - var styles = new WebInspector.DOMNodeStyles(node); - this._nodeStylesMap[node.id] = styles; - return styles; - }, - - // Protected - - mediaQueryResultChanged: function() - { - // Called from WebInspector.CSSObserver. - - for (var key in this._nodeStylesMap) - this._nodeStylesMap[key].mediaQueryResultDidChange(); - }, - - styleSheetChanged: function(styleSheetIdentifier) - { - // Called from WebInspector.CSSObserver. - - var styleSheet = this.styleSheetForIdentifier(styleSheetIdentifier); - console.assert(styleSheet); - - styleSheet.noteContentDidChange(); - - this._updateResourceContent(styleSheet); - }, - - // Private - - _nodePseudoClassesDidChange: function(event) - { - var node = event.target; - - for (var key in this._nodeStylesMap) { - var nodeStyles = this._nodeStylesMap[key]; - if (nodeStyles.node !== node && !nodeStyles.node.isDescendant(node)) - continue; - nodeStyles.pseudoClassesDidChange(node); - } - }, - - _nodeAttributesDidChange: function(event) - { - var node = event.target; - - for (var key in this._nodeStylesMap) { - var nodeStyles = this._nodeStylesMap[key]; - if (nodeStyles.node !== node && !nodeStyles.node.isDescendant(node)) - continue; - nodeStyles.attributeDidChange(node, event.data.name); - } - }, - - _mainResourceDidChange: function(event) - { - console.assert(event.target instanceof WebInspector.Frame); - - if (!event.target.isMainFrame()) - return; - - // Clear our maps when the main frame navigates. - - this._styleSheetIdentifierMap = {}; - this._styleSheetFrameURLMap = {}; - this._nodeStylesMap = {}; - }, - - _resourceAdded: function(event) - { - console.assert(event.target instanceof WebInspector.Frame); - - var resource = event.data.resource; - console.assert(resource); - - if (resource.type !== WebInspector.Resource.Type.Stylesheet) - return; - - this._clearStyleSheetsForResource(resource); - }, - - _resourceTypeDidChange: function(event) - { - console.assert(event.target instanceof WebInspector.Resource); - - var resource = event.target; - if (resource.type !== WebInspector.Resource.Type.Stylesheet) - return; - - this._clearStyleSheetsForResource(resource); - }, - - _clearStyleSheetsForResource: function(resource) - { - // Clear known stylesheets for this URL and frame. This will cause the stylesheets to - // be updated next time _fetchInfoForAllStyleSheets is called. - // COMPATIBILITY (iOS 6): The frame's id was not available for the key, so delete just the url too. - delete this._styleSheetFrameURLMap[this._frameURLMapKey(resource.parentFrame, resource.url)]; - delete this._styleSheetFrameURLMap[resource.url]; - }, - - _frameURLMapKey: function(frame, url) - { - return (frame ? frame.id + ":" : "") + url; - }, - - _lookupStyleSheetForResource: function(resource, callback) - { - this._lookupStyleSheet(resource.parentFrame, resource.url, callback); - }, - - _lookupStyleSheet: function(frame, url, callback) - { - console.assert(frame instanceof WebInspector.Frame); - - function syleSheetsFetched() - { - callback(this._styleSheetFrameURLMap[key] || this._styleSheetFrameURLMap[url] || null); - } - - var key = this._frameURLMapKey(frame, url); - - // COMPATIBILITY (iOS 6): The frame's id was not available for the key, so check for just the url too. - if (key in this._styleSheetFrameURLMap || url in this._styleSheetFrameURLMap) - callback(this._styleSheetFrameURLMap[key] || this._styleSheetFrameURLMap[url] || null); - else - this._fetchInfoForAllStyleSheets(syleSheetsFetched.bind(this)); - }, - - _fetchInfoForAllStyleSheets: function(callback) - { - console.assert(typeof callback === "function"); - - function processStyleSheets(error, styleSheets) - { - this._styleSheetFrameURLMap = {}; - - if (error) { - callback(); - return; - } - - for (var i = 0; i < styleSheets.length; ++i) { - var styleSheetInfo = styleSheets[i]; - - // COMPATIBILITY (iOS 6): The info did not have 'frameId', so make parentFrame null in that case. - var parentFrame = "frameId" in styleSheetInfo ? WebInspector.frameResourceManager.frameForIdentifier(styleSheetInfo.frameId) : null; - - var styleSheet = this.styleSheetForIdentifier(styleSheetInfo.styleSheetId); - styleSheet.updateInfo(styleSheetInfo.sourceURL, parentFrame); - - var key = this._frameURLMapKey(parentFrame, styleSheetInfo.sourceURL); - this._styleSheetFrameURLMap[key] = styleSheet; - } - - callback(); - } - - CSSAgent.getAllStyleSheets(processStyleSheets.bind(this)); - }, - - _resourceContentDidChange: function(event) - { - var resource = event.target; - if (resource === this._ignoreResourceContentDidChangeEventForResource) - return; - - // Ignore if it isn't a CSS stylesheet. - if (resource.type !== WebInspector.Resource.Type.Stylesheet || resource.syntheticMIMEType !== "text/css") - return; - - function applyStyleSheetChanges() - { - function styleSheetFound(styleSheet) - { - delete resource.__pendingChangeTimeout; - - console.assert(styleSheet); - if (!styleSheet) - return; - - // To prevent updating a TextEditor's content while the user is typing in it we want to - // ignore the next _updateResourceContent call. - resource.__ignoreNextUpdateResourceContent = true; - - WebInspector.branchManager.currentBranch.revisionForRepresentedObject(styleSheet).content = resource.content; - } - - this._lookupStyleSheetForResource(resource, styleSheetFound.bind(this)); - } - - if (resource.__pendingChangeTimeout) - clearTimeout(resource.__pendingChangeTimeout); - resource.__pendingChangeTimeout = setTimeout(applyStyleSheetChanges.bind(this), 500); - }, - - _updateResourceContent: function(styleSheet) - { - console.assert(styleSheet); - - function fetchedStyleSheetContent(styleSheet, content) - { - delete styleSheet.__pendingChangeTimeout; - - console.assert(styleSheet.url); - if (!styleSheet.url) - return; - - var resource = null; - - // COMPATIBILITY (iOS 6): The stylesheet did not always have a frame, so fallback to looking - // for the resource in all frames. - if (styleSheet.parentFrame) - resource = styleSheet.parentFrame.resourceForURL(styleSheet.url); - else - resource = WebInspector.frameResourceManager.resourceForURL(styleSheet.url); - - if (!resource) - return; - - // Only try to update stylesheet resources. Other resources, like documents, can contain - // multiple stylesheets and we don't have the source ranges to update those. - if (resource.type !== WebInspector.Resource.Type.Stylesheet) - return; - - if (resource.__ignoreNextUpdateResourceContent) { - delete resource.__ignoreNextUpdateResourceContent; - return; - } - - this._ignoreResourceContentDidChangeEventForResource = resource; - WebInspector.branchManager.currentBranch.revisionForRepresentedObject(resource).content = content; - delete this._ignoreResourceContentDidChangeEventForResource; - } - - function styleSheetReady() - { - styleSheet.requestContent(fetchedStyleSheetContent.bind(this)); - } - - function applyStyleSheetChanges() - { - if (styleSheet.url) - styleSheetReady.call(this); - else - this._fetchInfoForAllStyleSheets(styleSheetReady.bind(this)); - } - - if (styleSheet.__pendingChangeTimeout) - clearTimeout(styleSheet.__pendingChangeTimeout); - styleSheet.__pendingChangeTimeout = setTimeout(applyStyleSheetChanges.bind(this), 500); - } -} - -WebInspector.CSSStyleManager.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/CSSStyleSheet.js b/Source/WebInspectorUI/UserInterface/CSSStyleSheet.js deleted file mode 100644 index ef26aeb1a..000000000 --- a/Source/WebInspectorUI/UserInterface/CSSStyleSheet.js +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.CSSStyleSheet = function(id, url, parentFrame) -{ - WebInspector.SourceCode.call(this); - - console.assert(id); - - this._id = id || null; - - this.updateInfo(url, parentFrame); -}; - -WebInspector.Object.addConstructorFunctions(WebInspector.CSSStyleSheet); - -WebInspector.CSSStyleSheet.resetUniqueDisplayNameNumbers = function() -{ - WebInspector.CSSStyleSheet._nextUniqueDisplayNameNumber = 1; -} - -WebInspector.CSSStyleSheet._nextUniqueDisplayNameNumber = 1; - -WebInspector.CSSStyleSheet.Event = { - ContentDidChange: "stylesheet-content-did-change" -}; - -WebInspector.CSSStyleSheet.prototype = { - constructor: WebInspector.CSSStyleSheet, - - // Public - - get id() - { - return this._id; - }, - - get parentFrame() - { - return this._parentFrame; - }, - - get url() - { - return this._url; - }, - - get urlComponents() - { - if (!this._urlComponents) - this._urlComponents = parseURL(this._url); - return this._urlComponents; - }, - - get displayName() - { - if (this._url) - return WebInspector.displayNameForURL(this._url, this.urlComponents); - - // Assign a unique number to the StyleSheet object so it will stay the same. - if (!this._uniqueDisplayNameNumber) - this._uniqueDisplayNameNumber = this.constructor._nextUniqueDisplayNameNumber++; - - return WebInspector.UIString("Anonymous StyleSheet %d").format(this._uniqueDisplayNameNumber); - }, - - // Protected - - updateInfo: function(url, parentFrame) - { - this._url = url || null; - delete this._urlComponents; - - this._parentFrame = parentFrame || null; - }, - - get revisionForRequestedContent() - { - return this.currentRevision; - }, - - handleCurrentRevisionContentChange: function() - { - if (!this._id) - return; - - function contentDidChange(error) - { - if (error) - return; - - DOMAgent.markUndoableState(); - - this.dispatchEventToListeners(WebInspector.CSSStyleSheet.Event.ContentDidChange); - } - - this._ignoreNextContentDidChangeNotification = true; - - CSSAgent.setStyleSheetText(this._id, this.currentRevision.content, contentDidChange.bind(this)); - }, - - canRequestContentFromBackend: function() - { - // We can request content if we have an id. - return !!this._id; - }, - - requestContentFromBackend: function(callback) - { - if (!this._id) { - // There is no identifier to request content with. Return false to cause the - // pending callbacks to get null content. - return false; - } - - CSSAgent.getStyleSheetText(this._id, callback); - return true; - }, - - noteContentDidChange: function() - { - if (this._ignoreNextContentDidChangeNotification) { - delete this._ignoreNextContentDidChangeNotification; - return false; - } - - this.markContentAsStale(); - this.dispatchEventToListeners(WebInspector.CSSStyleSheet.Event.ContentDidChange); - return true; - } -}; - -WebInspector.CSSStyleSheet.prototype.__proto__ = WebInspector.SourceCode.prototype; diff --git a/Source/WebInspectorUI/UserInterface/CallFrame.js b/Source/WebInspectorUI/UserInterface/CallFrame.js deleted file mode 100644 index 6ffd0c86a..000000000 --- a/Source/WebInspectorUI/UserInterface/CallFrame.js +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.CallFrame = function(id, sourceCodeLocation, functionName, thisObject, scopeChain, nativeCode) -{ - WebInspector.Object.call(this); - - console.assert(!sourceCodeLocation || sourceCodeLocation instanceof WebInspector.SourceCodeLocation); - console.assert(!thisObject || thisObject instanceof WebInspector.RemoteObject); - console.assert(!scopeChain || scopeChain instanceof Array); - - this._id = id || null; - this._sourceCodeLocation = sourceCodeLocation || null; - this._functionName = functionName || null; - this._thisObject = thisObject || null; - this._scopeChain = scopeChain || []; - this._nativeCode = nativeCode || false; -}; - -WebInspector.CallFrame.prototype = { - constructor: WebInspector.CallFrame, - - // Public - - get id() - { - return this._id; - }, - - get sourceCodeLocation() - { - return this._sourceCodeLocation; - }, - - get functionName() - { - return this._functionName; - }, - - get nativeCode() - { - return this._nativeCode; - }, - - get thisObject() - { - return this._thisObject; - }, - - get scopeChain() - { - return this._scopeChain; - }, - - saveIdentityToCookie: function() - { - // Do nothing. The call frame is torn down when the inspector closes, and - // we shouldn't restore call frame content views across debugger pauses. - }, - - collectScopeChainVariableNames: function(callback) - { - var result = {this: true}; - - var pendingRequests = this._scopeChain.length; - - function propertiesCollected(properties) - { - for (var i = 0; properties && i < properties.length; ++i) - result[properties[i].name] = true; - - if (--pendingRequests) - return; - - callback(result); - } - - for (var i = 0; i < this._scopeChain.length; ++i) - this._scopeChain[i].object.getAllProperties(propertiesCollected); - } -}; - -WebInspector.CallFrame.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/CallFrameIcons.css b/Source/WebInspectorUI/UserInterface/CallFrameIcons.css deleted file mode 100644 index 45d993c24..000000000 --- a/Source/WebInspectorUI/UserInterface/CallFrameIcons.css +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.function-icon .icon { - content: url(Images/Function.svg); -} - -.event-listener-icon .icon { - content: url(Images/EventListener.svg); -} - -.native-icon .icon { - content: url(Images/Native.svg); -} diff --git a/Source/WebInspectorUI/UserInterface/CallFrameTreeElement.js b/Source/WebInspectorUI/UserInterface/CallFrameTreeElement.js deleted file mode 100644 index 1fb0329c9..000000000 --- a/Source/WebInspectorUI/UserInterface/CallFrameTreeElement.js +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.CallFrameTreeElement = function(callFrame) -{ - console.assert(callFrame instanceof WebInspector.CallFrame); - - var className = WebInspector.CallFrameTreeElement.FunctionIconStyleClassName; - if (callFrame.nativeCode) - className = WebInspector.CallFrameTreeElement.NativeIconStyleClassName; - - // This is more than likely an event listener function with an "on" prefix and it is - // as long or longer than the shortest event listener name -- "oncut". - if (callFrame.functionName && callFrame.functionName.startsWith("on") && callFrame.functionName.length >= 5) - className = WebInspector.CallFrameTreeElement.EventListenerIconStyleClassName; - - var title = callFrame.functionName || WebInspector.UIString("(anonymous function)"); - - WebInspector.GeneralTreeElement.call(this, className, title, null, callFrame, false); - - if (!callFrame.nativeCode && callFrame.sourceCodeLocation) { - var displayScriptURL = callFrame.sourceCodeLocation.displaySourceCode.url; - if (displayScriptURL) { - this.subtitle = document.createElement("span"); - callFrame.sourceCodeLocation.populateLiveDisplayLocationString(this.subtitle, "textContent"); - // Set the tooltip on the entire tree element in onattach, once the element is created. - this.tooltipHandledSeparately = true; - } - } - - this._callFrame = callFrame; - - this.small = true; -}; - -WebInspector.CallFrameTreeElement.FunctionIconStyleClassName = "function-icon"; -WebInspector.CallFrameTreeElement.EventListenerIconStyleClassName = "event-listener-icon"; -WebInspector.CallFrameTreeElement.NativeIconStyleClassName = "native-icon"; - -WebInspector.CallFrameTreeElement.prototype = { - constructor: WebInspector.CallFrameTreeElement, - - // Public - - get callFrame() - { - return this._callFrame; - }, - - // Protected - - onattach: function() - { - WebInspector.GeneralTreeElement.prototype.onattach.call(this); - - console.assert(this.element); - - if (this.tooltipHandledSeparately) { - var tooltipPrefix = this.mainTitle + "\n"; - this._callFrame.sourceCodeLocation.populateLiveDisplayLocationTooltip(this.element, tooltipPrefix); - } - } -}; - -WebInspector.CallFrameTreeElement.prototype.__proto__ = WebInspector.GeneralTreeElement.prototype; diff --git a/Source/WebInspectorUI/UserInterface/CanvasDataGridNode.js b/Source/WebInspectorUI/UserInterface/CanvasDataGridNode.js deleted file mode 100644 index f0bbadbcd..000000000 --- a/Source/WebInspectorUI/UserInterface/CanvasDataGridNode.js +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.CanvasDataGridNode = function(profileView, data) -{ - WebInspector.DataGridNode.call(this, data, false); - this._profileView = profileView; -} - -WebInspector.CanvasDataGridNode.prototype = { - - constructor: WebInspector.CanvasDataGridNode, - - get data() - { - var data = {}; - return data; - }, - - get rawData() - { - return this._data; - }, - - createCell: function(columnIdentifier) - { - var cell = WebInspector.DataGridNode.prototype.createCell.call(this, columnIdentifier); - cell.removeChildren(); - - if (this.rawData.url) { - var wrapperDiv = cell.createChild("div"); - wrapperDiv.appendChild(this._linkifyLocation(this.rawData.url, this.rawData.lineNumber, this.rawData.columnNumber)); - } - - return cell; - }, - - _linkifyLocation: function(url, lineNumber, columnNumber) - { - return WebInspector.linkifyLocation(url, lineNumber, columnNumber || 0); - } -} - -WebInspector.CanvasDataGridNode.prototype.__proto__ = WebInspector.DataGridNode.prototype; - diff --git a/Source/WebInspectorUI/UserInterface/CanvasObserver.js b/Source/WebInspectorUI/UserInterface/CanvasObserver.js deleted file mode 100644 index 2bd56a740..000000000 --- a/Source/WebInspectorUI/UserInterface/CanvasObserver.js +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.CanvasObserver = function() -{ - WebInspector.Object.call(this); -}; - -WebInspector.CanvasObserver.prototype = { - constructor: WebInspector.CanvasObserver, - - // Events defined by the "Canvas" domain. - - contextCreated: function(frameId) - { - // FIXME: Implement this. - }, - - traceLogsRemoved: function(frameId, traceLogId) - { - // FIXME: Implement this. - } -}; - -WebInspector.CanvasObserver.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/CanvasProfileObject.js b/Source/WebInspectorUI/UserInterface/CanvasProfileObject.js deleted file mode 100644 index e7fd424e4..000000000 --- a/Source/WebInspectorUI/UserInterface/CanvasProfileObject.js +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.CanvasProfileObject = function(title, id, recording, data) -{ - WebInspector.ProfileObject.call(this, WebInspector.CanvasProfileType.TypeId, title, id, recording); - - this._data = data || []; -}; - -WebInspector.CanvasProfileObject.prototype = { - constructor: WebInspector.CanvasProfileObject, - - get data() - { - return this._data; - }, - - set data(data) - { - this._data = data; - } -}; - -WebInspector.CanvasProfileObject.prototype.__proto__ = WebInspector.ProfileObject.prototype; diff --git a/Source/WebInspectorUI/UserInterface/CanvasProfileType.js b/Source/WebInspectorUI/UserInterface/CanvasProfileType.js deleted file mode 100644 index 099981e0b..000000000 --- a/Source/WebInspectorUI/UserInterface/CanvasProfileType.js +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.CanvasProfileType = function() -{ - WebInspector.ProfileType.call(this, WebInspector.CanvasProfileType.TypeId, WebInspector.UIString("Collect Canvas Profile")); - this._recording = false; - this._profileId = 1; - WebInspector.CanvasProfileType.instance = this; -} - -WebInspector.CanvasProfileType.TypeId = "CANVAS"; - -WebInspector.CanvasProfileType.prototype = { - - constructor: WebInspector.CanvasProfileType, - - get buttonTooltip() - { - return this._recording ? WebInspector.UIString("Stop Canvas profiling.") : WebInspector.UIString("Start Canvas profiling."); - }, - - buttonClicked: function() - { - if (this._recording) - this.stopRecordingProfile(); - else - this.startRecordingProfile(); - }, - - get treeItemTitle() - { - return WebInspector.UIString("CANVAS PROFILES"); - }, - - get description() - { - return WebInspector.UIString("Canvas profiles allow you to examine drawing operations on canvas elements."); - }, - - reset: function() - { - this._profileId = 1; - }, - - nextProfileId: function() - { - return this._profileId++; - }, - - isRecordingProfile: function() - { - return this._recording; - }, - - setRecordingProfile: function(isProfiling) - { - this._recording = isProfiling; - }, - - startRecordingProfile: function() - { - this._recording = true; - // FIXME: This is where we would ask the Canvas Agent to profile. - }, - - stopRecordingProfile: function(callback) - { - this._recording = false; - // FIXME: This is where we would ask the Canvas Agent to stop profiling. - // For now pass in an empty array of canvas calls. - callback(null, {data: []}); - }, - - createSidebarTreeElementForProfile: function(profile) - { - return new WebInspector.ProfileSidebarTreeElement(profile, profile.title, "profile-sidebar-tree-item"); - }, - - createView: function(profile) - { - return new WebInspector.CanvasProfileView(profile); - } -} - -WebInspector.CanvasProfileType.prototype.__proto__ = WebInspector.ProfileType.prototype; diff --git a/Source/WebInspectorUI/UserInterface/CanvasProfileView.js b/Source/WebInspectorUI/UserInterface/CanvasProfileView.js deleted file mode 100644 index da385c1a4..000000000 --- a/Source/WebInspectorUI/UserInterface/CanvasProfileView.js +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.CanvasProfileView = function(profile) -{ - console.assert(profile instanceof WebInspector.CanvasProfileObject); - - WebInspector.ProfileView.call(this, profile); -} - -WebInspector.CanvasProfileView.prototype = { - - constructor: WebInspector.CanvasProfileView, - - updateLayout: function() - { - if (this.dataGrid) - this.dataGrid.updateLayout(); - }, - - get recordingTitle() - { - return WebInspector.UIString("Recording Canvas Profile…"); - }, - - displayProfile: function() - { - var columns = {"number": {title: "#", width: "5%", sortable: false}, - "source": {title: WebInspector.UIString("Call"), width: "75%", sortable: false, disclosure: true}, - "location": {title: WebInspector.UIString("Location"), width: "20%", sortable: false}}; - - this.dataGrid = new WebInspector.DataGrid(columns); - this.dataGrid.element.classList.add("canvas-profile-view"); - - this.element.appendChild(this.dataGrid.element); - this.dataGrid.updateLayout(); - - this._createProfileNodes(); - }, - - _createProfileNodes: function() - { - var data = this.profile.data; - if (!data) { - // The profiler may have been terminated with the "Clear all profiles." button. - return; - } - - this.profile.children = []; - for (var i = 0; i < data.length; ++i) { - var node = new WebInspector.CanvasDataGridNode(this, data[i]); - this.profile.children.push(node); - } - }, - - rebuildGridItems: function() - { - this.dataGrid.removeChildren(); - - var children = this.profile.children; - var count = children.length; - - for (var index = 0; index < count; ++index) - this.dataGrid.appendChild(children[index]); - }, - - refreshData: function() - { - var child = this.dataGrid.children[0]; - while (child) { - child.refresh(); - child = child.traverseNextNode(false, null, true); - } - } - -} - -WebInspector.CanvasProfileView.prototype.__proto__ = WebInspector.ProfileView.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ClusterContentView.css b/Source/WebInspectorUI/UserInterface/ClusterContentView.css deleted file mode 100644 index f0df69078..000000000 --- a/Source/WebInspectorUI/UserInterface/ClusterContentView.css +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.content-view.cluster > .content-view-container { - position: absolute; - top: 0; - left: 0; - right: 0; - bottom: 0; -} diff --git a/Source/WebInspectorUI/UserInterface/ClusterContentView.js b/Source/WebInspectorUI/UserInterface/ClusterContentView.js deleted file mode 100644 index 4631a0104..000000000 --- a/Source/WebInspectorUI/UserInterface/ClusterContentView.js +++ /dev/null @@ -1,257 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ClusterContentView = function(representedObject) -{ - WebInspector.ContentView.call(this, representedObject); - - this.element.classList.add(WebInspector.ClusterContentView.StyleClassName); - - this._contentViewContainer = new WebInspector.ContentViewContainer(); - this._contentViewContainer.addEventListener(WebInspector.ContentViewContainer.Event.CurrentContentViewDidChange, this._currentContentViewDidChange, this); - this.element.appendChild(this._contentViewContainer.element); - - WebInspector.ContentView.addEventListener(WebInspector.ContentView.Event.SelectionPathComponentsDidChange, this._contentViewSelectionPathComponentDidChange, this); - WebInspector.ContentView.addEventListener(WebInspector.ContentView.Event.SupplementalRepresentedObjectsDidChange, this._contentViewSupplementalRepresentedObjectsDidChange, this); - WebInspector.ContentView.addEventListener(WebInspector.ContentView.Event.NumberOfSearchResultsDidChange, this._contentViewNumberOfSearchResultsDidChange, this); -}; - -WebInspector.ClusterContentView.StyleClassName = "cluster"; - -WebInspector.ClusterContentView.prototype = { - constructor: WebInspector.ClusterContentView, - - // Public - - get navigationItems() - { - var currentContentView = this._contentViewContainer.currentContentView; - return currentContentView ? currentContentView.navigationItems : []; - }, - - get contentViewContainer() - { - return this._contentViewContainer; - }, - - get supportsSplitContentBrowser() - { - if (this._contentViewContainer.currentContentView) - return this._contentViewContainer.currentContentView.supportsSplitContentBrowser; - return true; - }, - - updateLayout: function() - { - var currentContentView = this._contentViewContainer.currentContentView; - if (currentContentView) - currentContentView.updateLayout(); - }, - - shown: function() - { - this._contentViewContainer.shown(); - }, - - hidden: function() - { - this._contentViewContainer.hidden(); - }, - - closed: function() - { - this._contentViewContainer.closeAllContentViews(); - - WebInspector.ContentView.removeEventListener(WebInspector.ContentView.Event.SelectionPathComponentsDidChange, this._contentViewSelectionPathComponentDidChange, this); - WebInspector.ContentView.removeEventListener(WebInspector.ContentView.Event.SupplementalRepresentedObjectsDidChange, this._contentViewSupplementalRepresentedObjectsDidChange, this); - WebInspector.ContentView.removeEventListener(WebInspector.ContentView.Event.NumberOfSearchResultsDidChange, this._contentViewNumberOfSearchResultsDidChange, this); - }, - - canGoBack: function() - { - return this._contentViewContainer.canGoBack(); - }, - - canGoForward: function() - { - return this._contentViewContainer.canGoForward(); - }, - - goBack: function() - { - this._contentViewContainer.goBack() - }, - - goForward: function() - { - this._contentViewContainer.goForward() - }, - - get selectionPathComponents() - { - if (!this._contentViewContainer.currentContentView) - return []; - return this._contentViewContainer.currentContentView.selectionPathComponents; - }, - - get supplementalRepresentedObjects() - { - if (!this._contentViewContainer.currentContentView) - return []; - return this._contentViewContainer.currentContentView.supplementalRepresentedObjects; - }, - - get handleCopyEvent() - { - var currentContentView = this._contentViewContainer.currentContentView; - return currentContentView && typeof currentContentView.handleCopyEvent === "function" ? currentContentView.handleCopyEvent.bind(currentContentView) : null; - }, - - get supportsSave() - { - var currentContentView = this._contentViewContainer.currentContentView; - return currentContentView && currentContentView.supportsSave; - }, - - get saveData() - { - var currentContentView = this._contentViewContainer.currentContentView; - return currentContentView && currentContentView.saveData || null; - }, - - get supportsSearch() - { - // Always return true so we can intercept the search query to resend it when switching content views. - return true; - }, - - get numberOfSearchResults() - { - var currentContentView = this._contentViewContainer.currentContentView; - if (!currentContentView || !currentContentView.supportsSearch) - return null; - return currentContentView.numberOfSearchResults; - }, - - get hasPerformedSearch() - { - var currentContentView = this._contentViewContainer.currentContentView; - if (!currentContentView || !currentContentView.supportsSearch) - return false; - return currentContentView.hasPerformedSearch; - }, - - set automaticallyRevealFirstSearchResult(reveal) - { - var currentContentView = this._contentViewContainer.currentContentView; - if (!currentContentView || !currentContentView.supportsSearch) - return; - currentContentView.automaticallyRevealFirstSearchResult = reveal; - }, - - performSearch: function(query) - { - this._searchQuery = query; - - var currentContentView = this._contentViewContainer.currentContentView; - if (!currentContentView || !currentContentView.supportsSearch) - return; - currentContentView.performSearch(query); - }, - - searchCleared: function() - { - this._searchQuery = null; - - var currentContentView = this._contentViewContainer.currentContentView; - if (!currentContentView || !currentContentView.supportsSearch) - return; - currentContentView.searchCleared(); - }, - - searchQueryWithSelection: function() - { - var currentContentView = this._contentViewContainer.currentContentView; - if (!currentContentView || !currentContentView.supportsSearch) - return null; - return currentContentView.searchQueryWithSelection(); - }, - - revealPreviousSearchResult: function(changeFocus) - { - var currentContentView = this._contentViewContainer.currentContentView; - if (!currentContentView || !currentContentView.supportsSearch) - return; - currentContentView.revealPreviousSearchResult(changeFocus); - }, - - revealNextSearchResult: function(changeFocus) - { - var currentContentView = this._contentViewContainer.currentContentView; - if (!currentContentView || !currentContentView.supportsSearch) - return; - currentContentView.revealNextSearchResult(changeFocus); - }, - - // Private - - _currentContentViewDidChange: function(event) - { - var currentContentView = this._contentViewContainer.currentContentView; - if (currentContentView && currentContentView.supportsSearch) { - if (this._searchQuery) - currentContentView.performSearch(this._searchQuery); - else - currentContentView.searchCleared(); - } - - this.dispatchEventToListeners(WebInspector.ContentView.Event.SelectionPathComponentsDidChange); - this.dispatchEventToListeners(WebInspector.ContentView.Event.NumberOfSearchResultsDidChange); - this.dispatchEventToListeners(WebInspector.ContentView.Event.NavigationItemsDidChange); - }, - - _contentViewSelectionPathComponentDidChange: function(event) - { - if (event.target !== this._contentViewContainer.currentContentView) - return; - this.dispatchEventToListeners(WebInspector.ContentView.Event.SelectionPathComponentsDidChange); - }, - - _contentViewSupplementalRepresentedObjectsDidChange: function(event) - { - if (event.target !== this._contentViewContainer.currentContentView) - return; - this.dispatchEventToListeners(WebInspector.ContentView.Event.SupplementalRepresentedObjectsDidChange); - }, - - _contentViewNumberOfSearchResultsDidChange: function(event) - { - if (event.target !== this._contentViewContainer.currentContentView) - return; - this.dispatchEventToListeners(WebInspector.ContentView.Event.NumberOfSearchResultsDidChange); - } -}; - -WebInspector.ClusterContentView.prototype.__proto__ = WebInspector.ContentView.prototype; diff --git a/Source/WebInspectorUI/UserInterface/CodeMirrorAdditions.js b/Source/WebInspectorUI/UserInterface/CodeMirrorAdditions.js deleted file mode 100644 index 65260da54..000000000 --- a/Source/WebInspectorUI/UserInterface/CodeMirrorAdditions.js +++ /dev/null @@ -1,541 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -(function () { - // By default CodeMirror defines syntax highlighting styles based on token - // only and shared styles between modes. This limiting and does not match - // what we have done in the Web Inspector. So this modifies the XML, CSS - // and JavaScript modes to supply two styles for each token. One for the - // token and one with the mode name. - - function tokenizeLinkString(stream, state) - { - console.assert(state._linkQuoteCharacter !== undefined); - - // Eat the string until the same quote is found that started the string. - // If this is unquoted, then eat until whitespace or common parse errors. - if (state._linkQuoteCharacter) - stream.eatWhile(new RegExp("[^" + state._linkQuoteCharacter + "]")); - else - stream.eatWhile(/[^\s\u00a0=<>\"\']/); - - // If the stream isn't at the end of line then we found the end quote. - // In the case, change _linkTokenize to parse the end of the link next. - // Otherwise _linkTokenize will stay as-is to parse more of the link. - if (!stream.eol()) - state._linkTokenize = tokenizeEndOfLinkString; - - return "link"; - } - - function tokenizeEndOfLinkString(stream, state) - { - console.assert(state._linkQuoteCharacter !== undefined); - console.assert(state._linkBaseStyle); - - // Eat the quote character to style it with the base style. - if (state._linkQuoteCharacter) - stream.eat(state._linkQuoteCharacter); - - var style = state._linkBaseStyle; - - // Clean up the state. - delete state._linkTokenize; - delete state._linkQuoteCharacter; - delete state._linkBaseStyle; - - return style; - } - - function extendedXMLToken(stream, state) - { - if (state._linkTokenize) { - // Call the link tokenizer instead. - var style = state._linkTokenize(stream, state); - return style && (style + " m-" + this.name); - } - - // Remember the start position so we can rewind if needed. - var startPosition = stream.pos; - var style = this._token(stream, state); - - if (style === "attribute") { - // Look for "href" or "src" attributes. If found then we should - // expect a string later that should get the "link" style instead. - var text = stream.current().toLowerCase(); - if (text === "href" || text === "src") - state._expectLink = true; - else - delete state._expectLink; - } else if (state._expectLink && style === "string") { - delete state._expectLink; - - // This is a link, so setup the state to process it next. - state._linkTokenize = tokenizeLinkString; - state._linkBaseStyle = style; - - // The attribute may or may not be quoted. - var quote = stream.current()[0]; - state._linkQuoteCharacter = quote === "'" || quote === "\"" ? quote : null; - - // Rewind the steam to the start of this token. - stream.pos = startPosition; - - // Eat the open quote of the string so the string style - // will be used for the quote character. - if (state._linkQuoteCharacter) - stream.eat(state._linkQuoteCharacter); - } else if (style) { - // We don't expect other tokens between attribute and string since - // spaces and the equal character are not tokenized. So if we get - // another token before a string then we stop expecting a link. - delete state._expectLink; - } - - return style && (style + " m-" + this.name); - } - - function tokenizeCSSURLString(stream, state) - { - console.assert(state._urlQuoteCharacter); - - // If we are an unquoted url string, return whitespace blocks as a whitespace token (null). - if (state._unquotedURLString && stream.eatSpace()) - return null; - - var ch = null; - var escaped = false; - var reachedEndOfURL = false; - var lastNonWhitespace = stream.pos; - var quote = state._urlQuoteCharacter; - - // Parse characters until the end of the stream/line or a proper end quote character. - while ((ch = stream.next()) != null) { - if (ch == quote && !escaped) { - reachedEndOfURL = true; - break; - } - escaped = !escaped && ch === "\\"; - if (!/[\s\u00a0]/.test(ch)) - lastNonWhitespace = stream.pos; - } - - // If we are an unquoted url string, do not include trailing whitespace, rewind to the last real character. - if (state._unquotedURLString) - stream.pos = lastNonWhitespace; - - // If we have reached the proper the end of the url string, switch to the end tokenizer to reset the state. - if (reachedEndOfURL) { - if (!state._unquotedURLString) - stream.backUp(1); - this._urlTokenize = tokenizeEndOfCSSURLString; - } - - return "link"; - } - - function tokenizeEndOfCSSURLString(stream, state) - { - console.assert(state._urlQuoteCharacter); - console.assert(state._urlBaseStyle); - - // Eat the quote character to style it with the base style. - if (!state._unquotedURLString) - stream.eat(state._urlQuoteCharacter); - - var style = state._urlBaseStyle; - - delete state._urlTokenize; - delete state._urlQuoteCharacter; - delete state._urlBaseStyle; - - return style; - } - - function extendedCSSToken(stream, state) - { - if (state._urlTokenize) { - // Call the link tokenizer instead. - var style = state._urlTokenize(stream, state); - return style && (style + " m-" + (this.alternateName || this.name)); - } - - // Remember the start position so we can rewind if needed. - var startPosition = stream.pos; - var style = this._token(stream, state); - - if (style) { - if (style === "string-2" && stream.current() === "url") { - // If the current text is "url" then we should expect the next string token to be a link. - state._expectLink = true; - } else if (state._expectLink && style === "string") { - // We expected a string and got it. This is a link. Parse it the way we want it. - delete state._expectLink; - - // This is a link, so setup the state to process it next. - state._urlTokenize = tokenizeCSSURLString; - state._urlBaseStyle = style; - - // The url may or may not be quoted. - var quote = stream.current()[0]; - state._urlQuoteCharacter = quote === "'" || quote === "\"" ? quote : ")"; - state._unquotedURLString = state._urlQuoteCharacter === ")"; - - // Rewind the steam to the start of this token. - stream.pos = startPosition; - - // Eat the open quote of the string so the string style - // will be used for the quote character. - if (!state._unquotedURLString) - stream.eat(state._urlQuoteCharacter); - } else if (state._expectLink) { - // We expected a string and didn't get one. Cleanup. - delete state._expectLink; - } - } - - return style && (style + " m-" + (this.alternateName || this.name)); - } - - function extendedToken(stream, state) - { - // CodeMirror moves the original token function to _token when we extended it. - // So call it to get the style that we will add an additional class name to. - var style = this._token(stream, state); - return style && (style + " m-" + (this.alternateName || this.name)); - } - - function extendedCSSRuleStartState(base) - { - // CodeMirror moves the original token function to _startState when we extended it. - // So call it to get the original start state that we will modify. - var state = this._startState(base); - - // Start the stack off like it has already parsed a rule. This causes everything - // after to be parsed as properties in a rule. - state.stack = ["rule"]; - - return state; - } - - CodeMirror.extendMode("css", {token: extendedCSSToken}); - CodeMirror.extendMode("xml", {token: extendedXMLToken}); - CodeMirror.extendMode("javascript", {token: extendedToken}); - - CodeMirror.defineMode("css-rule", CodeMirror.modes.css); - CodeMirror.extendMode("css-rule", {token: extendedCSSToken, startState: extendedCSSRuleStartState, alternateName: "css"}); - - CodeMirror.defineExtension("hasLineClass", function(line, where, className) { - // This matches the arguments to addLineClass and removeLineClass. - var classProperty = (where === "text" ? "textClass" : (where == "background" ? "bgClass" : "wrapClass")); - var lineInfo = this.lineInfo(line); - if (!lineInfo) - return false; - - if (!lineInfo[classProperty]) - return false; - - // Test for the simple case. - if (lineInfo[classProperty] === className) - return true; - - // Do a quick check for the substring. This is faster than a regex, which requires escaping the input first. - var index = lineInfo[classProperty].indexOf(className); - if (index === -1) - return false; - - // Check that it is surrounded by spaces. Add padding spaces first to work with beginning and end of string cases. - var paddedClass = " " + lineInfo[classProperty] + " "; - return paddedClass.indexOf(" " + className + " ", index) !== -1; - }); - - CodeMirror.defineExtension("setUniqueBookmark", function(position, options) { - var marks = this.findMarksAt(position); - for (var i = 0; i < marks.length; ++i) { - if (marks[i].__uniqueBookmark) { - marks[i].clear(); - break; - } - } - - var uniqueBookmark = this.setBookmark(position, options); - uniqueBookmark.__uniqueBookmark = true; - return uniqueBookmark; - }); - - CodeMirror.defineExtension("toggleLineClass", function(line, where, className) { - if (this.hasLineClass(line, where, className)) { - this.removeLineClass(line, where, className); - return false; - } - - this.addLineClass(line, where, className); - return true; - }); - - CodeMirror.defineExtension("alterNumberInRange", function(amount, startPosition, endPosition, updateSelection) { - // We don't try if the range is multiline, pass to another key handler. - if (startPosition.line !== endPosition.line) - return false; - - if (updateSelection) { - // Remember the cursor position/selection. - var selectionStart = this.getCursor("start"); - var selectionEnd = this.getCursor("end"); - } - - var line = this.getLine(startPosition.line); - - var foundPeriod = false; - - var start = NaN; - var end = NaN; - - for (var i = startPosition.ch; i >= 0; --i) { - var character = line.charAt(i); - - if (character === ".") { - if (foundPeriod) - break; - foundPeriod = true; - } else if (character !== "-" && character !== "+" && isNaN(parseInt(character))) { - // Found the end already, just scan backwards. - if (i === startPosition.ch) { - end = i; - continue; - } - - break; - } - - start = i; - } - - if (isNaN(end)) { - for (var i = startPosition.ch + 1; i < line.length; ++i) { - var character = line.charAt(i); - - if (character === ".") { - if (foundPeriod) { - end = i; - break; - } - - foundPeriod = true; - } else if (isNaN(parseInt(character))) { - end = i; - break; - } - - end = i + 1; - } - } - - // No number range found, pass to another key handler. - if (isNaN(start) || isNaN(end)) - return false; - - var number = parseFloat(line.substring(start, end)); - - // Make the new number and constrain it to a precision of 6, this matches numbers the engine returns. - // Use the Number constructor to forget the fixed precision, so 1.100000 will print as 1.1. - var alteredNumber = Number((number + amount).toFixed(6)); - var alteredNumberString = alteredNumber.toString(); - - var from = {line: startPosition.line, ch: start}; - var to = {line: startPosition.line, ch: end}; - - this.replaceRange(alteredNumberString, from, to); - - if (updateSelection) { - var previousLength = to.ch - from.ch; - var newLength = alteredNumberString.length; - - // Fix up the selection so it follows the increase or decrease in the replacement length. - if (previousLength != newLength) { - if (selectionStart.line === from.line && selectionStart.ch > from.ch) - selectionStart.ch += newLength - previousLength; - - if (selectionEnd.line === from.line && selectionEnd.ch > from.ch) - selectionEnd.ch += newLength - previousLength; - } - - this.setSelection(selectionStart, selectionEnd); - } - - return true; - }); - - function alterNumber(amount, codeMirror) - { - function findNumberToken(position) - { - // CodeMirror includes the unit in the number token, so searching for - // number tokens is the best way to get both the number and unit. - var token = codeMirror.getTokenAt(position); - if (token && token.type && /\bnumber\b/.test(token.type)) - return token; - return null; - } - - var position = codeMirror.getCursor("head"); - var token = findNumberToken(position); - - if (!token) { - // If the cursor is at the outside beginning of the token, the previous - // findNumberToken wont find it. So check the next column for a number too. - position.ch += 1; - token = findNumberToken(position); - } - - if (!token) - return CodeMirror.Pass; - - var foundNumber = codeMirror.alterNumberInRange(amount, {ch: token.start, line: position.line}, {ch: token.end, line: position.line}, true); - if (!foundNumber) - return CodeMirror.Pass; - } - - CodeMirror.defineExtension("boundsForRange", function(range) { - var firstCharCoords = this.cursorCoords(range.start); - var lastCharCoords = this.cursorCoords(range.end); - return new WebInspector.Rect(firstCharCoords.left, firstCharCoords.top, lastCharCoords.right - firstCharCoords.left, firstCharCoords.bottom - firstCharCoords.top); - }); - - CodeMirror.defineExtension("createColorMarkers", function(lineNumber, callback) { - var createdMarkers = []; - - var start = typeof lineNumber === "number" ? lineNumber : 0; - var end = typeof lineNumber === "number" ? lineNumber + 1 : this.lineCount(); - - // Matches rgba(0, 0, 0, 0.5), rgb(0, 0, 0), hsl(), hsla(), #fff, #ffffff, white - const colorRegex = /((?:rgb|hsl)a?\([^)]+\)|#[0-9a-fA-F]{6}|#[0-9a-fA-F]{3}|\b\w+\b(?![-.]))/g; - - for (var lineNumber = start; lineNumber < end; ++lineNumber) { - var lineContent = this.getLine(lineNumber); - var match = colorRegex.exec(lineContent); - while (match) { - - // Act as a negative look-behind and disallow the color from being prefixing with certain characters. - if (match.index > 0 && /[-.]/.test(lineContent[match.index - 1])) { - match = colorRegex.exec(lineContent); - continue; - } - - var from = {line: lineNumber, ch: match.index}; - var to = {line: lineNumber, ch: match.index + match[0].length}; - - var foundColorMarker = false; - var markers = this.findMarksAt(to); - for (var j = 0; j < markers.length; ++j) { - if (WebInspector.TextMarker.textMarkerForCodeMirrorTextMarker(markers[j]).type === WebInspector.TextMarker.Type.Color) { - foundColorMarker = true; - break; - } - } - - if (foundColorMarker) { - match = colorRegex.exec(lineContent); - continue; - } - - var colorString = match[0]; - var color = WebInspector.Color.fromString(colorString); - if (!color) { - match = colorRegex.exec(lineContent); - continue; - } - - var marker = this.markText(from, to); - marker = new WebInspector.TextMarker(marker, WebInspector.TextMarker.Type.Color); - - createdMarkers.push(marker); - - if (callback) - callback(marker, color, colorString); - - match = colorRegex.exec(lineContent); - } - } - - return createdMarkers; - }); - - function ignoreKey(codeMirror) - { - // Do nothing to ignore the key. - } - - CodeMirror.keyMap["default"] = { - "Alt-Up": alterNumber.bind(null, 1), - "Ctrl-Alt-Up": alterNumber.bind(null, 0.1), - "Shift-Alt-Up": alterNumber.bind(null, 10), - "Alt-PageUp": alterNumber.bind(null, 10), - "Shift-Alt-PageUp": alterNumber.bind(null, 100), - "Alt-Down": alterNumber.bind(null, -1), - "Ctrl-Alt-Down": alterNumber.bind(null, -0.1), - "Shift-Alt-Down": alterNumber.bind(null, -10), - "Alt-PageDown": alterNumber.bind(null, -10), - "Shift-Alt-PageDown": alterNumber.bind(null, -100), - "Cmd-/": "toggleComment", - "Shift-Tab": ignoreKey, - fallthrough: "macDefault" - }; - - // Register some extra MIME-types for CodeMirror. These are in addition to the - // ones CodeMirror already registers, like text/html, text/javascript, etc. - const extraXMLTypes = ["text/xml", "text/xsl"]; - extraXMLTypes.forEach(function(type) { - CodeMirror.defineMIME(type, "xml"); - }); - - const extraHTMLTypes = ["application/xhtml+xml", "image/svg+xml"]; - extraHTMLTypes.forEach(function(type) { - CodeMirror.defineMIME(type, "htmlmixed"); - }); - - const extraJavaScriptTypes = ["text/ecmascript", "application/javascript", "application/ecmascript", "application/x-javascript", - "text/x-javascript", "text/javascript1.1", "text/javascript1.2", "text/javascript1.3", "text/jscript", "text/livescript"]; - extraJavaScriptTypes.forEach(function(type) { - CodeMirror.defineMIME(type, "javascript"); - }); - - const extraJSONTypes = ["application/x-json", "text/x-json"]; - extraJSONTypes.forEach(function(type) { - CodeMirror.defineMIME(type, {name: "javascript", json: true}); - }); - -})(); - -WebInspector.compareCodeMirrorPositions = function(a, b) -{ - var lineCompare = a.line - b.line; - if (lineCompare !== 0) - return lineCompare; - - var aColumn = "ch" in a ? a.ch : Number.MAX_VALUE; - var bColumn = "ch" in b ? b.ch : Number.MAX_VALUE; - return aColumn - bColumn; -}; diff --git a/Source/WebInspectorUI/UserInterface/CodeMirrorColorEditingController.js b/Source/WebInspectorUI/UserInterface/CodeMirrorColorEditingController.js deleted file mode 100644 index bd242a0a7..000000000 --- a/Source/WebInspectorUI/UserInterface/CodeMirrorColorEditingController.js +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.CodeMirrorColorEditingController = function(codeMirror, marker) -{ - WebInspector.Object.call(this); - - this._codeMirror = codeMirror; - this._marker = marker; - this._delegate = null; - - this._range = marker.range; - this._color = WebInspector.Color.fromString(this.text); - - this._keyboardShortcutEsc = new WebInspector.KeyboardShortcut(null, WebInspector.KeyboardShortcut.Key.Escape); -} - -WebInspector.CodeMirrorColorEditingController.prototype = { - constructor: WebInspector.CodeMirrorColorEditingController, - __proto__: WebInspector.Object.prototype, - - // Public - - get marker() - { - return this._marker; - }, - - get range() - { - return this._range; - }, - - get color() - { - return this._color; - }, - - set color(color) - { - this.text = color.toString(); - this._color = color; - }, - - get delegate() - { - return this._delegate; - }, - - set delegate(delegate) - { - this._delegate = delegate; - }, - - get text() - { - var from = {line: this._range.startLine, ch: this._range.startColumn}; - var to = {line: this._range.endLine, ch: this._range.endColumn}; - return this._codeMirror.getRange(from, to); - }, - - set text(text) - { - var from = {line: this._range.startLine, ch: this._range.startColumn}; - var to = {line: this._range.endLine, ch: this._range.endColumn}; - this._codeMirror.replaceRange(text, from, to); - - var lines = text.split("\n"); - var endLine = this._range.startLine + lines.length - 1; - var endColumn = lines.length > 1 ? lines.lastValue.length : this._range.startColumn + text.length; - this._range = new WebInspector.TextRange(this._range.startLine, this._range.startColumn, endLine, endColumn); - }, - - presentHoverMenu: function() - { - this._hoverMenu = new WebInspector.HoverMenu(this); - this._hoverMenu.element.classList.add("color"); - this._bounds = this._marker.bounds; - this._hoverMenu.present(this._bounds); - }, - - dismissHoverMenu: function() - { - this._hoverMenu.dismiss(); - }, - - // Protected - - handleEvent: function(event) - { - if (!this._keyboardShortcutEsc.matchesEvent(event) || !this._popover.visible) - return; - - this.color = this._originalColor; - this._popover.dismiss(); - - event.stopPropagation(); - event.preventDefault(); - }, - - hoverMenuButtonWasPressed: function(hoverMenu) - { - var colorPicker = new WebInspector.ColorPicker; - colorPicker.addEventListener(WebInspector.ColorPicker.Event.ColorChanged, this._colorPickerColorChanged, this); - - this._popover = new WebInspector.Popover(this); - this._popover.content = colorPicker.element; - this._popover.present(this._bounds.pad(2), [WebInspector.RectEdge.MAX_Y, WebInspector.RectEdge.MAX_X]); - - window.addEventListener("keydown", this, true); - - colorPicker.color = this._color; - - hoverMenu.dismiss(); - - if (this._delegate && typeof this._delegate.colorEditingControllerDidStartEditing === "function") - this._delegate.colorEditingControllerDidStartEditing(this); - - this._originalColor = this._color.copy(); - }, - - didDismissPopover: function(popover) - { - delete this._popover; - delete this._originalColor; - - window.removeEventListener("keydown", this, true); - - if (this._delegate && typeof this._delegate.colorEditingControllerDidFinishEditing === "function") - this._delegate.colorEditingControllerDidFinishEditing(this); - }, - - // Private - - _colorPickerColorChanged: function(event) - { - this.color = event.target.color; - } -} diff --git a/Source/WebInspectorUI/UserInterface/CodeMirrorCompletionController.css b/Source/WebInspectorUI/UserInterface/CodeMirrorCompletionController.css deleted file mode 100644 index 2f27d1c6e..000000000 --- a/Source/WebInspectorUI/UserInterface/CodeMirrorCompletionController.css +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.CodeMirror .CodeMirror-lines .completion-hint { - opacity: 0.4; -} diff --git a/Source/WebInspectorUI/UserInterface/CodeMirrorCompletionController.js b/Source/WebInspectorUI/UserInterface/CodeMirrorCompletionController.js deleted file mode 100644 index c27e16b5c..000000000 --- a/Source/WebInspectorUI/UserInterface/CodeMirrorCompletionController.js +++ /dev/null @@ -1,824 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.CodeMirrorCompletionController = function(codeMirror, delegate, stopCharactersRegex) -{ - WebInspector.Object.call(this); - - console.assert(codeMirror); - - this._codeMirror = codeMirror; - this._stopCharactersRegex = stopCharactersRegex || null; - this._delegate = delegate || null; - - this._startOffset = NaN; - this._endOffset = NaN; - this._lineNumber = NaN; - this._prefix = ""; - this._completions = []; - this._extendedCompletionProviders = {}; - - this._suggestionsView = new WebInspector.CompletionSuggestionsView(this); - - this._keyMap = { - "Up": this._handleUpKey.bind(this), - "Down": this._handleDownKey.bind(this), - "Right": this._handleRightOrEnterKey.bind(this), - "Esc": this._handleEscapeKey.bind(this), - "Enter": this._handleRightOrEnterKey.bind(this), - "Tab": this._handleTabKey.bind(this), - "Cmd-A": this._handleHideKey.bind(this), - "Cmd-Z": this._handleHideKey.bind(this), - "Shift-Cmd-Z": this._handleHideKey.bind(this), - "Cmd-Y": this._handleHideKey.bind(this) - }; - - this._handleChangeListener = this._handleChange.bind(this); - this._handleCursorActivityListener = this._handleCursorActivity.bind(this); - this._handleHideActionListener = this._handleHideAction.bind(this); - - this._codeMirror.addKeyMap(this._keyMap); - - this._codeMirror.on("change", this._handleChangeListener); - this._codeMirror.on("cursorActivity", this._handleCursorActivityListener); - this._codeMirror.on("blur", this._handleHideActionListener); - this._codeMirror.on("scroll", this._handleHideActionListener); -}; - -WebInspector.CodeMirrorCompletionController.GenericStopCharactersRegex = /[\s=:;,]/; -WebInspector.CodeMirrorCompletionController.DefaultStopCharactersRegexModeMap = {"css": /[\s:;,{}()]/, "javascript": /[\s=:;,!+\-*/%&|^~?<>.{}()[\]]/}; -WebInspector.CodeMirrorCompletionController.BaseExpressionStopCharactersRegexModeMap = {"javascript": /[\s=:;,!+\-*/%&|^~?<>]/}; -WebInspector.CodeMirrorCompletionController.OpenBracketCharactersRegex = /[({[]/; -WebInspector.CodeMirrorCompletionController.CloseBracketCharactersRegex = /[)}\]]/; -WebInspector.CodeMirrorCompletionController.MatchingBrackets = {"{": "}", "(": ")", "[": "]", "}": "{", ")": "(", "]": "["}; -WebInspector.CodeMirrorCompletionController.CompletionHintStyleClassName = "completion-hint"; -WebInspector.CodeMirrorCompletionController.CompletionsHiddenDelay = 250; -WebInspector.CodeMirrorCompletionController.CompletionTypingDelay = 250; -WebInspector.CodeMirrorCompletionController.CompletionOrigin = "+completion"; -WebInspector.CodeMirrorCompletionController.DeleteCompletionOrigin = "+delete-completion"; - -WebInspector.CodeMirrorCompletionController.prototype = { - constructor: WebInspector.CodeMirrorCompletionController, - - // Public - - get delegate() - { - return this._delegate; - }, - - addExtendedCompletionProvider: function(modeName, provider) - { - this._extendedCompletionProviders[modeName] = provider; - }, - - updateCompletions: function(completions, implicitSuffix) - { - if (isNaN(this._startOffset) || isNaN(this._endOffset) || isNaN(this._lineNumber)) - return; - - if (!completions || !completions.length) { - this.hideCompletions(); - return; - } - - this._completions = completions; - - if (typeof implicitSuffix === "string") - this._implicitSuffix = implicitSuffix; - - var from = {line: this._lineNumber, ch: this._startOffset}; - var to = {line: this._lineNumber, ch: this._endOffset}; - - var firstCharCoords = this._codeMirror.cursorCoords(from); - var lastCharCoords = this._codeMirror.cursorCoords(to); - var bounds = new WebInspector.Rect(firstCharCoords.left, firstCharCoords.top, lastCharCoords.right - firstCharCoords.left, firstCharCoords.bottom - firstCharCoords.top); - - // Try to restore the previous selected index, otherwise just select the first. - var index = this._currentCompletion ? completions.indexOf(this._currentCompletion) : 0; - if (index === -1) - index = 0; - - if (this._forced || completions.length > 1 || completions[index] !== this._prefix) { - // Update and show the suggestion list. - this._suggestionsView.update(completions, index); - this._suggestionsView.show(bounds); - } else if (this._implicitSuffix) { - // The prefix and the completion exactly match, but there is an implicit suffix. - // Just hide the suggestion list and keep the completion hint for the implicit suffix. - this._suggestionsView.hide(); - } else { - // The prefix and the completion exactly match, hide the completions. Return early so - // the completion hint isn't updated. - this.hideCompletions(); - return; - } - - this._applyCompletionHint(completions[index]); - }, - - isCompletionChange: function(change) - { - return this._ignoreChange || change.origin === WebInspector.CodeMirrorCompletionController.CompletionOrigin || change.origin === WebInspector.CodeMirrorCompletionController.DeleteCompletionOrigin; - }, - - isShowingCompletions: function() - { - return this._suggestionsView.visible || (this._completionHintMarker && this._completionHintMarker.find()); - }, - - isHandlingClickEvent: function() - { - return this._suggestionsView.isHandlingClickEvent(); - }, - - hideCompletions: function() - { - this._suggestionsView.hide(); - - this._removeCompletionHint(); - - this._startOffset = NaN; - this._endOffset = NaN; - this._lineNumber = NaN; - this._prefix = ""; - this._completions = []; - this._implicitSuffix = ""; - this._forced = false; - - if (this._completionDelayTimeout) { - clearTimeout(this._completionDelayTimeout); - delete this._completionDelayTimeout; - } - - delete this._currentCompletion; - delete this._ignoreNextCursorActivity; - }, - - close: function() - { - this._codeMirror.removeKeyMap(this._keyMap); - - this._codeMirror.off("change", this._handleChangeListener); - this._codeMirror.off("cursorActivity", this._handleCursorActivityListener); - this._codeMirror.off("blur", this._handleHideActionListener); - this._codeMirror.off("scroll", this._handleHideActionListener); - }, - - // Protected - - completionSuggestionsSelectedCompletion: function(suggestionsView, completionText) - { - this._applyCompletionHint(completionText); - }, - - completionSuggestionsClickedCompletion: function(suggestionsView, completionText) - { - // The clicked suggestion causes the editor to loose focus. Restore it so the user can keep typing. - this._codeMirror.focus(); - - this._applyCompletionHint(completionText); - this._commitCompletionHint(); - }, - - // Private - - get _currentReplacementText() - { - return this._currentCompletion + this._implicitSuffix; - }, - - _hasPendingCompletion: function() - { - return !isNaN(this._startOffset) && !isNaN(this._endOffset) && !isNaN(this._lineNumber); - }, - - _notifyCompletionsHiddenSoon: function() - { - function notify() - { - if (this._completionHintMarker) - return; - - if (this._delegate && typeof this._delegate.completionControllerCompletionsHidden === "function") - this._delegate.completionControllerCompletionsHidden(this); - } - - if (this._notifyCompletionsHiddenIfNeededTimeout) - clearTimeout(this._notifyCompletionsHiddenIfNeededTimeout); - this._notifyCompletionsHiddenIfNeededTimeout = setTimeout(notify.bind(this), WebInspector.CodeMirrorCompletionController.CompletionsHiddenDelay); - }, - - _applyCompletionHint: function(completionText) - { - console.assert(completionText); - if (!completionText) - return; - - function update() - { - this._currentCompletion = completionText; - - this._removeCompletionHint(true, true); - - var replacementText = this._currentReplacementText; - - var from = {line: this._lineNumber, ch: this._startOffset}; - var cursor = {line: this._lineNumber, ch: this._endOffset}; - var to = {line: this._lineNumber, ch: this._startOffset + replacementText.length}; - - this._codeMirror.replaceRange(replacementText, from, cursor, WebInspector.CodeMirrorCompletionController.CompletionOrigin); - this._removeLastChangeFromHistory(); - - this._codeMirror.setCursor(cursor); - - if (cursor.ch !== to.ch) - this._completionHintMarker = this._codeMirror.markText(cursor, to, {className: WebInspector.CodeMirrorCompletionController.CompletionHintStyleClassName}); - } - - this._ignoreChange = true; - this._ignoreNextCursorActivity = true; - - this._codeMirror.operation(update.bind(this)); - - delete this._ignoreChange; - }, - - _commitCompletionHint: function() - { - function update() - { - this._removeCompletionHint(true, true); - - var replacementText = this._currentReplacementText; - - var from = {line: this._lineNumber, ch: this._startOffset}; - var cursor = {line: this._lineNumber, ch: this._endOffset}; - var to = {line: this._lineNumber, ch: this._startOffset + replacementText.length}; - - var lastChar = this._currentCompletion.charAt(this._currentCompletion.length - 1); - var isClosing = ")]}".indexOf(lastChar); - if (isClosing !== -1) - to.ch -= 1 + this._implicitSuffix.length; - - this._codeMirror.replaceRange(replacementText, from, cursor, WebInspector.CodeMirrorCompletionController.CompletionOrigin); - - // Don't call _removeLastChangeFromHistory here to allow the committed completion to be undone. - - this._codeMirror.setCursor(to); - - this.hideCompletions(); - } - - this._ignoreChange = true; - this._ignoreNextCursorActivity = true; - - this._codeMirror.operation(update.bind(this)); - - delete this._ignoreChange; - }, - - _removeLastChangeFromHistory: function() - { - var history = this._codeMirror.getHistory(); - - // We don't expect a undone history. But if there is one clear it. If could lead to undefined behavior. - console.assert(!history.undone.length); - history.undone = []; - - // Pop the last item from the done history. - console.assert(history.done.length); - history.done.pop(); - - this._codeMirror.setHistory(history); - }, - - _removeCompletionHint: function(nonatomic, dontRestorePrefix) - { - if (!this._completionHintMarker) - return; - - this._notifyCompletionsHiddenSoon(); - - function update() - { - var range = this._completionHintMarker.find(); - if (range) { - this._completionHintMarker.clear(); - - this._codeMirror.replaceRange("", range.from, range.to, WebInspector.CodeMirrorCompletionController.DeleteCompletionOrigin); - this._removeLastChangeFromHistory(); - } - - this._completionHintMarker = null; - - if (dontRestorePrefix) - return; - - console.assert(!isNaN(this._startOffset)); - console.assert(!isNaN(this._endOffset)); - console.assert(!isNaN(this._lineNumber)); - - var from = {line: this._lineNumber, ch: this._startOffset}; - var to = {line: this._lineNumber, ch: this._endOffset}; - - this._codeMirror.replaceRange(this._prefix, from, to, WebInspector.CodeMirrorCompletionController.DeleteCompletionOrigin); - this._removeLastChangeFromHistory(); - } - - if (nonatomic) { - update.call(this); - return; - } - - this._ignoreChange = true; - - this._codeMirror.operation(update.bind(this)); - - delete this._ignoreChange; - }, - - _scanStringForExpression: function(modeName, string, startOffset, direction, allowMiddleAndEmpty, includeStopCharacter, ignoreInitialUnmatchedOpenBracket, stopCharactersRegex) - { - console.assert(direction === -1 || direction === 1); - - var stopCharactersRegex = stopCharactersRegex || this._stopCharactersRegex || WebInspector.CodeMirrorCompletionController.DefaultStopCharactersRegexModeMap[modeName] || WebInspector.CodeMirrorCompletionController.GenericStopCharactersRegex; - - function isStopCharacter(character) - { - return stopCharactersRegex.test(character); - } - - function isOpenBracketCharacter(character) - { - return WebInspector.CodeMirrorCompletionController.OpenBracketCharactersRegex.test(character); - } - - function isCloseBracketCharacter(character) - { - return WebInspector.CodeMirrorCompletionController.CloseBracketCharactersRegex.test(character); - } - - function matchingBracketCharacter(character) - { - return WebInspector.CodeMirrorCompletionController.MatchingBrackets[character]; - } - - var endOffset = Math.min(startOffset, string.length); - - var endOfLineOrWord = endOffset === string.length || isStopCharacter(string.charAt(endOffset)); - - if (!endOfLineOrWord && !allowMiddleAndEmpty) - return null; - - var bracketStack = []; - var bracketOffsetStack = []; - var lastCloseBracketOffset = NaN; - - var startOffset = endOffset; - var firstOffset = endOffset + direction; - for (var i = firstOffset; direction > 0 ? i < string.length : i >= 0; i += direction) { - var character = string.charAt(i); - - // Ignore stop characters when we are inside brackets. - if (isStopCharacter(character) && !bracketStack.length) - break; - - if (isCloseBracketCharacter(character)) { - bracketStack.push(character); - bracketOffsetStack.push(i); - } else if (isOpenBracketCharacter(character)) { - if ((!ignoreInitialUnmatchedOpenBracket || i !== firstOffset) && (!bracketStack.length || matchingBracketCharacter(character) !== bracketStack.lastValue)) - break; - - bracketOffsetStack.pop(); - bracketStack.pop(); - } - - startOffset = i + (direction > 0 ? 1 : 0); - } - - if (bracketOffsetStack.length) - startOffset = bracketOffsetStack.pop() + 1; - - if (includeStopCharacter && startOffset > 0 && startOffset < string.length) - startOffset += direction; - - if (direction > 0) { - var tempEndOffset = endOffset; - endOffset = startOffset; - startOffset = tempEndOffset; - } - - return {string: string.substring(startOffset, endOffset), startOffset: startOffset, endOffset: endOffset}; - }, - - _completeAtCurrentPosition: function(force) - { - if (this._codeMirror.somethingSelected()) { - this.hideCompletions(); - return; - } - - if (this._completionDelayTimeout) { - clearTimeout(this._completionDelayTimeout); - delete this._completionDelayTimeout; - } - - this._removeCompletionHint(true, true); - - var cursor = this._codeMirror.getCursor(); - var token = this._codeMirror.getTokenAt(cursor); - - // Don't try to complete inside comments. - if (token.type && /\bcomment\b/.test(token.type)) { - this.hideCompletions(); - return; - } - - var mode = this._codeMirror.getMode(); - var innerMode = CodeMirror.innerMode(mode, token.state).mode; - var modeName = innerMode.alternateName || innerMode.name; - - var lineNumber = cursor.line; - var lineString = this._codeMirror.getLine(lineNumber); - - var backwardScanResult = this._scanStringForExpression(modeName, lineString, cursor.ch, -1, force); - if (!backwardScanResult) { - this.hideCompletions(); - return; - } - - var forwardScanResult = this._scanStringForExpression(modeName, lineString, cursor.ch, 1, true, true); - var suffix = forwardScanResult.string; - - this._ignoreNextCursorActivity = true; - - this._startOffset = backwardScanResult.startOffset; - this._endOffset = backwardScanResult.endOffset; - this._lineNumber = lineNumber; - this._prefix = backwardScanResult.string; - this._completions = []; - this._implicitSuffix = ""; - this._forced = force; - - var baseExpressionStopCharactersRegex = WebInspector.CodeMirrorCompletionController.BaseExpressionStopCharactersRegexModeMap[modeName]; - if (baseExpressionStopCharactersRegex) - var baseScanResult = this._scanStringForExpression(modeName, lineString, this._startOffset, -1, true, false, true, baseExpressionStopCharactersRegex); - - if (!force && !backwardScanResult.string && (!baseScanResult || !baseScanResult.string)) { - this.hideCompletions(); - return; - } - - var defaultCompletions = []; - - switch (modeName) { - case "css": - defaultCompletions = this._generateCSSCompletions(token, baseScanResult ? baseScanResult.string : null, suffix); - break; - case "javascript": - defaultCompletions = this._generateJavaScriptCompletions(token, baseScanResult ? baseScanResult.string : null, suffix); - break; - } - - var extendedCompletionsProvider = this._extendedCompletionProviders[modeName]; - if (extendedCompletionsProvider) { - extendedCompletionsProvider.completionControllerCompletionsNeeded(this, defaultCompletions, baseScanResult ? baseScanResult.string : null, this._prefix, suffix, force); - return; - } - - if (this._delegate && typeof this._delegate.completionControllerCompletionsNeeded === "function") - this._delegate.completionControllerCompletionsNeeded(this, this._prefix, defaultCompletions, baseScanResult ? baseScanResult.string : null, suffix, force); - else - this.updateCompletions(defaultCompletions); - }, - - _generateCSSCompletions: function(mainToken, base, suffix) - { - // We only support completion inside CSS rules. - if (!mainToken.state || !mainToken.state.stack || !mainToken.state.stack.contains("rule")) - return []; - - var token = mainToken; - var lineNumber = this._lineNumber; - - // Scan backwards looking for the current property. - while (token.state.stack.lastValue === "propertyValue") { - // Found the beginning of the line. Go to the previous line. - if (!token.start) { - --lineNumber; - - // No more lines, stop. - if (lineNumber < 0) - break; - } - - // Get the previous token. - token = this._codeMirror.getTokenAt({line: lineNumber, ch: token.start ? token.start : Number.MAX_VALUE}); - } - - // If we have a property token and it's not the main token, then we are working on - // the value for that property and should complete allowed values. - if (mainToken !== token && token.type && /\bproperty\b/.test(token.type)) { - var propertyName = token.string; - - // If there is a suffix and it isn't a semicolon, then we should use a space since - // the user is editing in the middle. - this._implicitSuffix = suffix && suffix !== ";" ? " " : ";"; - - // Don't use an implicit suffix if it would be the same as the existing suffix. - if (this._implicitSuffix === suffix) - this._implicitSuffix = ""; - - return WebInspector.CSSKeywordCompletions.forProperty(propertyName).startsWith(this._prefix); - } - - this._implicitSuffix = suffix !== ":" ? ": " : ""; - - // Complete property names. - return WebInspector.CSSCompletions.cssNameCompletions.startsWith(this._prefix); - }, - - _generateJavaScriptCompletions: function(mainToken, base, suffix) - { - // If there is a base expression then we should not attempt to match any keywords or variables. - // Allow only open bracket characters at the end of the base, otherwise leave completions with - // a base up to the delegate to figure out. - if (base && !/[({[]$/.test(base)) - return []; - - var matchingWords = []; - - const prefix = this._prefix; - - const declaringVariable = mainToken.state.lexical.type === "vardef"; - const insideSwitch = mainToken.state.lexical.prev ? mainToken.state.lexical.prev.info === "switch" : false; - const insideBlock = mainToken.state.lexical.prev ? mainToken.state.lexical.prev.type === "}" : false; - const insideParenthesis = mainToken.state.lexical.type === ")"; - const insideBrackets = mainToken.state.lexical.type === "]"; - - const allKeywords = ["break", "case", "catch", "const", "continue", "debugger", "default", "delete", "do", "else", "false", "finally", "for", "function", "if", "in", - "Infinity", "instanceof", "NaN", "new", "null", "return", "switch", "this", "throw", "true", "try", "typeof", "undefined", "var", "void", "while", "with"]; - const valueKeywords = ["false", "Infinity", "NaN", "null", "this", "true", "undefined"]; - - const allowedKeywordsInsideBlocks = allKeywords.keySet(); - const allowedKeywordsWhenDeclaringVariable = valueKeywords.keySet(); - const allowedKeywordsInsideParenthesis = valueKeywords.concat(["function"]).keySet(); - const allowedKeywordsInsideBrackets = allowedKeywordsInsideParenthesis; - const allowedKeywordsOnlyInsideSwitch = ["case", "default"].keySet(); - - function matchKeywords(keywords) - { - matchingWords = matchingWords.concat(keywords.filter(function(word) { - if (!insideSwitch && word in allowedKeywordsOnlyInsideSwitch) - return false; - if (insideBlock && !(word in allowedKeywordsInsideBlocks)) - return false; - if (insideBrackets && !(word in allowedKeywordsInsideBrackets)) - return false; - if (insideParenthesis && !(word in allowedKeywordsInsideParenthesis)) - return false; - if (declaringVariable && !(word in allowedKeywordsWhenDeclaringVariable)) - return false; - return word.startsWith(prefix); - })); - } - - function matchVariables() - { - function filterVariables(variables) - { - for (var variable = variables; variable; variable = variable.next) { - // Don't match the variable if this token is in a variable declaration. - // Otherwise the currently typed text will always match and that isn't useful. - if (declaringVariable && variable.name === prefix) - continue; - - if (variable.name.startsWith(prefix) && !matchingWords.contains(variable.name)) - matchingWords.push(variable.name); - } - } - - var context = mainToken.state.context; - while (context) { - filterVariables(context.vars); - context = context.prev; - } - - filterVariables(mainToken.state.globalVars); - } - - switch (suffix.substring(0, 1)) { - case "": - case " ": - matchVariables(); - matchKeywords(allKeywords); - break; - - case ".": - case "[": - matchVariables(); - matchKeywords(["false", "Infinity", "NaN", "this", "true"]); - break; - - case "(": - matchVariables(); - matchKeywords(["catch", "else", "for", "function", "if", "return", "switch", "throw", "while", "with"]); - break; - - case "{": - matchKeywords(["do", "else", "finally", "return", "try"]); - break; - - case ":": - if (insideSwitch) - matchKeywords(["case", "default"]); - break; - - case ";": - matchVariables(); - matchKeywords(valueKeywords); - matchKeywords(["break", "continue", "debugger", "return", "void"]); - break; - } - - return matchingWords; - }, - - _handleUpKey: function(codeMirror) - { - if (!this._hasPendingCompletion()) - return CodeMirror.Pass; - - if (!this.isShowingCompletions()) - return; - - this._suggestionsView.selectPrevious(); - }, - - _handleDownKey: function(codeMirror) - { - if (!this._hasPendingCompletion()) - return CodeMirror.Pass; - - if (!this.isShowingCompletions()) - return; - - this._suggestionsView.selectNext(); - }, - - _handleRightOrEnterKey: function(codeMirror) - { - if (!this._hasPendingCompletion()) - return CodeMirror.Pass; - - if (!this.isShowingCompletions()) - return; - - this._commitCompletionHint(); - }, - - _handleEscapeKey: function(codeMirror) - { - var delegateImplementsShouldAllowEscapeCompletion = this._delegate && typeof this._delegate.completionControllerShouldAllowEscapeCompletion === "function"; - if (this._hasPendingCompletion()) - this.hideCompletions(); - else if (this._codeMirror.getOption("readOnly")) - return CodeMirror.Pass; - else if (!delegateImplementsShouldAllowEscapeCompletion || this._delegate.completionControllerShouldAllowEscapeCompletion(this)) - this._completeAtCurrentPosition(true); - else - return CodeMirror.Pass; - }, - - _handleTabKey: function(codeMirror) - { - if (!this._hasPendingCompletion()) - return CodeMirror.Pass; - - if (!this.isShowingCompletions()) - return; - - console.assert(this._completions.length); - if (!this._completions.length) - return; - - console.assert(this._currentCompletion); - if (!this._currentCompletion) - return; - - // Commit the current completion if there is only one suggestion. - if (this._completions.length === 1) { - this._commitCompletionHint(); - return; - } - - var prefixLength = this._prefix.length; - - var commonPrefix = this._completions[0]; - for (var i = 1; i < this._completions.length; ++i) { - var completion = this._completions[i]; - var lastIndex = Math.min(commonPrefix.length, completion.length); - for (var j = prefixLength; j < lastIndex; ++j) { - if (commonPrefix[j] !== completion[j]) { - commonPrefix = commonPrefix.substr(0, j); - break; - } - } - } - - // Commit the current completion if there is no common prefix that is longer. - if (commonPrefix === this._prefix) { - this._commitCompletionHint(); - return; - } - - // Set the prefix to the common prefix so _applyCompletionHint will insert the - // common prefix as commited text. Adjust _endOffset to match the new prefix. - this._prefix = commonPrefix; - this._endOffset = this._startOffset + commonPrefix.length; - - this._applyCompletionHint(this._currentCompletion); - }, - - _handleChange: function(codeMirror, change) - { - if (this.isCompletionChange(change)) - return; - - this._ignoreNextCursorActivity = true; - - if (!change.origin || change.origin.charAt(0) !== "+") { - this.hideCompletions(); - return; - } - - // Only complete on delete if we are showing completions already. - if (change.origin === "+delete" && !this._hasPendingCompletion()) - return; - - if (this._completionDelayTimeout) { - clearTimeout(this._completionDelayTimeout); - delete this._completionDelayTimeout; - } - - if (this._hasPendingCompletion()) - this._completeAtCurrentPosition(false); - else - this._completionDelayTimeout = setTimeout(this._completeAtCurrentPosition.bind(this, false), WebInspector.CodeMirrorCompletionController.CompletionTypingDelay); - }, - - _handleCursorActivity: function(codeMirror) - { - if (this._ignoreChange) - return; - - if (this._ignoreNextCursorActivity) { - delete this._ignoreNextCursorActivity; - return; - } - - this.hideCompletions(); - }, - - _handleHideKey: function(codeMirror) - { - this.hideCompletions(); - - return CodeMirror.Pass; - }, - - _handleHideAction: function(codeMirror) - { - // Clicking a suggestion causes the editor to blur. We don't want to hide completions in this case. - if (this.isHandlingClickEvent()) - return; - - this.hideCompletions(); - } -}; - -WebInspector.CodeMirrorCompletionController.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/CodeMirrorDragToAlterNumberController.css b/Source/WebInspectorUI/UserInterface/CodeMirrorDragToAlterNumberController.css deleted file mode 100644 index d67d6b361..000000000 --- a/Source/WebInspectorUI/UserInterface/CodeMirrorDragToAlterNumberController.css +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.CodeMirror.drag-to-adjust .CodeMirror-lines { - cursor: col-resize; -} diff --git a/Source/WebInspectorUI/UserInterface/CodeMirrorDragToAlterNumberController.js b/Source/WebInspectorUI/UserInterface/CodeMirrorDragToAlterNumberController.js deleted file mode 100644 index 52a0095fa..000000000 --- a/Source/WebInspectorUI/UserInterface/CodeMirrorDragToAlterNumberController.js +++ /dev/null @@ -1,234 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.CodeMirrorDragToAlterNumberController = function(codeMirror) -{ - this._codeMirror = codeMirror; - this._active = false; - this._dragging = false; - this._enabled = false; - this._tracksMouseClickAndDrag = false; -}; - -WebInspector.CodeMirrorDragToAlterNumberController.StyleClassName = "drag-to-adjust"; - -WebInspector.CodeMirrorDragToAlterNumberController.prototype = { - constructor: WebInspector.CodeMirrorDragToAlterNumberController, - - // Public - - set enabled(enabled) - { - if (this._enabled === enabled) - return; - - this._element = this._codeMirror.getWrapperElement(); - - if (enabled) { - this._element.addEventListener("mouseenter", this); - this._element.addEventListener("mouseleave", this); - } else { - this._element.removeEventListener("mouseenter", this); - this._element.removeEventListener("mouseleave", this); - } - }, - - // Protected - - handleEvent: function(event) - { - switch(event.type) { - case "mouseenter": - if (!this._dragging) - this._setActive(true); - break; - case "mouseleave": - if (!this._dragging) - this._setActive(false); - break; - case "mousemove": - if (this._dragging) - this._mouseWasDragged(event); - else - this._mouseMoved(event); - break; - case "mousedown": - this._mouseWasPressed(event); - break; - case "mouseup": - this._mouseWasReleased(event); - break; - case "contextmenu": - event.preventDefault(); - break; - } - }, - - // Private - - _setActive: function(active) - { - if (this._active === active || this._codeMirror.getOption("readOnly")) - return; - - if (active) { - WebInspector.notifications.addEventListener(WebInspector.Notification.GlobalModifierKeysDidChange, this._modifiersDidChange, this); - this._element.addEventListener("mousemove", this); - } else { - WebInspector.notifications.removeEventListener(WebInspector.Notification.GlobalModifierKeysDidChange, this._modifiersDidChange, this); - this._element.removeEventListener("mousemove", this); - this._hoveredTokenInfo = null; - this._setTracksMouseClickAndDrag(false); - } - - this._active = active; - }, - - _setDragging: function(dragging) - { - if (this._dragging === dragging) - return; - - console.assert(window.event); - if (dragging) - WebInspector.elementDragStart(this._element, this, this, window.event, "col-resize", window); - else - WebInspector.elementDragEnd(window.event); - - this._dragging = dragging; - }, - - _setTracksMouseClickAndDrag: function(tracksMouseClickAndDrag) - { - if (this._tracksMouseClickAndDrag === tracksMouseClickAndDrag) - return; - - if (tracksMouseClickAndDrag) { - this._element.classList.add(WebInspector.CodeMirrorDragToAlterNumberController.StyleClassName); - window.addEventListener("mousedown", this, true); - window.addEventListener("contextmenu", this, true); - } else { - this._element.classList.remove(WebInspector.CodeMirrorDragToAlterNumberController.StyleClassName); - window.removeEventListener("mousedown", this, true); - window.removeEventListener("contextmenu", this, true); - this._setDragging(false); - } - - this._tracksMouseClickAndDrag = tracksMouseClickAndDrag; - }, - - _modifiersDidChange: function(event) - { - this._setTracksMouseClickAndDrag(this._hoveredTokenInfo && this._hoveredTokenInfo.containsNumber && WebInspector.modifierKeys.altKey); - }, - - _mouseMoved: function(event) - { - var position = this._codeMirror.coordsChar({left: event.pageX, top: event.pageY}); - var token = this._codeMirror.getTokenAt(position); - - if (!token || !token.type || !token.string) { - if (this._hoveredTokenInfo) - this._reset(); - return; - } - - // Stop right here if we're hovering the same token as we were last time. - if (this._hoveredTokenInfo && this._hoveredTokenInfo.line === position.line && - this._hoveredTokenInfo.token.start === token.start && this._hoveredTokenInfo.token.end === token.end) - return; - - var containsNumber = token.type.indexOf("number") !== -1; - this._hoveredTokenInfo = { - token: token, - line: position.line, - containsNumber: containsNumber, - startPosition: { - ch: token.start, - line: position.line - }, - endPosition: { - ch: token.end, - line: position.line - } - }; - - this._setTracksMouseClickAndDrag(containsNumber && event.altKey); - }, - - _mouseWasPressed: function(event) - { - this._lastX = event.screenX; - - this._setDragging(true); - - event.preventDefault(); - event.stopPropagation(); - }, - - _mouseWasDragged: function(event) - { - var x = event.screenX; - var amount = x - this._lastX; - - if (Math.abs(amount) < 1) - return; - - this._lastX = x; - - if (event.ctrlKey) - amount /= 10; - else if (event.shiftKey) - amount *= 10; - - this._codeMirror.alterNumberInRange(amount, this._hoveredTokenInfo.startPosition, this._hoveredTokenInfo.endPosition, false); - - event.preventDefault(); - event.stopPropagation(); - }, - - _mouseWasReleased: function(event) - { - this._setDragging(false); - - event.preventDefault(); - event.stopPropagation(); - - this._reset(); - }, - - _reset: function() - { - this._hoveredTokenInfo = null; - this._setTracksMouseClickAndDrag(false); - this._element.classList.remove(WebInspector.CodeMirrorDragToAlterNumberController.StyleClassName); - } -}; - -CodeMirror.defineOption("dragToAdjustNumbers", true, function(codeMirror, value, oldValue) { - if (!codeMirror.dragToAlterNumberController) - codeMirror.dragToAlterNumberController = new WebInspector.CodeMirrorDragToAlterNumberController(codeMirror); - codeMirror.dragToAlterNumberController.enabled = value; -}); diff --git a/Source/WebInspectorUI/UserInterface/CodeMirrorFormatters.js b/Source/WebInspectorUI/UserInterface/CodeMirrorFormatters.js deleted file mode 100644 index 3d99cb64f..000000000 --- a/Source/WebInspectorUI/UserInterface/CodeMirrorFormatters.js +++ /dev/null @@ -1,403 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -// In the inspector token types have been modified to include extra mode information -// after the actual token type. So we can't do token === "foo". So instead we do -// /\bfoo\b/.test(token). - -CodeMirror.extendMode("javascript", { - shouldHaveSpaceBeforeToken: function(lastToken, lastContent, token, state, content, isComment) - { - if (!token) { - if (content === "(") // Most keywords like "if (" but not "function(" or "typeof(". - return lastToken && /\bkeyword\b/.test(lastToken) && (lastContent !== "function" && lastContent !== "typeof" && lastContent !== "instanceof"); - if (content === ":") // Ternary. - return (state.lexical.type === "stat" || state.lexical.type === ")"); - if (content === "!") // Unary ! should not be confused with "!=". - return false; - return "+-/*&&||!===+=-=>=<=?".indexOf(content) >= 0; // Operators. - } - - if (isComment) - return true; - - if (/\bkeyword\b/.test(token)) { // Most keywords require spaces before them, unless a '}' can come before it. - if (content === "else" || content === "catch" || content === "finally") - return lastContent === "}"; - return false; - } - - return false; - }, - - shouldHaveSpaceAfterLastToken: function(lastToken, lastContent, token, state, content, isComment) - { - if (lastToken && /\bkeyword\b/.test(lastToken)) { // Most keywords require spaces after them, unless a '{' or ';' can come after it. - if (lastContent === "else") - return true; - if (lastContent === "catch") - return true; - if (lastContent === "return") - return content !== ";"; - if (lastContent === "throw") - return true; - if (lastContent === "try") - return true; - if (lastContent === "finally") - return true; - if (lastContent === "do") - return true; - return false; - } - - if (lastToken && /\bcomment\b/.test(lastToken)) // Embedded /* comment */. - return true; - if (lastContent === ")") // "){". - return content === "{"; - if (lastContent === ";") // In for loop. - return state.lexical.type === ")"; - if (lastContent === "!") // Unary ! should not be confused with "!=". - return false; - - return ",+-/*&&||:!===+=-=>=<=?".indexOf(lastContent) >= 0; // Operators. - }, - - newlinesAfterToken: function(lastToken, lastContent, token, state, content, isComment) - { - if (!token) { - if (content === ",") // In object literals, like in {a:1,b:2}, but not in param lists or vardef lists. - return state.lexical.type === "}" ? 1 : 0; - if (content === ";") // Everywhere except in for loop conditions. - return state.lexical.type !== ")" ? 1 : 0; - if (content === ":" && state.lexical.type === "}" && state.lexical.prev && state.lexical.prev.type === "form") // Switch case/default. - return 1; - return content.length === 1 && "{}".indexOf(content) >= 0 ? 1 : 0; // After braces. - } - - if (isComment) - return 1; - - return 0; - }, - - removeLastNewline: function(lastToken, lastContent, token, state, content, isComment, firstTokenOnLine) - { - if (!token) { - if (content === "}") // "{}". - return lastContent === "{"; - if (content === ";") // "x = {};" or ";;". - return "};".indexOf(lastContent) >= 0; - if (content === ":") // Ternary. - return lastContent === "}" && (state.lexical.type === "stat" || state.lexical.type === ")"); - if (",().".indexOf(content) >= 0) // "})", "}.bind", "function() { ... }()", or "}, false)". - return lastContent === "}"; - return false; - } - - if (isComment) { // Comment after semicolon. - if (!firstTokenOnLine && lastContent === ";") - return true; - return false; - } - - if (/\bkeyword\b/.test(token)) { - if (content === "else" || content === "catch" || content === "finally") // "} else", "} catch", "} finally" - return lastContent === "}"; - return false; - } - - return false; - }, - - indentAfterToken: function(lastToken, lastContent, token, state, content, isComment) - { - return content === "{" || content === "case" || content === "default"; - }, - - newlineBeforeToken: function(lastToken, lastContent, token, state, content, isComment) - { - if (state._jsPrettyPrint.shouldIndent) - return true; - - return content === "}" && lastContent !== "{"; // "{}" - }, - - indentBeforeToken: function(lastToken, lastContent, token, state, content, isComment) - { - if (state._jsPrettyPrint.shouldIndent) - return true; - - return false; - }, - - dedentsBeforeToken: function(lastToken, lastContent, token, state, content, isComment) - { - var dedent = 0; - - if (state._jsPrettyPrint.shouldDedent) - dedent += state._jsPrettyPrint.dedentSize; - - if (!token && content === "}") - dedent += 1; - else if (token && /\bkeyword\b/.test(token) && (content === "case" || content === "default")) - dedent += 1; - - return dedent; - }, - - modifyStateForTokenPre: function(lastToken, lastContent, token, state, content, isComment) - { - if (!state._jsPrettyPrint) { - state._jsPrettyPrint = { - indentCount: 0, // How far have we indented because of single statement blocks. - shouldIndent: false, // Signal we should indent on entering a single statement block. - shouldDedent: false, // Signal we should dedent on leaving a single statement block. - dedentSize: 0, // How far we should dedent when leaving a single statement block. - lastIfIndentCount: 0, // Keep track of the indent the last time we saw an if without braces. - openBraceStartMarkers: [], // Keep track of non-single statement blocks. - openBraceTrackingCount: -1, // Keep track of "{" and "}" in non-single statement blocks. - }; - } - - // - Entering: - // - Preconditions: - // - last lexical was a "form" we haven't encountered before - // - last content was ")", "else", or "do" - // - current lexical is not ")" (in an expression or condition) - // - Cases: - // 1. "{" - // - indent +0 - // - save this indent size so when we encounter the "}" we know how far to dedent - // 2. "else if" - // - indent +0 and do not signal to add a newline and indent - // - mark the last if location so when we encounter an "else" we know how far to dedent - // - mark the lexical state so we know we are inside a single statement block - // 3. Token without brace. - // - indent +1 and signal to add a newline and indent - // - mark the last if location so when we encounter an "else" we know how far to dedent - // - mark the lexical state so we know we are inside a single statement block - if (!isComment && state.lexical.prev && state.lexical.prev.type === "form" && !state.lexical.prev._jsPrettyPrintMarker && (lastContent === ")" || lastContent === "else" || lastContent === "do") && (state.lexical.type !== ")")) { - if (content === "{") { - // Save the state at the opening brace so we can return to it when we see "}". - var savedState = {indentCount:state._jsPrettyPrint.indentCount, openBraceTrackingCount:state._jsPrettyPrint.openBraceTrackingCount}; - state._jsPrettyPrint.openBraceStartMarkers.push(savedState); - state._jsPrettyPrint.openBraceTrackingCount = 1; - } else if (state.lexical.type !== "}") { - // Increase the indent count. Signal for a newline and indent if needed. - if (!(lastContent === "else" && content === "if")) { - state._jsPrettyPrint.indentCount++; - state._jsPrettyPrint.shouldIndent = true; - } - state.lexical.prev._jsPrettyPrintMarker = true; - if (state._jsPrettyPrint.enteringIf) - state._jsPrettyPrint.lastIfIndentCount = state._jsPrettyPrint.indentCount - 1; - } - } - - // - Leaving: - // - Preconditions: - // - we must be indented - // - ignore ";", wait for the next token instead. - // - Cases: - // 1. "else" - // - dedent to the last "if" - // 2. "}" and all braces we saw are balanced - // - dedent to the last "{" - // 3. Token without a marker on the stack - // - dedent all the way - else if (state._jsPrettyPrint.indentCount) { - console.assert(!state._jsPrettyPrint.shouldDedent); - console.assert(!state._jsPrettyPrint.dedentSize); - - // Track "{" and "}" to know when the "}" is really closing a block. - if (!isComment) { - if (content === "{") - state._jsPrettyPrint.openBraceTrackingCount++; - else if (content === "}") - state._jsPrettyPrint.openBraceTrackingCount--; - } - - if (content === ";") { - // Ignore. - } else if (content === "else") { - // Dedent to the last "if". - if (lastContent !== "}") { - state._jsPrettyPrint.shouldDedent = true; - state._jsPrettyPrint.dedentSize = state._jsPrettyPrint.indentCount - state._jsPrettyPrint.lastIfIndentCount; - state._jsPrettyPrint.lastIfIndentCount = 0; - } - } else if (content === "}" && !state._jsPrettyPrint.openBraceTrackingCount && state._jsPrettyPrint.openBraceStartMarkers.length) { - // Dedent to the last "{". - var savedState = state._jsPrettyPrint.openBraceStartMarkers.pop(); - state._jsPrettyPrint.shouldDedent = true; - state._jsPrettyPrint.dedentSize = state._jsPrettyPrint.indentCount - savedState.indentCount; - state._jsPrettyPrint.openBraceTrackingCount = savedState.openBraceTrackingCount; - } else { - // Dedent all the way. - var shouldDedent = true; - var lexical = state.lexical.prev; - while (lexical) { - if (lexical._jsPrettyPrintMarker) { - shouldDedent = false; - break; - } - lexical = lexical.prev; - } - if (shouldDedent) { - state._jsPrettyPrint.shouldDedent = true; - state._jsPrettyPrint.dedentSize = state._jsPrettyPrint.indentCount; - } - } - } - - // Signal for when we will be entering an if. - if (token && state.lexical.type === "form" && state.lexical.prev && state.lexical.prev !== "form" && /\bkeyword\b/.test(token)) - state._jsPrettyPrint.enteringIf = (content === "if"); - }, - - modifyStateForTokenPost: function(lastToken, lastContent, token, state, content, isComment) - { - if (state._jsPrettyPrint.shouldIndent) - state._jsPrettyPrint.shouldIndent = false; - - if (state._jsPrettyPrint.shouldDedent) { - state._jsPrettyPrint.indentCount -= state._jsPrettyPrint.dedentSize; - state._jsPrettyPrint.dedentSize = 0; - state._jsPrettyPrint.shouldDedent = false; - } - } -}); - -CodeMirror.extendMode("css", { - shouldHaveSpaceBeforeToken: function(lastToken, lastContent, token, state, content, isComment) - { - if (!token) { - if (content === "{") - return true; - return false; - } - - if (isComment) - return true; - - if (/\bkeyword\b/.test(token)) { - if (content.charAt(0) === "!") // "!important". - return true; - return false; - } - - return false; - }, - - shouldHaveSpaceAfterLastToken: function(lastToken, lastContent, token, state, content, isComment) - { - if (!lastToken) { - if (lastContent === ",") - return true; - return false; - } - - if (/\boperator\b/.test(lastToken)) { - if (lastContent === ":") // Space in "prop: value" but not in a selectors "a:link" or "div::after" or media queries "(max-device-width:480px)". - return state.stack.lastValue === "propertyValue"; - return false; - } - - if (/\bcomment\b/.test(lastToken)) - return true; - - return false; - }, - - newlinesAfterToken: function(lastToken, lastContent, token, state, content, isComment) - { - if (!token) { - if (content === ";") - return 1; - if (content === ",") { // "a,b,c,...,z{}" rule list at top level or in @media top level and only if the line length will be large. - if ((!state.stack.length || state.stack.lastValue === "@media{") && state._cssPrettyPrint.lineLength > 60) { - state._cssPrettyPrint.lineLength = 0; - return 1; - } - return 0; - } - if (content === "{") - return 1; - if (content === "}") // 2 newlines between rule declarations. - return 2; - return 0; - } - - if (isComment) - return 1; - - return 0; - }, - - removeLastNewline: function(lastToken, lastContent, token, state, content, isComment, firstTokenOnLine) - { - if (isComment) { // Comment after semicolon. - if (!firstTokenOnLine && lastContent === ";") - return true; - return false; - } - - return content === "}" && (lastContent === "{" || lastContent === "}"); // "{}" and "}\n}" when closing @media. - }, - - indentAfterToken: function(lastToken, lastContent, token, state, content, isComment) - { - return content === "{"; - }, - - newlineBeforeToken: function(lastToken, lastContent, token, state, content, isComment) - { - return content === "}" && (lastContent !== "{" && lastContent !== "}"); // "{}" and "}\n}" when closing @media. - }, - - indentBeforeToken: function(lastToken, lastContent, token, state, content, isComment) - { - return false; - }, - - dedentsBeforeToken: function(lastToken, lastContent, token, state, content, isComment) - { - return content === "}" ? 1 : 0; - }, - - modifyStateForTokenPost: function(lastToken, lastContent, token, state, content, isComment) - { - if (!state._cssPrettyPrint) - state._cssPrettyPrint = {lineLength: 0}; - - // In order insert newlines in selector lists we need keep track of the length of the current line. - // This isn't exact line length, only the builder knows that, but it is good enough to get an idea. - // If we are at a top level, keep track of the current line length, otherwise we reset to 0. - if (!state.stack.length || state.stack.lastValue === "@media{") - state._cssPrettyPrint.lineLength += content.length; - else - state._cssPrettyPrint.lineLength = 0; - } -}); diff --git a/Source/WebInspectorUI/UserInterface/CodeMirrorOverrides.css b/Source/WebInspectorUI/UserInterface/CodeMirrorOverrides.css deleted file mode 100644 index d77dc9a0e..000000000 --- a/Source/WebInspectorUI/UserInterface/CodeMirrorOverrides.css +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.CodeMirror { - z-index: 0; -} - -.CodeMirror, -.CodeMirror * { - box-sizing: content-box; -} - -.CodeMirror .CodeMirror-lines { - /* One pixel bottom padding needed to show the bottom border for matching brackets and search matches. */ - padding: 0 0 1px 0; -} - -.CodeMirror pre { - padding: 1px 3px 1px 7px; -} - -.CodeMirror .CodeMirror-selected { - background-color: rgb(212, 212, 212); -} - -.CodeMirror.CodeMirror-focused .CodeMirror-selected { - background-color: highlight; -} - -.CodeMirror .CodeMirror-cursor { - pointer-events: none; -} - -.CodeMirror .CodeMirror-lines .CodeMirror-matchingbracket { - color: inherit; - background-color: rgba(100, 130, 235, 0.2); - border-bottom: 1px dotted rgb(20, 20, 235); -} - -.CodeMirror .CodeMirror-lines .CodeMirror-nonmatchingbracket { - color: inherit; - background-color: rgba(235, 30, 20, 0.2); - border-bottom: 1px dotted rgb(235, 30, 20); -} - -.CodeMirror .CodeMirror-gutters { - background-color: rgb(247, 247, 247); - border-right: 1px solid rgb(231, 231, 231); -} - -.CodeMirror .CodeMirror-linenumber { - padding: 0 2px; - min-width: 21px; - - color: rgb(146, 146, 146); - - font-size: 9px; - line-height: 13px; - font-family: "Lucida Grande", sans-serif; - text-align: right; -} diff --git a/Source/WebInspectorUI/UserInterface/CodeMirrorTokenTrackingController.css b/Source/WebInspectorUI/UserInterface/CodeMirrorTokenTrackingController.css deleted file mode 100644 index 516755d1c..000000000 --- a/Source/WebInspectorUI/UserInterface/CodeMirrorTokenTrackingController.css +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.CodeMirror .jump-to-symbol-highlight { - color: blue !important; - text-decoration: underline !important; - cursor: pointer !important; - -webkit-text-stroke-width: 0 !important; -} diff --git a/Source/WebInspectorUI/UserInterface/CodeMirrorTokenTrackingController.js b/Source/WebInspectorUI/UserInterface/CodeMirrorTokenTrackingController.js deleted file mode 100644 index 3a042e317..000000000 --- a/Source/WebInspectorUI/UserInterface/CodeMirrorTokenTrackingController.js +++ /dev/null @@ -1,509 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.CodeMirrorTokenTrackingController = function(codeMirror, delegate) -{ - WebInspector.Object.call(this); - - console.assert(codeMirror); - - this._codeMirror = codeMirror; - this._delegate = delegate || null; - this._mode = WebInspector.CodeMirrorTokenTrackingController.Mode.None; - - this._mouseOverDelayDuration = 0; - this._mouseOutReleaseDelayDuration = 0; - this._classNameForHighlightedRange = null; - - this._enabled = false; - this._tracking = false; - this._hoveredTokenInfo = null; - this._hoveredMarker = null; -}; - -WebInspector.CodeMirrorTokenTrackingController.JumpToSymbolHighlightStyleClassName = "jump-to-symbol-highlight"; - -WebInspector.CodeMirrorTokenTrackingController.Mode = { - None: "none", - NonSymbolTokens: "non-symbol-tokens", - JavaScriptExpression: "javascript-expression", - MarkedTokens: "marked-tokens" -} - -WebInspector.CodeMirrorTokenTrackingController.prototype = { - constructor: WebInspector.CodeMirrorTokenTrackingController, - - // Public - - get delegate() - { - return this._delegate; - }, - - set delegate(x) - { - this._delegate = x; - }, - - get enabled() - { - return this._enabled; - }, - - set enabled(enabled) - { - if (this._enabled === enabled) - return; - - this._enabled = enabled; - - var wrapper = this._codeMirror.getWrapperElement(); - if (enabled) { - wrapper.addEventListener("mouseenter", this); - wrapper.addEventListener("mouseleave", this); - this._updateHoveredTokenInfo({left: WebInspector.mouseCoords.x, top: WebInspector.mouseCoords.y}); - this._startTracking(); - } else { - wrapper.removeEventListener("mouseenter", this); - wrapper.removeEventListener("mouseleave", this); - this._stopTracking(); - } - }, - - get mode() - { - return this._mode; - }, - - set mode(mode) - { - var oldMode = this._mode; - - this._mode = mode || WebInspector.CodeMirrorTokenTrackingController.Mode.None; - - if (oldMode !== this._mode && this._tracking && this._hoveredTokenInfo) - this._processNewHoveredToken(); - }, - - get mouseOverDelayDuration() - { - return this._mouseOverDelayDuration; - }, - - set mouseOverDelayDuration(x) - { - console.assert(x >= 0); - this._mouseOverDelayDuration = Math.max(x, 0); - }, - - get mouseOutReleaseDelayDuration() - { - return this._mouseOutReleaseDelayDuration; - }, - - set mouseOutReleaseDelayDuration(x) - { - console.assert(x >= 0); - this._mouseOutReleaseDelayDuration = Math.max(x, 0); - }, - - get classNameForHighlightedRange() - { - return this._classNameForHighlightedRange; - }, - - set classNameForHighlightedRange(x) - { - this._classNameForHighlightedRange = x || null; - }, - - get candidate() - { - return this._candidate; - }, - - get hoveredMarker() - { - return this._hoveredMarker; - }, - - set hoveredMarker(hoveredMarker) - { - this._hoveredMarker = hoveredMarker; - }, - - highlightLastHoveredRange: function() - { - if (this._candidate) - this.highlightRange(this._candidate.hoveredTokenRange); - }, - - highlightRange: function(range) - { - // Nothing to do if we're trying to highlight the same range. - if (this._codeMirrorMarkedText && this._codeMirrorMarkedText.className === this._classNameForHighlightedRange) { - var highlightedRange = this._codeMirrorMarkedText.find(); - if (WebInspector.compareCodeMirrorPositions(highlightedRange.from, range.start) === 0 && - WebInspector.compareCodeMirrorPositions(highlightedRange.to, range.end) === 0) - return; - } - - this.removeHighlightedRange(); - - var className = this._classNameForHighlightedRange || ""; - this._codeMirrorMarkedText = this._codeMirror.markText(range.start, range.end, {className: className}); - - window.addEventListener("mousemove", this, true); - }, - - removeHighlightedRange: function() - { - if (!this._codeMirrorMarkedText) - return; - - this._codeMirrorMarkedText.clear(); - delete this._codeMirrorMarkedText; - - window.removeEventListener("mousemove", this, true); - }, - - // Private - - _startTracking: function() - { - console.assert(!this._tracking); - if (this._tracking) - return; - - this._tracking = true; - - var wrapper = this._codeMirror.getWrapperElement(); - wrapper.addEventListener("mousemove", this, true); - wrapper.addEventListener("mouseout", this, false); - wrapper.addEventListener("mousedown", this, false); - wrapper.addEventListener("mouseup", this, false); - window.addEventListener("blur", this, true); - }, - - _stopTracking: function() - { - console.assert(this._tracking); - if (!this._tracking) - return; - - this._tracking = false; - this._candidate = null; - - var wrapper = this._codeMirror.getWrapperElement(); - wrapper.removeEventListener("mousemove", this, true); - wrapper.removeEventListener("mouseout", this, false); - wrapper.removeEventListener("mousedown", this, false); - wrapper.removeEventListener("mouseup", this, false); - window.removeEventListener("blur", this, true); - window.removeEventListener("mousemove", this, true); - - this._resetTrackingStates(); - }, - - handleEvent: function(event) - { - switch (event.type) { - case "mouseenter": - this._mouseEntered(event); - break; - case "mouseleave": - this._mouseLeft(event); - break; - case "mousemove": - if (event.currentTarget === window) - this._mouseMovedWithMarkedText(event); - else - this._mouseMovedOverEditor(event); - break; - case "mouseout": - // Only deal with a mouseout event that has the editor wrapper as the target. - if (!event.currentTarget.contains(event.relatedTarget)) - this._mouseMovedOutOfEditor(event); - break; - case "mousedown": - this._mouseButtonWasPressedOverEditor(event); - break; - case "mouseup": - this._mouseButtonWasReleasedOverEditor(event); - break; - case "blur": - this._windowLostFocus(event); - break; - } - }, - - _mouseEntered: function(event) - { - this._startTracking(); - }, - - _mouseLeft: function(event) - { - this._stopTracking(); - }, - - _mouseMovedWithMarkedText: function(event) - { - var shouldRelease = !event.target.classList.contains(this._classNameForHighlightedRange); - if (shouldRelease && this._delegate && typeof this._delegate.tokenTrackingControllerCanReleaseHighlightedRange === "function") - shouldRelease = this._delegate.tokenTrackingControllerCanReleaseHighlightedRange(this, event.target); - - if (shouldRelease) { - if (!this._markedTextMouseoutTimer) - this._markedTextMouseoutTimer = setTimeout(this._markedTextIsNoLongerHovered.bind(this), this._mouseOutReleaseDelayDuration); - return; - } - - clearTimeout(this._markedTextMouseoutTimer); - delete this._markedTextMouseoutTimer; - }, - - _markedTextIsNoLongerHovered: function() - { - if (this._delegate && typeof this._delegate.tokenTrackingControllerHighlightedRangeReleased === "function") - this._delegate.tokenTrackingControllerHighlightedRangeReleased(this); - delete this._markedTextMouseoutTimer; - }, - - _mouseMovedOverEditor: function(event) - { - this._updateHoveredTokenInfo({left: event.pageX, top: event.pageY}); - }, - - _updateHoveredTokenInfo: function(mouseCoords) - { - // Get the position in the text and the token at that position. - var position = this._codeMirror.coordsChar(mouseCoords); - var token = this._codeMirror.getTokenAt(position); - - if (!token || !token.type || !token.string) { - if (this._hoveredMarker && this._delegate && typeof this._delegate.tokenTrackingControllerMouseOutOfHoveredMarker === "function") { - if (!this._codeMirror.findMarksAt(position).contains(this._hoveredMarker.codeMirrorTextMarker)) - this._delegate.tokenTrackingControllerMouseOutOfHoveredMarker(this, this._hoveredMarker); - } - - this._resetTrackingStates(); - return; - } - - // Stop right here if we're hovering the same token as we were last time. - if (this._hoveredTokenInfo && - this._hoveredTokenInfo.position.line === position.line && - this._hoveredTokenInfo.token.start === token.start && - this._hoveredTokenInfo.token.end === token.end) - return; - - // We have a new hovered token. - var innerMode = CodeMirror.innerMode(this._codeMirror.getMode(), token.state); - var codeMirrorModeName = innerMode.mode.alternateName || innerMode.mode.name; - this._hoveredTokenInfo = { - token: token, - position: position, - innerMode: innerMode, - modeName: codeMirrorModeName - }; - - clearTimeout(this._tokenHoverTimer); - - if (this._codeMirrorMarkedText || !this._mouseOverDelayDuration) - this._processNewHoveredToken(); - else - this._tokenHoverTimer = setTimeout(this._processNewHoveredToken.bind(this), this._mouseOverDelayDuration); - }, - - _mouseMovedOutOfEditor: function(event) - { - clearTimeout(this._tokenHoverTimer); - delete this._hoveredTokenInfo; - delete this._selectionMayBeInProgress; - }, - - _mouseButtonWasPressedOverEditor: function(event) - { - this._selectionMayBeInProgress = true; - }, - - _mouseButtonWasReleasedOverEditor: function(event) - { - delete this._selectionMayBeInProgress; - this._mouseMovedOverEditor(event); - - if (this._codeMirrorMarkedText && this._hoveredTokenInfo) { - var position = this._codeMirror.coordsChar({left: event.pageX, top: event.pageY}); - var marks = this._codeMirror.findMarksAt(position); - for (var i = 0; i < marks.length; ++i) { - if (marks[i] === this._codeMirrorMarkedText) { - if (this._delegate && typeof this._delegate.tokenTrackingControllerHighlightedRangeWasClicked === "function") { - // Trigger the clicked delegate asynchronously, letting the editor complete handling of the click. - setTimeout(function() { this._delegate.tokenTrackingControllerHighlightedRangeWasClicked(this); }.bind(this), 0); - } - break; - } - } - } - }, - - _windowLostFocus: function(event) - { - this._resetTrackingStates(); - }, - - _processNewHoveredToken: function() - { - console.assert(this._hoveredTokenInfo); - - if (this._selectionMayBeInProgress) - return; - - this._candidate = null; - - switch (this._mode) { - case WebInspector.CodeMirrorTokenTrackingController.Mode.NonSymbolTokens: - this._candidate = this._processNonSymbolToken(); - break; - case WebInspector.CodeMirrorTokenTrackingController.Mode.JavaScriptExpression: - this._candidate = this._processJavaScriptExpression(); - break; - case WebInspector.CodeMirrorTokenTrackingController.Mode.MarkedTokens: - this._candidate = this._processMarkedToken(); - break; - } - - if (!this._candidate) - return; - - clearTimeout(this._markedTextMouseoutTimer); - delete this._markedTextMouseoutTimer; - - if (this._delegate && typeof this._delegate.tokenTrackingControllerNewHighlightCandidate === "function") - this._delegate.tokenTrackingControllerNewHighlightCandidate(this, this._candidate); - }, - - _processNonSymbolToken: function() - { - // Ignore any symbol tokens. - var type = this._hoveredTokenInfo.token.type; - if (!type) - return null; - - var startPosition = {line: this._hoveredTokenInfo.position.line, ch: this._hoveredTokenInfo.token.start}; - var endPosition = {line: this._hoveredTokenInfo.position.line, ch: this._hoveredTokenInfo.token.end}; - - return { - hoveredToken: this._hoveredTokenInfo.token, - hoveredTokenRange: {start: startPosition, end: endPosition}, - }; - }, - - _processJavaScriptExpression: function() - { - // Only valid within JavaScript. - if (this._hoveredTokenInfo.modeName !== "javascript") - return null; - - var startPosition = {line: this._hoveredTokenInfo.position.line, ch: this._hoveredTokenInfo.token.start}; - var endPosition = {line: this._hoveredTokenInfo.position.line, ch: this._hoveredTokenInfo.token.end}; - - // If the hovered token is within a selection, use the selection as our expression. - if (this._codeMirror.somethingSelected()) { - var selectionRange = { - start: this._codeMirror.getCursor("start"), - end: this._codeMirror.getCursor("end") - }; - - function tokenIsInRange(token, range) - { - return token.line >= range.start.line && token.ch >= range.start.ch && - token.line <= range.end.line && token.ch <= range.end.ch; - } - - if (tokenIsInRange(startPosition, selectionRange) || tokenIsInRange(endPosition, selectionRange)) { - return { - hoveredToken: this._hoveredTokenInfo.token, - hoveredTokenRange: selectionRange, - expression: this._codeMirror.getSelection(), - expressionRange: selectionRange, - }; - } - } - - // We only handle vars, definitions, properties, and the keyword 'this'. - var type = this._hoveredTokenInfo.token.type; - var isProperty = type.indexOf("property") !== -1; - var isKeyword = type.indexOf("keyword") !== -1; - if (!isProperty && !isKeyword && type.indexOf("variable") === -1 && type.indexOf("def") === -1) - return null; - - // Not object literal properties. - var state = this._hoveredTokenInfo.innerMode.state; - if (isProperty && state.lexical && state.lexical.type === "}") - return null; - - // Only the "this" keyword. - if (isKeyword && this._hoveredTokenInfo.token.string !== "this") - return null; - - // Work out the full hovered expression. - var expression = this._hoveredTokenInfo.token.string; - var expressionStartPosition = {line: this._hoveredTokenInfo.position.line, ch: this._hoveredTokenInfo.token.start}; - while (true) { - var token = this._codeMirror.getTokenAt(expressionStartPosition); - var isDot = token && !token.type && token.string === "."; - var isExpression = token && token.type && token.type.indexOf("m-javascript") !== -1; - if (!isDot && !isExpression) - break; - expression = token.string + expression; - expressionStartPosition.ch = token.start; - } - - // Return the candidate for this token and expression. - return { - hoveredToken: this._hoveredTokenInfo.token, - hoveredTokenRange: {start: startPosition, end: endPosition}, - expression: expression, - expressionRange: {start: expressionStartPosition, end: endPosition}, - }; - }, - - _processMarkedToken: function() - { - return this._processNonSymbolToken(); - }, - - _resetTrackingStates: function() - { - clearTimeout(this._tokenHoverTimer); - delete this._selectionMayBeInProgress; - delete this._hoveredTokenInfo; - this.removeHighlightedRange(); - } -}; - -WebInspector.CodeMirrorCompletionController.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/Color.js b/Source/WebInspectorUI/UserInterface/Color.js deleted file mode 100644 index edf5cd092..000000000 --- a/Source/WebInspectorUI/UserInterface/Color.js +++ /dev/null @@ -1,665 +0,0 @@ -/* - * Copyright (C) 2009, 2013 Apple Inc. All rights reserved. - * Copyright (C) 2009 Joseph Pecoraro - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.Color = function(format, components) -{ - this.format = format; - if (format === WebInspector.Color.Format.HSL || format === WebInspector.Color.Format.HSLA) - this._hsla = components; - else - this._rgba = components; - - this.valid = !components.some(function(component) { - return isNaN(component); - }); -} - -WebInspector.Color.Format = { - Original: "color-format-original", - Nickname: "color-format-nickname", - HEX: "color-format-hex", - ShortHEX: "color-format-short-hex", - RGB: "color-format-rgb", - RGBA: "color-format-rgba", - HSL: "color-format-hsl", - HSLA: "color-format-hsla" -}; - -WebInspector.Color.fromString = function(colorString) -{ - var value = colorString.toLowerCase().replace(/%|\s+/g, ""); - const transparentNicknames = ["transparent", "rgba(0,0,0,0)", "hsla(0,0,0,0)"]; - if (transparentNicknames.contains(value)) { - var color = new WebInspector.Color(WebInspector.Color.Format.Nickname, [0, 0, 0, 0]); - color.nickname = "transparent"; - color.original = colorString; - return color; - } - - // Simple - #hex, rgb(), nickname, hsl() - var simple = /^(?:#([0-9a-f]{3,6})|rgb\(([^)]+)\)|(\w+)|hsl\(([^)]+)\))$/i; - var match = colorString.match(simple); - if (match) { - if (match[1]) { // hex - var hex = match[1].toUpperCase(); - if (hex.length === 3) { - return new WebInspector.Color(WebInspector.Color.Format.ShortHEX, [ - parseInt(hex.charAt(0) + hex.charAt(0), 16) * 255, - parseInt(hex.charAt(1) + hex.charAt(1), 16) * 255, - parseInt(hex.charAt(2) + hex.charAt(2), 16) * 255, - 1 - ]); - } else { - return new WebInspector.Color(WebInspector.Color.Format.HEX, [ - parseInt(hex.substring(0, 2), 16) * 255, - parseInt(hex.substring(2, 4), 16) * 255, - parseInt(hex.substring(4, 6), 16) * 255, - 1 - ]); - } - } else if (match[2]) { // rgb - var rgb = match[2].split(/\s*,\s*/); - return new WebInspector.Color(WebInspector.Color.Format.RGB, [ - parseInt(rgb[0]), - parseInt(rgb[1]), - parseInt(rgb[2]), - 1 - ]); - } else if (match[3]) { // nickname - var nickname = match[3].toLowerCase(); - if (WebInspector.Color.Nicknames.hasOwnProperty(nickname)) { - var color = new WebInspector.Color(WebInspector.Color.Format.Nickname, WebInspector.Color.Nicknames[nickname].concat(1)); - color.nickname = nickname; - color.original = colorString; - return color; - } else - return null; - } else if (match[4]) { // hsl - var hsl = match[4].replace(/%/g, "").split(/\s*,\s*/); - return new WebInspector.Color(WebInspector.Color.Format.HSL, [ - parseInt(hsl[0]), - parseInt(hsl[1]), - parseInt(hsl[2]), - 1 - ]); - } - } - - // Advanced - rgba(), hsla() - var advanced = /^(?:rgba\(([^)]+)\)|hsla\(([^)]+)\))$/; - match = colorString.match(advanced); - if (match) { - if (match[1]) { // rgba - var rgba = match[1].split(/\s*,\s*/); - return new WebInspector.Color(WebInspector.Color.Format.RGBA, [ - parseInt(rgba[0]), - parseInt(rgba[1]), - parseInt(rgba[2]), - Number.constrain(parseFloat(rgba[3]), 0, 1) - ]); - } else if (match[2]) { // hsla - var hsla = match[2].replace(/%/g, "").split(/\s*,\s*/); - return new WebInspector.Color(WebInspector.Color.Format.HSLA, [ - parseInt(hsla[0]), - parseInt(hsla[1]), - parseInt(hsla[2]), - Number.constrain(parseFloat(hsla[3]), 0, 1) - ]); - } - } - - return null; -} - -WebInspector.Color.prototype = { - nextFormat: function(format) - { - format = format || this.format; - - switch (format) { - case WebInspector.Color.Format.Original: - return this.simple ? WebInspector.Color.Format.RGB : WebInspector.Color.Format.RGBA; - - case WebInspector.Color.Format.RGB: - case WebInspector.Color.Format.RGBA: - return this.simple ? WebInspector.Color.Format.HSL : WebInspector.Color.Format.HSLA; - - case WebInspector.Color.Format.HSL: - case WebInspector.Color.Format.HSLA: - if (this.nickname) - return WebInspector.Color.Format.Nickname; - if (this.simple) - return this._canBeSerializedAsShortHEX() ? WebInspector.Color.Format.ShortHEX : WebInspector.Color.Format.HEX; - else - return WebInspector.Color.Format.Original; - - case WebInspector.Color.Format.ShortHEX: - return WebInspector.Color.Format.HEX; - - case WebInspector.Color.Format.HEX: - return WebInspector.Color.Format.Original; - - case WebInspector.Color.Format.Nickname: - if (this.simple) - return this._canBeSerializedAsShortHEX() ? WebInspector.Color.Format.ShortHEX : WebInspector.Color.Format.HEX; - else - return WebInspector.Color.Format.Original; - - default: - console.error("Unknown color format."); - return null; - } - }, - - get alpha() - { - return this._rgba ? this._rgba[3] : this._hsla[3]; - }, - - get simple() - { - return this.alpha === 1; - }, - - get rgb() - { - var rgb = this.rgba.slice(); - rgb.pop(); - return rgb; - }, - - get hsl() - { - var hsl = this.hsla.slice(); - hsl.pop(); - return hsl; - }, - - get rgba() - { - if (!this._rgba) - this._rgba = this._hslaToRGBA(this._hsla); - return this._rgba; - }, - - get hsla() - { - if (!this._hsla) - this._hsla = this._rgbaToHSLA(this.rgba); - return this._hsla; - }, - - copy: function() - { - switch (this.format) { - case WebInspector.Color.Format.RGB: - case WebInspector.Color.Format.HEX: - case WebInspector.Color.Format.ShortHEX: - case WebInspector.Color.Format.Nickname: - case WebInspector.Color.Format.RGBA: - return new WebInspector.Color(this.format, this.rgba); - case WebInspector.Color.Format.HSL: - case WebInspector.Color.Format.HSLA: - return new WebInspector.Color(this.format, this.hsla); - } - }, - - toString: function(format) - { - if (!format) - format = this.format; - - switch (format) { - case WebInspector.Color.Format.Original: - return this._toOriginalString(); - case WebInspector.Color.Format.RGB: - return this._toRGBString(); - case WebInspector.Color.Format.RGBA: - return this._toRGBAString(); - case WebInspector.Color.Format.HSL: - return this._toHSLString(); - case WebInspector.Color.Format.HSLA: - return this._toHSLAString(); - case WebInspector.Color.Format.HEX: - return this._toHEXString(); - case WebInspector.Color.Format.ShortHEX: - return this._toShortHEXString(); - case WebInspector.Color.Format.Nickname: - return this._toNicknameString(); - } - - throw "invalid color format"; - }, - - _toOriginalString: function() - { - return this.original || this._toNicknameString(); - }, - - _toNicknameString: function() - { - if (this.nickname) - return this.nickname; - - var rgba = this.rgba; - if (!this.simple) { - if (rgba[0] === 0 && rgba[1] === 0 && rgba[2] === 0 && rgba[3] === 0) - return "transparent"; - return this._toRGBAString(); - } - - var nicknames = WebInspector.Color.Nicknames; - for (var nickname in nicknames) { - if (!nicknames.hasOwnProperty(nickname)) - continue; - - var nicknameRGB = nicknames[nickname]; - if (nicknameRGB[0] === rgba[0] && nicknameRGB[1] === rgba[1] && nicknameRGB[2] === rgba[2]) - return nickname; - } - - return this._toRGBString(); - }, - - _toShortHEXString: function() - { - if (!this.simple) - return this._toRGBAString(); - - var rgba = this.rgba; - var r = this._componentToHexValue(rgba[0]); - var g = this._componentToHexValue(rgba[1]); - var b = this._componentToHexValue(rgba[2]); - - if (r[0] === r[1] && g[0] === g[1] && b[0] === b[1]) - return "#" + r[0] + g[0] + b[0]; - else - return "#" + r + g + b; - }, - - _toHEXString: function() - { - if (!this.simple) - return this._toRGBAString(); - - var rgba = this.rgba; - var r = this._componentToHexValue(rgba[0]); - var g = this._componentToHexValue(rgba[1]); - var b = this._componentToHexValue(rgba[2]); - - return "#" + r + g + b; - }, - - _toRGBString: function() - { - if (!this.simple) - return this._toRGBAString(); - - var rgba = this.rgba; - return "rgb(" + [rgba[0], rgba[1], rgba[2]].join(", ") + ")"; - }, - - _toRGBAString: function() - { - return "rgba(" + this.rgba.join(", ") + ")"; - }, - - _toHSLString: function() - { - if (!this.simple) - return this._toHSLAString(); - - var hsla = this.hsla; - return "hsl(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%)"; - }, - - _toHSLAString: function() - { - var hsla = this.hsla; - return "hsla(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%, " + hsla[3] + ")"; - }, - - _canBeSerializedAsShortHEX: function() - { - var rgba = this.rgba; - - var r = this._componentToHexValue(rgba[0]); - if (r[0] !== r[1]) - return false; - - var g = this._componentToHexValue(rgba[1]); - if (g[0] !== g[1]) - return false; - - var b = this._componentToHexValue(rgba[2]); - if (b[0] !== b[1]) - return false; - - return true; - }, - - _componentToNumber: function(value) - { - return Number.constrain(value, 0, 255); - }, - - _componentToHexValue: function(value) - { - var hex = this._componentToNumber(value).toString(16); - if (hex.length === 1) - hex = "0" + hex; - return hex; - }, - - _rgbToHSL: function(rgb) - { - var r = this._componentToNumber(rgb[0]) / 255; - var g = this._componentToNumber(rgb[1]) / 255; - var b = this._componentToNumber(rgb[2]) / 255; - 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 = ((60 * (g - b) / diff) + 360) % 360; - else if (g === max) - var h = (60 * (b - r) / diff) + 120; - else - var h = (60 * (r - g) / diff) + 240; - - 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); - - h = Math.round(h); - s = Math.round(s * 100); - l = Math.round(l * 100); - - return [h, s, l]; - }, - - _hslToRGB: function(hsl) - { - var h = parseFloat(hsl[0]) / 360; - var s = parseFloat(hsl[1]) / 100; - var l = parseFloat(hsl[2]) / 100; - - h *= 6; - var sArray = [ - l += s *= l < .5 ? l : 1 - l, - l - h % 1 * s * 2, - l -= s *= 2, - l, - l + h % 1 * s, - l + s - ]; - return [ - Math.round(sArray[ ~~h % 6 ] * 255), - Math.round(sArray[ (h|16) % 6 ] * 255), - Math.round(sArray[ (h|8) % 6 ] * 255) - ]; - }, - - _rgbaToHSLA: function(rgba) - { - var hsl = this._rgbToHSL(rgba); - hsl.push(rgba[3]); - return hsl; - }, - - _hslaToRGBA: function(hsla) - { - var rgba = this._hslToRGB(hsla); - rgba.push(hsla[3]); - return rgba; - } -} - -WebInspector.Color.Nicknames = { - "aliceblue": [240, 248, 255], - "antiquewhite": [250, 235, 215], - "aquamarine": [127, 255, 212], - "azure": [240, 255, 255], - "beige": [245, 245, 220], - "bisque": [255, 228, 196], - "black": [0, 0, 0], - "blanchedalmond": [255, 235, 205], - "blue": [0, 0, 255], - "blueviolet": [138, 43, 226], - "brown": [165, 42, 42], - "burlywood": [222, 184, 135], - "cadetblue": [95, 158, 160], - "chartreuse": [127, 255, 0], - "chocolate": [210, 105, 30], - "coral": [255, 127, 80], - "cornflowerblue": [100, 149, 237], - "cornsilk": [255, 248, 220], - "crimson": [237, 164, 61], - "cyan": [0, 255, 255], - "darkblue": [0, 0, 139], - "darkcyan": [0, 139, 139], - "darkgoldenrod": [184, 134, 11], - "darkgray": [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], - "darkturquoise": [0, 206, 209], - "darkviolet": [148, 0, 211], - "deeppink": [255, 20, 147], - "deepskyblue": [0, 191, 255], - "dimgray": [105, 105, 105], - "dodgerblue": [30, 144, 255], - "firebrick": [178, 34, 34], - "floralwhite": [255, 250, 240], - "forestgreen": [34, 139, 34], - "gainsboro": [220, 220, 220], - "ghostwhite": [248, 248, 255], - "gold": [255, 215, 0], - "goldenrod": [218, 165, 32], - "gray": [128, 128, 128], - "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], - "lightgrey": [211, 211, 211], - "lightpink": [255, 182, 193], - "lightsalmon": [255, 160, 122], - "lightseagreen": [32, 178, 170], - "lightskyblue": [135, 206, 250], - "lightslategray": [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], - "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], - "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] -}; - -WebInspector.Color.rgb2hsv = function(r, g, b) -{ - r /= 255; - g /= 255; - b /= 255; - - var min = Math.min(Math.min(r, g), b); - var max = Math.max(Math.max(r, g), b); - var delta = max - min; - - var v = max; - var s, h; - - if (max === min) - h = 0; - else if (max === r) - h = (60 * ((g - b) / delta)) % 360; - else if (max === g) - h = 60 * ((b - r) / delta) + 120; - else if (max === b) - h = 60 * ((r - g) / delta) + 240; - - if (h < 0) - h += 360; - - // Saturation - if (max === 0) - s = 0; - else - s = 1 - (min/max); - - return [h, s, v]; -} - -WebInspector.Color.hsv2rgb = function(h, s, v) -{ - if (s === 0) - return [v, v, v]; - - h /= 60; - var i = Math.floor(h); - var data = [ - v * (1 - s), - v * (1 - s * (h - i)), - v * (1 - s * (1 - (h - i))) - ]; - var rgb; - - switch (i) { - case 0: - rgb = [v, data[2], data[0]]; - break; - case 1: - rgb = [data[1], v, data[0]]; - break; - case 2: - rgb = [data[0], v, data[2]]; - break; - case 3: - rgb = [data[0], data[1], v]; - break; - case 4: - rgb = [data[2], data[0], v]; - break; - default: - rgb = [v, data[0], data[1]]; - break; - } - - return rgb; -} diff --git a/Source/WebInspectorUI/UserInterface/ColorPicker.css b/Source/WebInspectorUI/UserInterface/ColorPicker.css deleted file mode 100644 index 72b85a740..000000000 --- a/Source/WebInspectorUI/UserInterface/ColorPicker.css +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.color-picker { - position: relative; - width: 256px; - height: 210px; - padding: 5px; -} - -.color-picker > * { - position: absolute; -} - -.color-picker > .slider { - top: 7px; - width: 196px; - -webkit-transform: rotate(-90deg) translateX(-100%); - -webkit-transform-origin: 0 0; -} - -.color-picker > .brightness { - left: 215px; -} - -.color-picker > .opacity { - left: 238px; -} diff --git a/Source/WebInspectorUI/UserInterface/ColorPicker.js b/Source/WebInspectorUI/UserInterface/ColorPicker.js deleted file mode 100644 index fc8059cff..000000000 --- a/Source/WebInspectorUI/UserInterface/ColorPicker.js +++ /dev/null @@ -1,144 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ColorPicker = function() -{ - WebInspector.Object.call(this); - - this._colorWheel = new WebInspector.ColorWheel(); - this._colorWheel.delegate = this; - this._colorWheel.dimension = 200; - - this._brightnessSlider = new WebInspector.Slider(); - this._brightnessSlider.delegate = this; - this._brightnessSlider.element.classList.add("brightness"); - - this._opacitySlider = new WebInspector.Slider(); - this._opacitySlider.delegate = this; - this._opacitySlider.element.classList.add("opacity"); - - this._element = document.createElement("div"); - this._element.className = "color-picker"; - - this._element.appendChild(this._colorWheel.element); - this._element.appendChild(this._brightnessSlider.element); - this._element.appendChild(this._opacitySlider.element); - - this._opacityPattern = 'url("data:image/svg+xml;base64,' + btoa('') + '")'; - - this._color = "white"; -}; - -WebInspector.ColorPicker.Event = { - ColorChanged: "css-color-picker-color-changed" -}; - -WebInspector.ColorPicker.prototype = { - contructor: WebInspector.ColorPicker, - __proto__: WebInspector.Object.prototype, - - // Public - - get element() - { - return this._element; - }, - - set brightness(brightness) - { - if (brightness === this._brightness) - return; - - this._colorWheel.brightness = brightness; - - this._updateColor(); - this._updateSliders(this._colorWheel.rawColor, this._colorWheel.tintedColor); - }, - - set opacity(opacity) - { - if (opacity === this._opacity) - return; - - this._opacity = opacity; - this._updateColor(); - }, - - get color() - { - return this._color; - }, - - set color(color) - { - this._dontUpdateColor = true; - - this._colorFormat = color.format; - - this._colorWheel.tintedColor = color; - this._brightnessSlider.value = this._colorWheel.brightness; - - this._opacitySlider.value = color.alpha; - this._updateSliders(this._colorWheel.rawColor, color); - - delete this._dontUpdateColor; - }, - - colorWheelColorDidChange: function(colorWheel) - { - this._updateColor(); - this._updateSliders(this._colorWheel.rawColor, this._colorWheel.tintedColor); - }, - - sliderValueDidChange: function(slider, value) - { - if (slider === this._opacitySlider) - this.opacity = value; - else if (slider === this._brightnessSlider) - this.brightness = value; - }, - - // Private - - _updateColor: function() - { - if (this._dontUpdateColor) - return; - - var opacity = Math.round(this._opacity * 100) / 100; - var rgba = this._colorWheel.tintedColor.rgb.concat(opacity); - this._color = new WebInspector.Color(WebInspector.Color.Format.RGBA, rgba).toString(this._colorFormat); - this.dispatchEventToListeners(WebInspector.ColorPicker.Event.ColorChanged, {color: this._color}); - }, - - _updateSliders: function(rawColor, tintedColor) - { - var rgba = this._colorWheel.tintedColor.rgb.concat(0); - var transparent = new WebInspector.Color(WebInspector.Color.Format.RGBA, rgba).toString(); - - this._opacitySlider.element.style.backgroundImage = "linear-gradient(90deg, " + transparent + ", " + tintedColor + "), " + this._opacityPattern; - this._brightnessSlider.element.style.backgroundImage = "linear-gradient(90deg, black, " + rawColor + ")"; - } -}; diff --git a/Source/WebInspectorUI/UserInterface/ColorWheel.css b/Source/WebInspectorUI/UserInterface/ColorWheel.css deleted file mode 100644 index 541663d0b..000000000 --- a/Source/WebInspectorUI/UserInterface/ColorWheel.css +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.color-wheel { - position: relative; -} - -.color-wheel > .crosshair { - position: absolute; - top: -4px; - left: -3px; - width: 5px; - height: 5px; - border: 1px solid black; - border-radius: 3px; - pointer-events: none; - background-color: white; -} diff --git a/Source/WebInspectorUI/UserInterface/ColorWheel.js b/Source/WebInspectorUI/UserInterface/ColorWheel.js deleted file mode 100644 index fd1570098..000000000 --- a/Source/WebInspectorUI/UserInterface/ColorWheel.js +++ /dev/null @@ -1,282 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ColorWheel = function() -{ - WebInspector.Object.call(this); - - this._rawCanvas = document.createElement("canvas"); - this._tintedCanvas = document.createElement("canvas"); - this._finalCanvas = document.createElement("canvas"); - - this._crosshair = document.createElement("div"); - this._crosshair.className = "crosshair"; - - this._element = document.createElement("div"); - this._element.className = "color-wheel"; - - this._element.appendChild(this._finalCanvas); - this._element.appendChild(this._crosshair); - - this._finalCanvas.addEventListener("mousedown", this); -} - -WebInspector.ColorWheel.prototype = { - contructor: WebInspector.ColorWheel, - __proto__: WebInspector.Object.prototype, - - // Public - - set dimension(dimension) - { - this._finalCanvas.width = this._tintedCanvas.width = this._rawCanvas.width = dimension; - this._finalCanvas.height = this._tintedCanvas.height = this._rawCanvas.height = dimension; - - this._dimension = dimension; - // We shrink the radius a bit for better anti-aliasing. - this._radius = dimension / 2 - 2; - - this._setCrosshairPosition(new WebInspector.Point(dimension / 2, dimension / 2)); - - this._drawRawCanvas(); - this._draw(); - }, - - get element() - { - return this._element; - }, - - get brightness() - { - return this._brightness; - }, - - set brightness(brightness) - { - this._brightness = brightness; - this._draw(); - }, - - get tintedColor() - { - if (this._crosshairPosition) - return this._colorAtPointWithBrightness(this._crosshairPosition.x, this._crosshairPosition.y, this._brightness); - - return new WebInspector.Color(WebInspector.Color.Format.RGBA, [0, 0, 0, 0]); - }, - - set tintedColor(tintedColor) - { - var data = this._tintedColorToPointAndBrightness(tintedColor); - this._setCrosshairPosition(data.point); - this.brightness = data.brightness; - }, - - get rawColor() - { - if (this._crosshairPosition) - return this._colorAtPointWithBrightness(this._crosshairPosition.x, this._crosshairPosition.y, 1); - - return new WebInspector.Color(WebInspector.Color.Format.RGBA, [0, 0, 0, 0]); - }, - - // Protected - - handleEvent: function(event) - { - switch (event.type) { - case "mousedown": - this._handleMousedown(event); - break; - case "mousemove": - this._handleMousemove(event); - break; - case "mouseup": - this._handleMouseup(event); - break; - } - }, - - // Private - - _handleMousedown: function(event) - { - window.addEventListener("mousemove", this, true); - window.addEventListener("mouseup", this, true); - - this._updateColorForMouseEvent(event); - }, - - _handleMousemove: function(event) - { - this._updateColorForMouseEvent(event); - }, - - _handleMouseup: function(event) - { - window.removeEventListener("mousemove", this, true); - window.removeEventListener("mouseup", this, true); - }, - - _pointInCircleForEvent: function(event) - { - function distance(a, b) - { - return Math.sqrt(Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2)); - } - - function angleFromCenterToPoint(center, point) - { - return Math.atan2(point.y - center.y, point.x - center.x); - } - - function pointOnCircumference(c, r, a) - { - return new WebInspector.Point(c.x + r * Math.cos(a), c.y + r * Math.sin(a)); - } - - var dimension = this._dimension; - var point = window.webkitConvertPointFromPageToNode(this._finalCanvas, new WebKitPoint(event.pageX, event.pageY)); - var center = new WebInspector.Point(dimension / 2, dimension / 2); - if (distance(point, center) > this._radius) { - var angle = angleFromCenterToPoint(center, point); - point = pointOnCircumference(center, this._radius, angle); - } - return point; - }, - - _updateColorForMouseEvent: function(event) - { - var point = this._pointInCircleForEvent(event); - - this._setCrosshairPosition(point); - - if (this.delegate && typeof this.delegate.colorWheelColorDidChange === "function") - this.delegate.colorWheelColorDidChange(this); - }, - - _setCrosshairPosition: function(point) - { - this._crosshairPosition = point; - this._crosshair.style.webkitTransform = "translate(" + Math.round(point.x) + "px, " + Math.round(point.y) + "px)"; - }, - - _tintedColorToPointAndBrightness: function(color) - { - var rgb = color.rgb; - var hsv = WebInspector.Color.rgb2hsv(rgb[0], rgb[1], rgb[2]); - var cosHue = Math.cos(hsv[0] * Math.PI / 180); - var sinHue = Math.sin(hsv[0] * Math.PI / 180); - var center = this._dimension / 2; - var x = center + (center * cosHue * hsv[1]); - var y = center - (center * sinHue * hsv[1]); - return { - point: new WebInspector.Point(x, y), - brightness: hsv[2] - }; - }, - - _drawRawCanvas: function() { - var ctx = this._rawCanvas.getContext("2d"); - - var dimension = this._dimension; - var center = dimension / 2; - - ctx.fillStyle = "white"; - ctx.fillRect(0, 0, dimension, dimension); - - var imageData = ctx.getImageData(0, 0, dimension, dimension); - var data = imageData.data; - for (var j = 0; j < dimension; ++j) { - for (var i = 0; i < dimension; ++i) { - var color = this._colorAtPointWithBrightness(i, j, 1); - if (!color) - continue; - var pos = (j * dimension + i) * 4; - data[pos] = color.rgb[0]; - data[pos + 1] = color.rgb[1]; - data[pos + 2] = color.rgb[2]; - } - } - ctx.putImageData(imageData, 0, 0); - }, - - _colorAtPointWithBrightness: function(x, y, brightness) - { - var center = this._dimension / 2; - var xDis = x - center; - var yDis = y - center; - var distance = Math.sqrt(xDis * xDis + yDis * yDis); - - if (distance - center > 0.001) - return new WebInspector.Color(WebInspector.Color.Format.RGBA, [0, 0, 0, 0]); - - var h = Math.atan2(y - center, center - x) * 180 / Math.PI; - h = (h + 180) % 360; - var v = brightness; - var s = Math.max(0, distance) / center; - - var rgb = WebInspector.Color.hsv2rgb(h, s, v); - return new WebInspector.Color(WebInspector.Color.Format.RGBA, [ - Math.round(rgb[0] * 255), - Math.round(rgb[1] * 255), - Math.round(rgb[2] * 255), - 1 - ]); - }, - - _drawTintedCanvas: function() - { - var ctx = this._tintedCanvas.getContext("2d"); - var dimension = this._dimension; - - ctx.save(); - ctx.drawImage(this._rawCanvas, 0, 0, dimension, dimension); - if (this._brightness !== 1) { - ctx.globalAlpha = 1 - this._brightness; - ctx.fillStyle = "black"; - ctx.fillRect(0, 0, dimension, dimension); - } - ctx.restore(); - }, - - _draw: function() - { - this._drawTintedCanvas(); - - var ctx = this._finalCanvas.getContext("2d"); - var dimension = this._dimension; - - ctx.save(); - ctx.clearRect(0, 0, dimension, dimension); - ctx.beginPath(); - ctx.arc(dimension / 2, dimension / 2, this._radius + 1, 0, Math.PI * 2, true); - ctx.closePath(); - ctx.clip(); - ctx.drawImage(this._tintedCanvas, 0, 0, dimension, dimension); - ctx.restore(); - } -}; diff --git a/Source/WebInspectorUI/UserInterface/CompletionSuggestionsView.css b/Source/WebInspectorUI/UserInterface/CompletionSuggestionsView.css deleted file mode 100644 index bdbd313b4..000000000 --- a/Source/WebInspectorUI/UserInterface/CompletionSuggestionsView.css +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.completion-suggestions { - position: absolute; - display: block; - - background-color: rgba(255, 255, 255, 0.9); - border-radius: 5px; - - z-index: 100; - - margin-top: -1px; - margin-left: -10px; - - box-shadow: rgba(0, 0, 0, 0.25) 0 5px 10px, rgba(0, 0, 0, 0.15) 0 0 0 1px; -} - -.completion-suggestions > .completion-suggestions-container { - position: absolute; - top: 0; - left: 0; - right: 0; - bottom: 0; - - overflow-x: hidden; - overflow-y: auto; - - border-radius: 5px; -} - -.completion-suggestions-container > .item { - padding: 1px 10px; - margin: 0; - - font-size: 11px; - font-family: Menlo, monospace; - - line-height: 16px; - height: 16px; - - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; - - color: black; -} - -.completion-suggestions-container:not(:active) > .item.selected, -.completion-suggestions-container > .item:active { - box-shadow: inset rgb(87, 152, 206) 0 1px 0; - background: -webkit-linear-gradient(top, rgb(110, 167, 216), rgb(36, 114, 181)); - - color: white; - text-shadow: rgb(51, 88, 123) 0 1px 0; -} diff --git a/Source/WebInspectorUI/UserInterface/CompletionSuggestionsView.js b/Source/WebInspectorUI/UserInterface/CompletionSuggestionsView.js deleted file mode 100644 index ce4c9c3ec..000000000 --- a/Source/WebInspectorUI/UserInterface/CompletionSuggestionsView.js +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.CompletionSuggestionsView = function(delegate) -{ - WebInspector.Object.call(this); - - this._delegate = delegate || null; - - this._selectedIndex = NaN; - - this._element = document.createElement("div"); - this._element.className = WebInspector.CompletionSuggestionsView.StyleClassName; - - this._containerElement = document.createElement("div"); - this._containerElement.className = WebInspector.CompletionSuggestionsView.ContainerElementStyleClassName; - this._containerElement.addEventListener("mousedown", this._mouseDown.bind(this)); - this._containerElement.addEventListener("mouseup", this._mouseUp.bind(this)); - this._containerElement.addEventListener("click", this._itemClicked.bind(this)); - this._element.appendChild(this._containerElement); -}; - -WebInspector.CompletionSuggestionsView.StyleClassName = "completion-suggestions"; -WebInspector.CompletionSuggestionsView.ContainerElementStyleClassName = "completion-suggestions-container"; -WebInspector.CompletionSuggestionsView.ItemElementStyleClassName = "item"; -WebInspector.CompletionSuggestionsView.SelectedItemStyleClassName = "selected"; - -WebInspector.CompletionSuggestionsView.prototype = { - constructor: WebInspector.CompletionSuggestionsView, - - // Public - - get delegate() - { - return this._delegate; - }, - - get visible() - { - return !!this._element.parentNode; - }, - - get selectedIndex() - { - return this._selectedIndex; - }, - - set selectedIndex(index) - { - var selectedItemElement = this._selectedItemElement; - if (selectedItemElement) - selectedItemElement.classList.remove(WebInspector.CompletionSuggestionsView.SelectedItemStyleClassName); - - this._selectedIndex = index; - - selectedItemElement = this._selectedItemElement; - if (!selectedItemElement) - return; - - selectedItemElement.classList.add(WebInspector.CompletionSuggestionsView.SelectedItemStyleClassName); - selectedItemElement.scrollIntoViewIfNeeded(false); - }, - - selectNext: function() - { - var count = this._containerElement.children.length; - - if (isNaN(this._selectedIndex) || this._selectedIndex === count - 1) - this.selectedIndex = 0; - else - ++this.selectedIndex; - - var selectedItemElement = this._selectedItemElement; - if (selectedItemElement && this._delegate && typeof this._delegate.completionSuggestionsSelectedCompletion === "function") - this._delegate.completionSuggestionsSelectedCompletion(this, selectedItemElement.textContent); - }, - - selectPrevious: function() - { - if (isNaN(this._selectedIndex) || this._selectedIndex === 0) - this.selectedIndex = this._containerElement.children.length - 1; - else - --this.selectedIndex; - - var selectedItemElement = this._selectedItemElement; - if (selectedItemElement && this._delegate && typeof this._delegate.completionSuggestionsSelectedCompletion === "function") - this._delegate.completionSuggestionsSelectedCompletion(this, selectedItemElement.textContent); - }, - - isHandlingClickEvent: function() - { - return this._mouseIsDown; - }, - - show: function(anchorBounds) - { - // Measure the container so we can know the intrinsic size of the items. - this._containerElement.style.position = "absolute"; - document.body.appendChild(this._containerElement); - - var containerWidth = this._containerElement.offsetWidth; - var containerHeight = this._containerElement.offsetHeight; - - this._containerElement.removeAttribute("style"); - this._element.appendChild(this._containerElement); - - // Lay out the suggest-box relative to the anchorBounds. - const margin = 10; - const horizontalPadding = 22; - const absoluteMaximumHeight = 160; - - var x = anchorBounds.origin.x; - var y = anchorBounds.origin.y + anchorBounds.size.height; - - var maximumWidth = window.innerWidth - anchorBounds.origin.x - margin; - var width = Math.min(containerWidth, maximumWidth - horizontalPadding) + horizontalPadding; - var paddedWidth = containerWidth + horizontalPadding; - - if (width < paddedWidth) { - // Shift the suggest box to the left to accommodate the content without trimming to the BODY edge. - maximumWidth = window.innerWidth - margin; - width = Math.min(containerWidth, maximumWidth - horizontalPadding) + horizontalPadding; - x = document.body.offsetWidth - width; - } - - var aboveHeight = anchorBounds.origin.y; - var underHeight = window.innerHeight - anchorBounds.origin.y - anchorBounds.size.height; - var maximumHeight = Math.min(absoluteMaximumHeight, Math.max(underHeight, aboveHeight) - margin); - var height = Math.min(containerHeight, maximumHeight); - - // Position the suggestions below the anchor. If there is no room, position the suggestions above. - if (underHeight - height < 0) - y = aboveHeight - height; - - this._element.style.left = x + "px"; - this._element.style.top = y + "px"; - this._element.style.width = width + "px"; - this._element.style.height = height + "px"; - - document.body.appendChild(this._element); - }, - - hide: function() - { - this._element.remove(); - }, - - update: function(completions, selectedIndex) - { - this._containerElement.removeChildren(); - - if (typeof selectedIndex === "number") - this._selectedIndex = selectedIndex; - - for (var i = 0; i < completions.length; ++i) { - var itemElement = document.createElement("div"); - itemElement.className = WebInspector.CompletionSuggestionsView.ItemElementStyleClassName; - itemElement.textContent = completions[i]; - if (i === this._selectedIndex) - itemElement.classList.add(WebInspector.CompletionSuggestionsView.SelectedItemStyleClassName); - this._containerElement.appendChild(itemElement); - } - }, - - // Private - - get _selectedItemElement() - { - if (isNaN(this._selectedIndex)) - return null; - - var element = this._containerElement.children[this._selectedIndex] || null; - console.assert(element); - return element; - }, - - _mouseDown: function(event) - { - if (event.button !== 0) - return; - this._mouseIsDown = true; - }, - - _mouseUp: function(event) - { - if (event.button !== 0) - return; - this._mouseIsDown = false; - }, - - _itemClicked: function(event) - { - if (event.button !== 0) - return; - - var itemElement = event.target.enclosingNodeOrSelfWithClass(WebInspector.CompletionSuggestionsView.ItemElementStyleClassName); - console.assert(itemElement); - if (!itemElement) - return; - - if (this._delegate && typeof this._delegate.completionSuggestionsClickedCompletion === "function") - this._delegate.completionSuggestionsClickedCompletion(this, itemElement.textContent); - } -}; - -WebInspector.CompletionSuggestionsView.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ComputedStyleDetailsPanel.css b/Source/WebInspectorUI/UserInterface/ComputedStyleDetailsPanel.css deleted file mode 100644 index 1d0a58e11..000000000 --- a/Source/WebInspectorUI/UserInterface/ComputedStyleDetailsPanel.css +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (C) 2013 Adobe Systems Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.details-section > .content > .group > .row.simple.content-flow-link > .value > span > .icon { - width: 12px; - height: 12px; - content: url(Images/ContentFlow.svg); - margin-right: 4px; - -webkit-user-select: none; -} - -.details-section > .content > .group > .row.simple.content-flow-link span -{ - vertical-align: top; -} diff --git a/Source/WebInspectorUI/UserInterface/ComputedStyleDetailsPanel.js b/Source/WebInspectorUI/UserInterface/ComputedStyleDetailsPanel.js deleted file mode 100644 index 9a5626fd4..000000000 --- a/Source/WebInspectorUI/UserInterface/ComputedStyleDetailsPanel.js +++ /dev/null @@ -1,219 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ComputedStyleDetailsPanel = function() -{ - WebInspector.StyleDetailsPanel.call(this, WebInspector.ComputedStyleDetailsPanel.StyleClassName, "computed", WebInspector.UIString("Computed")); - - this._computedStyleShowAllSetting = new WebInspector.Setting("computed-style-show-all", false); - - var computedStyleShowAllLabel = document.createElement("label"); - computedStyleShowAllLabel.textContent = WebInspector.UIString("Show All"); - - this._computedStyleShowAllCheckbox = document.createElement("input"); - this._computedStyleShowAllCheckbox.type = "checkbox"; - this._computedStyleShowAllCheckbox.checked = this._computedStyleShowAllSetting.value; - this._computedStyleShowAllCheckbox.addEventListener("change", this._computedStyleShowAllCheckboxValueChanged.bind(this)); - computedStyleShowAllLabel.appendChild(this._computedStyleShowAllCheckbox); - - this._propertiesTextEditor = new WebInspector.CSSStyleDeclarationTextEditor(this); - this._propertiesTextEditor.showsImplicitProperties = this._computedStyleShowAllSetting.value; - this._propertiesTextEditor.alwaysShowPropertyNames = ["display", "width", "height"]; - this._propertiesTextEditor.sortProperties = true; - - var propertiesRow = new WebInspector.DetailsSectionRow; - var propertiesGroup = new WebInspector.DetailsSectionGroup([propertiesRow]); - var propertiesSection = new WebInspector.DetailsSection("computed-style-properties", WebInspector.UIString("Properties"), [propertiesGroup], computedStyleShowAllLabel); - - propertiesRow.element.appendChild(this._propertiesTextEditor.element); - - // Region flow name is used to display the "flow-from" property of the Region Containers. - this._regionFlowFragment = document.createElement("span"); - this._regionFlowFragment.appendChild(document.createElement("img")).className = "icon"; - this._regionFlowNameLabelValue = this._regionFlowFragment.appendChild(document.createElement("span")); - - var goToRegionFlowButton = this._regionFlowFragment.appendChild(WebInspector.createGoToArrowButton()); - goToRegionFlowButton.addEventListener("click", this._goToRegionFlowArrowWasClicked.bind(this)); - - this._regionFlowNameRow = new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("Region Flow")); - this._regionFlowNameRow.element.classList.add("content-flow-link"); - - // Content flow name is used to display the "flow-into" property of the Content nodes. - this._contentFlowFragment = document.createElement("span"); - this._contentFlowFragment.appendChild(document.createElement("img")).className = "icon"; - this._contentFlowNameLabelValue = this._contentFlowFragment.appendChild(document.createElement("span")); - - var goToContentFlowButton = this._contentFlowFragment.appendChild(WebInspector.createGoToArrowButton()); - goToContentFlowButton.addEventListener("click", this._goToContentFlowArrowWasClicked.bind(this)); - - this._contentFlowNameRow = new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("Content Flow")); - this._contentFlowNameRow.element.classList.add("content-flow-link"); - - var flowNamesGroup = new WebInspector.DetailsSectionGroup([this._regionFlowNameRow, this._contentFlowNameRow]); - this._flowNamesSection = new WebInspector.DetailsSection("content-flow", WebInspector.UIString("Flows"), [flowNamesGroup]); - - this._containerRegionsDataGrid = new WebInspector.DOMTreeDataGrid; - this._containerRegionsDataGrid.element.classList.add("no-header"); - - var containerRegionsRow = new WebInspector.DetailsSectionDataGridRow(this._containerRegionsDataGrid); - var containerRegionsGroup = new WebInspector.DetailsSectionGroup([containerRegionsRow]); - this._containerRegionsFlowSection = new WebInspector.DetailsSection("container-regions", WebInspector.UIString("Container Regions"), [containerRegionsGroup]); - - this.element.appendChild(propertiesSection.element); - this.element.appendChild(this._flowNamesSection.element); - this.element.appendChild(this._containerRegionsFlowSection.element); - - this._resetFlowDetails(); -}; - -WebInspector.ComputedStyleDetailsPanel.StyleClassName = "computed"; - -WebInspector.ComputedStyleDetailsPanel.prototype = { - constructor: WebInspector.ComputedStyleDetailsPanel, - - // Public - - get regionFlow() - { - return this._regionFlow; - }, - - set regionFlow(regionFlow) - { - this._regionFlow = regionFlow; - this._regionFlowNameLabelValue.textContent = regionFlow ? regionFlow.name : ""; - this._regionFlowNameRow.value = regionFlow ? this._regionFlowFragment : null; - this._updateFlowNamesSectionVisibility(); - }, - - get contentFlow() - { - return this._contentFlow; - }, - - set contentFlow(contentFlow) - { - this._contentFlow = contentFlow; - this._contentFlowNameLabelValue.textContent = contentFlow ? contentFlow.name : ""; - this._contentFlowNameRow.value = contentFlow ? this._contentFlowFragment : null; - this._updateFlowNamesSectionVisibility(); - }, - - get containerRegions() - { - return this._containerRegions; - }, - - set containerRegions(regions) - { - this._containerRegions = regions; - - if (!regions || !regions.length) { - this._containerRegionsFlowSection.element.classList.add("hidden"); - return; - } - - this._containerRegionsDataGrid.removeChildren(); - for (var regionNode of regions) - this._containerRegionsDataGrid.appendChild(new WebInspector.DOMTreeDataGridNode(regionNode)); - - this._containerRegionsFlowSection.element.classList.remove("hidden"); - }, - - refresh: function() - { - this._propertiesTextEditor.style = this.nodeStyles.computedStyle; - this._refreshFlowDetails(this.nodeStyles.node); - }, - - // Protected - - shown: function() - { - WebInspector.StyleDetailsPanel.prototype.shown.call(this); - - this._propertiesTextEditor.updateLayout(); - }, - - widthDidChange: function() - { - this._propertiesTextEditor.updateLayout(); - }, - - // Private - - _computedStyleShowAllCheckboxValueChanged: function(event) - { - var checked = this._computedStyleShowAllCheckbox.checked; - this._computedStyleShowAllSetting.value = checked; - this._propertiesTextEditor.showsImplicitProperties = checked; - }, - - _updateFlowNamesSectionVisibility: function() - { - this._flowNamesSection.element.classList.toggle("hidden", !this._contentFlow && !this._regionFlow); - }, - - _resetFlowDetails : function() - { - this.regionFlow = null; - this.contentFlow = null; - this.containerRegions = null; - }, - - _refreshFlowDetails: function(domNode) - { - this._resetFlowDetails(); - if (!domNode) - return; - - function contentFlowInfoReady(error, flowData) - { - // Element is not part of any flow. - if (error || !flowData) { - this._resetFlowDetails(); - return; - } - - this.regionFlow = flowData.regionFlow; - this.contentFlow = flowData.contentFlow; - this.containerRegions = flowData.regions; - } - - WebInspector.domTreeManager.getNodeContentFlowInfo(domNode, contentFlowInfoReady.bind(this)); - }, - - _goToRegionFlowArrowWasClicked: function() - { - WebInspector.resourceSidebarPanel.showContentFlowDOMTree(this._regionFlow); - }, - - _goToContentFlowArrowWasClicked: function() - { - WebInspector.resourceSidebarPanel.showContentFlowDOMTree(this._contentFlow, this.nodeStyles.node, true); - } -}; - -WebInspector.ComputedStyleDetailsPanel.prototype.__proto__ = WebInspector.StyleDetailsPanel.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ConsoleCommand.js b/Source/WebInspectorUI/UserInterface/ConsoleCommand.js deleted file mode 100644 index 95b24c28e..000000000 --- a/Source/WebInspectorUI/UserInterface/ConsoleCommand.js +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (C) 2007, 2008, 2013 Apple Inc. All rights reserved. - * Copyright (C) 2009 Joseph Pecoraro - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ConsoleCommand = function(command) -{ - WebInspector.Object.call(this); - - this.command = command; -}; - -WebInspector.ConsoleCommand.prototype = { - constructor: WebInspector.ConsoleCommand, - - // Public - - clearHighlight: function() - { - var highlightedMessage = this._formattedCommand; - delete this._formattedCommand; - this._formatCommand(); - this._element.replaceChild(this._formattedCommand, highlightedMessage); - }, - - highlightSearchResults: function(regexObject) - { - regexObject.lastIndex = 0; - var text = this.command; - var match = regexObject.exec(text); - var offset = 0; - var matchRanges = []; - while (match) { - matchRanges.push({ offset: match.index, length: match[0].length }); - match = regexObject.exec(text); - } - highlightSearchResults(this._formattedCommand, matchRanges); - this._element.scrollIntoViewIfNeeded(); - }, - - matchesRegex: function(regexObject) - { - return regexObject.test(this.command); - }, - - toMessageElement: function() - { - if (!this._element) { - this._element = document.createElement("div"); - this._element.command = this; - this._element.className = "console-user-command"; - this._element.setAttribute("data-labelprefix", WebInspector.UIString("Input: ")); - - this._formatCommand(); - this._element.appendChild(this._formattedCommand); - } - return this._element; - }, - - // Private - - _formatCommand: function() - { - this._formattedCommand = document.createElement("span"); - this._formattedCommand.className = "console-message-text source-code"; - this._formattedCommand.textContent = this.command; - }, - - toClipboardString: function(isPrefixOptional) - { - return (isPrefixOptional ? "" : "> ") + this.command; - } -}; - -WebInspector.ConsoleCommand.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ConsoleCommandResult.js b/Source/WebInspectorUI/UserInterface/ConsoleCommandResult.js deleted file mode 100644 index 2c2e2bd43..000000000 --- a/Source/WebInspectorUI/UserInterface/ConsoleCommandResult.js +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (C) 2007, 2008, 2013 Apple Inc. All rights reserved. - * Copyright (C) 2009 Joseph Pecoraro - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ConsoleCommandResult = function(result, wasThrown, originatingCommand) -{ - var level = (wasThrown ? WebInspector.ConsoleMessage.MessageLevel.Error : WebInspector.ConsoleMessage.MessageLevel.Log); - this.originatingCommand = originatingCommand; - - WebInspector.ConsoleMessageImpl.call(this, WebInspector.ConsoleMessage.MessageSource.JS, level, "", null, WebInspector.ConsoleMessage.MessageType.Result, undefined, undefined, undefined, undefined, [result]); -}; - -WebInspector.ConsoleCommandResult.prototype = { - constructor: WebInspector.ConsoleCommandResult, - - // Public - - enforcesClipboardPrefixString: false, - - toMessageElement: function() - { - var element = WebInspector.ConsoleMessageImpl.prototype.toMessageElement.call(this); - element.classList.add("console-user-command-result"); - if (!element.getAttribute("data-labelprefix")) - element.setAttribute("data-labelprefix", WebInspector.UIString("Output: ")); - return element; - }, - - get clipboardPrefixString() - { - return "< "; - } -}; - -WebInspector.ConsoleCommandResult.prototype.__proto__ = WebInspector.ConsoleMessageImpl.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ConsoleGroup.js b/Source/WebInspectorUI/UserInterface/ConsoleGroup.js deleted file mode 100644 index 901e1b193..000000000 --- a/Source/WebInspectorUI/UserInterface/ConsoleGroup.js +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (C) 2007, 2008, 2013 Apple Inc. All rights reserved. - * Copyright (C) 2009 Joseph Pecoraro - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ConsoleGroup = function(parentGroup, isNewSession) -{ - WebInspector.Object.call(this); - - this.parentGroup = parentGroup; - - var element = document.createElement("div"); - element.className = "console-group"; - element.group = this; - this.element = element; - - if (isNewSession) - element.classList.add("new-session"); - - var messagesElement = document.createElement("div"); - messagesElement.className = "console-group-messages"; - element.appendChild(messagesElement); - this.messagesElement = messagesElement; -}; - -WebInspector.ConsoleGroup.prototype = { - constructor: WebInspector.ConsoleGroup, - - // Public - - addMessage: function(msg) - { - var element = msg.toMessageElement(); - - var wrapper = document.createElement("div"); - wrapper.className = WebInspector.LogContentView.ItemWrapperStyleClassName; - wrapper.messageElement = wrapper.appendChild(element); - - if (msg.type === WebInspector.ConsoleMessage.MessageType.StartGroup || msg.type === WebInspector.ConsoleMessage.MessageType.StartGroupCollapsed) { - this.messagesElement.parentNode.insertBefore(wrapper, this.messagesElement); - element.addEventListener("click", this._titleClicked.bind(this)); - element.addEventListener("mousedown", this._titleMouseDown.bind(this)); - var groupElement = element.enclosingNodeOrSelfWithClass("console-group"); - if (groupElement && msg.type === WebInspector.ConsoleMessage.MessageType.StartGroupCollapsed) - groupElement.classList.add("collapsed"); - } else - this.messagesElement.appendChild(wrapper); - }, - - hasMessages: function() - { - return !!this.messagesElement.childNodes.length; - }, - - // Private - - _titleMouseDown: function(event) - { - event.preventDefault(); - }, - - _titleClicked: function(event) - { - var groupTitleElement = event.target.enclosingNodeOrSelfWithClass("console-group-title"); - if (groupTitleElement) { - var groupElement = groupTitleElement.enclosingNodeOrSelfWithClass("console-group"); - if (groupElement) - if (groupElement.classList.contains("collapsed")) - groupElement.classList.remove("collapsed"); - else - groupElement.classList.add("collapsed"); - groupTitleElement.scrollIntoViewIfNeeded(true); - } - } -}; - -WebInspector.ConsoleGroup.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ConsoleMessage.js b/Source/WebInspectorUI/UserInterface/ConsoleMessage.js deleted file mode 100644 index 718865712..000000000 --- a/Source/WebInspectorUI/UserInterface/ConsoleMessage.js +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright (C) 2011 Google Inc. All rights reserved. - * Copyright (C) 2007, 2008, 2013 Apple Inc. All rights reserved. - * Copyright (C) 2009 Joseph Pecoraro - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ConsoleMessage = function(source, level, url, line, column, repeatCount) -{ - this.source = source; - this.level = level; - this.url = url || null; - this.line = line || 0; - this.column = column || 0; - - repeatCount = repeatCount || 1; - this.repeatCount = repeatCount; - this.repeatDelta = repeatCount; - this.totalRepeatCount = repeatCount; -} - -WebInspector.ConsoleMessage.prototype = { - /** - * @return {boolean} - */ - isErrorOrWarning: function() - { - return (this.level === WebInspector.ConsoleMessage.MessageLevel.Warning || this.level === WebInspector.ConsoleMessage.MessageLevel.Error); - }, - - updateRepeatCount: function() - { - // Implemented by concrete instances - }, - - /** - * @return {WebInspector.ConsoleMessage} - */ - clone: function() - { - // Implemented by concrete instances - } -} - -/** - * @param {string} source - * @param {string} level - * @param {string} message - * @param {string=} type - * @param {string=} url - * @param {number=} line - * @param {number=} repeatCount - * @param {Array.=} parameters - * @param {ConsoleAgent.StackTrace=} stackTrace - * @param {WebInspector.Resource=} request - * - * @return {WebInspector.ConsoleMessage} - */ -WebInspector.ConsoleMessage.create = function(source, level, message, type, url, line, column, repeatCount, parameters, stackTrace, request) -{ - return new WebInspector.ConsoleMessageImpl(source, level, message, null, type, url, line, column, repeatCount, parameters, stackTrace, request); -} - -// Note: Keep these constants in sync with the ones in Console.h -WebInspector.ConsoleMessage.MessageSource = { - HTML: "html", - XML: "xml", - JS: "javascript", - Network: "network", - ConsoleAPI: "console-api", - Other: "other" -}; - -WebInspector.ConsoleMessage.MessageType = { - Log: "log", - Dir: "dir", - DirXML: "dirxml", - Trace: "trace", - StartGroup: "startGroup", - StartGroupCollapsed: "startGroupCollapsed", - EndGroup: "endGroup", - Assert: "assert", - Result: "result" -}; - -WebInspector.ConsoleMessage.MessageLevel = { - Tip: "tip", - Log: "log", - Warning: "warning", - Error: "error", - Debug: "debug" -}; diff --git a/Source/WebInspectorUI/UserInterface/ConsoleMessageImpl.js b/Source/WebInspectorUI/UserInterface/ConsoleMessageImpl.js deleted file mode 100644 index a61ffc260..000000000 --- a/Source/WebInspectorUI/UserInterface/ConsoleMessageImpl.js +++ /dev/null @@ -1,714 +0,0 @@ -/* - * Copyright (C) 2011 Google Inc. All rights reserved. - * Copyright (C) 2007, 2008, 2013 Apple Inc. All rights reserved. - * Copyright (C) 2009 Joseph Pecoraro - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ConsoleMessageImpl = function(source, level, message, linkifier, type, url, line, column, repeatCount, parameters, stackTrace, request) -{ - WebInspector.ConsoleMessage.call(this, source, level, url, line, column, repeatCount); - - this._linkifier = linkifier; - this.type = type || WebInspector.ConsoleMessage.MessageType.Log; - this._messageText = message; - this._parameters = parameters; - this._stackTrace = stackTrace; - this._request = request; - - this._customFormatters = { - "object": this._formatParameterAsObject, - "array": this._formatParameterAsArray, - "node": this._formatParameterAsNode, - "string": this._formatParameterAsString - }; -} - -WebInspector.ConsoleMessageImpl.prototype = { - - enforcesClipboardPrefixString: true, - - _formatMessage: function() - { - this._formattedMessage = document.createElement("span"); - this._formattedMessage.className = "console-message-text source-code"; - - var messageText; - if (this.source === WebInspector.ConsoleMessage.MessageSource.ConsoleAPI) { - switch (this.type) { - case WebInspector.ConsoleMessage.MessageType.Trace: - messageText = document.createTextNode("console.trace()"); - break; - case WebInspector.ConsoleMessage.MessageType.Assert: - var args = [WebInspector.UIString("Assertion failed:")]; - if (this._parameters) - args = args.concat(this._parameters); - messageText = this._format(args); - break; - case WebInspector.ConsoleMessage.MessageType.Dir: - var obj = this._parameters ? this._parameters[0] : undefined; - var args = ["%O", obj]; - messageText = this._format(args); - break; - default: - var args = this._parameters || [this._messageText]; - messageText = this._format(args); - } - } else if (this.source === WebInspector.ConsoleMessage.MessageSource.Network) { - if (this._request) { - this._stackTrace = this._request.stackTrace; - if (this._request.initiator && this._request.initiator.url) { - this.url = this._request.initiator.url; - this.line = this._request.initiator.lineNumber; - } - messageText = document.createElement("span"); - if (this.level === WebInspector.ConsoleMessage.MessageLevel.Error) { - messageText.appendChild(document.createTextNode(this._request.requestMethod + " ")); - messageText.appendChild(WebInspector.linkifyRequestAsNode(this._request)); - if (this._request.failed) - messageText.appendChild(document.createTextNode(" " + this._request.localizedFailDescription)); - else - messageText.appendChild(document.createTextNode(" " + this._request.statusCode + " (" + this._request.statusText + ")")); - } else { - var fragment = WebInspector.linkifyStringAsFragmentWithCustomLinkifier(this._messageText, WebInspector.linkifyRequestAsNode.bind(null, this._request, "")); - messageText.appendChild(fragment); - } - } else { - if (this.url) { - var anchor = WebInspector.linkifyURLAsNode(this.url, this.url, "console-message-url"); - this._formattedMessage.appendChild(anchor); - } - messageText = this._format([this._messageText]); - } - } else { - var args = this._parameters || [this._messageText]; - messageText = this._format(args); - } - - if (this.source !== WebInspector.ConsoleMessage.MessageSource.Network || this._request) { - if (this._stackTrace && this._stackTrace.length && this._stackTrace[0].url) { - var urlElement = this._linkifyCallFrame(this._stackTrace[0]); - this._formattedMessage.appendChild(urlElement); - } else if (this.url && this.url !== "undefined") { - var urlElement = this._linkifyLocation(this.url, this.line, this.column); - this._formattedMessage.appendChild(urlElement); - } - } - - this._formattedMessage.appendChild(messageText); - - if (this._shouldDumpStackTrace()) { - var ol = document.createElement("ol"); - ol.className = "outline-disclosure"; - var treeOutline = new TreeOutline(ol); - - var content = this._formattedMessage; - var root = new TreeElement(content, null, true); - content.treeElementForTest = root; - treeOutline.appendChild(root); - if (this.type === WebInspector.ConsoleMessage.MessageType.Trace) - root.expand(); - - this._populateStackTraceTreeElement(root); - this._formattedMessage = ol; - } - - // This is used for inline message bubbles in SourceFrames, or other plain-text representations. - this._message = messageText.textContent; - }, - - _shouldDumpStackTrace: function() - { - return !!this._stackTrace && this._stackTrace.length && (this.source === WebInspector.ConsoleMessage.MessageSource.Network || this.level === WebInspector.ConsoleMessage.MessageLevel.Error || this.type === WebInspector.ConsoleMessage.MessageType.Trace); - }, - - get message() - { - // force message formatting - var formattedMessage = this.formattedMessage; - return this._message; - }, - - get formattedMessage() - { - if (!this._formattedMessage) - this._formatMessage(); - return this._formattedMessage; - }, - - _linkifyLocation: function(url, lineNumber, columnNumber) - { - // ConsoleMessage stack trace line numbers are one-based. - lineNumber = lineNumber ? lineNumber - 1 : 0; - - return WebInspector.linkifyLocation(url, lineNumber, columnNumber, "console-message-url"); - }, - - _linkifyCallFrame: function(callFrame) - { - return this._linkifyLocation(callFrame.url, callFrame.lineNumber, callFrame.columnNumber); - }, - - isErrorOrWarning: function() - { - return (this.level === WebInspector.ConsoleMessage.MessageLevel.Warning || this.level === WebInspector.ConsoleMessage.MessageLevel.Error); - }, - - _format: function(parameters) - { - // This node is used like a Builder. Values are continually appended onto it. - var formattedResult = document.createElement("span"); - if (!parameters.length) - return formattedResult; - - // Formatting code below assumes that parameters are all wrappers whereas frontend console - // API allows passing arbitrary values as messages (strings, numbers, etc.). Wrap them here. - for (var i = 0; i < parameters.length; ++i) { - // FIXME: Only pass runtime wrappers here. - if (parameters[i] instanceof WebInspector.RemoteObject) - continue; - - if (typeof parameters[i] === "object") - parameters[i] = WebInspector.RemoteObject.fromPayload(parameters[i]); - else - parameters[i] = WebInspector.RemoteObject.fromPrimitiveValue(parameters[i]); - } - - // There can be string log and string eval result. We distinguish between them based on message type. - var shouldFormatMessage = WebInspector.RemoteObject.type(parameters[0]) === "string" && this.type !== WebInspector.ConsoleMessage.MessageType.Result; - - // Multiple parameters with the first being a format string. Save unused substitutions. - if (shouldFormatMessage) { - // Multiple parameters with the first being a format string. Save unused substitutions. - var result = this._formatWithSubstitutionString(parameters, formattedResult); - parameters = result.unusedSubstitutions; - if (parameters.length) - formattedResult.appendChild(document.createTextNode(" ")); - } - - // Single parameter, or unused substitutions from above. - for (var i = 0; i < parameters.length; ++i) { - // Inline strings when formatting. - if (shouldFormatMessage && parameters[i].type === "string") - formattedResult.appendChild(document.createTextNode(parameters[i].description)); - else - formattedResult.appendChild(this._formatParameter(parameters[i])); - if (i < parameters.length - 1) - formattedResult.appendChild(document.createTextNode(" ")); - } - return formattedResult; - }, - - /** - * @param {boolean=} forceObjectFormat - */ - _formatParameter: function(output, forceObjectFormat) - { - var type; - if (forceObjectFormat) - type = "object"; - else if (output instanceof WebInspector.RemoteObject) - type = output.subtype || output.type; - else - type = typeof output; - - var formatter = this._customFormatters[type]; - if (!formatter) { - formatter = this._formatParameterAsValue; - output = output.description; - } - - var span = document.createElement("span"); - span.className = "console-formatted-" + type + " source-code"; - formatter.call(this, output, span); - return span; - }, - - _formatParameterAsValue: function(val, elem) - { - elem.appendChild(document.createTextNode(val)); - }, - - _formatParameterAsObject: function(obj, elem) - { - elem.appendChild(new WebInspector.ObjectPropertiesSection(obj, obj.description).element); - }, - - _formatParameterAsNode: function(object, elem) - { - function printNode(nodeId) - { - if (!nodeId) { - // Sometimes DOM is loaded after the sync message is being formatted, so we get no - // nodeId here. So we fall back to object formatting here. - this._formatParameterAsObject(object, elem); - return; - } - var treeOutline = new WebInspector.DOMTreeOutline(false, false, true); - treeOutline.setVisible(true); - treeOutline.rootDOMNode = WebInspector.domTreeManager.nodeForId(nodeId); - treeOutline.element.classList.add("outline-disclosure"); - if (!treeOutline.children[0].hasChildren) - treeOutline.element.classList.add("single-node"); - elem.appendChild(treeOutline.element); - } - object.pushNodeToFrontend(printNode.bind(this)); - }, - - _formatParameterAsArray: function(arr, elem) - { - arr.getOwnProperties(this._printArray.bind(this, arr, elem)); - }, - - _formatParameterAsString: function(output, elem) - { - var span = document.createElement("span"); - span.className = "console-formatted-string source-code"; - span.appendChild(WebInspector.linkifyStringAsFragment(output.description)); - - // Make black quotes. - elem.classList.remove("console-formatted-string"); - elem.appendChild(document.createTextNode("\"")); - elem.appendChild(span); - elem.appendChild(document.createTextNode("\"")); - }, - - _printArray: function(array, elem, properties) - { - if (!properties) - return; - - var elements = []; - for (var i = 0; i < properties.length; ++i) { - var property = properties[i]; - var name = property.name; - if (!isNaN(name)) - elements[name] = this._formatAsArrayEntry(property.value); - } - - elem.appendChild(document.createTextNode("[")); - var lastNonEmptyIndex = -1; - - function appendUndefined(elem, index) - { - if (index - lastNonEmptyIndex <= 1) - return; - var span = elem.createChild("span", "console-formatted-undefined"); - span.textContent = WebInspector.UIString("undefined × %d").format(index - lastNonEmptyIndex - 1); - } - - var length = array.arrayLength(); - for (var i = 0; i < length; ++i) { - var element = elements[i]; - if (!element) - continue; - - if (i - lastNonEmptyIndex > 1) { - appendUndefined(elem, i); - elem.appendChild(document.createTextNode(", ")); - } - - elem.appendChild(element); - lastNonEmptyIndex = i; - if (i < length - 1) - elem.appendChild(document.createTextNode(", ")); - } - appendUndefined(elem, length); - - elem.appendChild(document.createTextNode("]")); - }, - - _formatAsArrayEntry: function(output) - { - // Prevent infinite expansion of cross-referencing arrays. - return this._formatParameter(output, output.subtype && output.subtype === "array"); - }, - - _formatWithSubstitutionString: function(parameters, formattedResult) - { - var formatters = {}; - - function parameterFormatter(force, obj) - { - return this._formatParameter(obj, force); - } - - function stringFormatter(obj) - { - return obj.description; - } - - function floatFormatter(obj) - { - if (typeof obj.value !== "number") - return parseFloat(obj.description); - return obj.value; - } - - function integerFormatter(obj) - { - if (typeof obj.value !== "number") - return parseInt(obj.description); - return Math.floor(obj.value); - } - - var currentStyle = null; - function styleFormatter(obj) - { - currentStyle = {}; - var buffer = document.createElement("span"); - buffer.setAttribute("style", obj.description); - for (var i = 0; i < buffer.style.length; i++) { - var property = buffer.style[i]; - if (isWhitelistedProperty(property)) - currentStyle[property] = buffer.style[property]; - } - } - - function isWhitelistedProperty(property) - { - var prefixes = ["background", "border", "color", "font", "line", "margin", "padding", "text", "-webkit-background", "-webkit-border", "-webkit-font", "-webkit-margin", "-webkit-padding", "-webkit-text"]; - for (var i = 0; i < prefixes.length; i++) { - if (property.startsWith(prefixes[i])) - return true; - } - return false; - } - - // Firebug uses %o for formatting objects. - formatters.o = parameterFormatter.bind(this, false); - formatters.s = stringFormatter; - formatters.f = floatFormatter; - - // Firebug allows both %i and %d for formatting integers. - formatters.i = integerFormatter; - formatters.d = integerFormatter; - - // Firebug uses %c for styling the message. - formatters.c = styleFormatter; - - // Support %O to force object formatting, instead of the type-based %o formatting. - formatters.O = parameterFormatter.bind(this, true); - - function append(a, b) - { - if (b instanceof Node) - a.appendChild(b); - else if (b) { - var toAppend = WebInspector.linkifyStringAsFragment(b.toString()); - if (currentStyle) { - var wrapper = document.createElement("span"); - for (var key in currentStyle) - wrapper.style[key] = currentStyle[key]; - wrapper.appendChild(toAppend); - toAppend = wrapper; - } - a.appendChild(toAppend); - } - return a; - } - - // String.format does treat formattedResult like a Builder, result is an object. - return String.format(parameters[0].description, parameters.slice(1), formatters, formattedResult, append); - }, - - clearHighlight: function() - { - if (!this._formattedMessage) - return; - - var highlightedMessage = this._formattedMessage; - delete this._formattedMessage; - this._formatMessage(); - this._element.replaceChild(this._formattedMessage, highlightedMessage); - }, - - highlightSearchResults: function(regexObject) - { - if (!this._formattedMessage) - return; - - regexObject.lastIndex = 0; - var text = this.message; - var match = regexObject.exec(text); - var offset = 0; - var matchRanges = []; - while (match) { - matchRanges.push({ offset: match.index, length: match[0].length }); - match = regexObject.exec(text); - } - highlightSearchResults(this._formattedMessage, matchRanges); - this._element.scrollIntoViewIfNeeded(); - }, - - matchesRegex: function(regexObject) - { - return regexObject.test(this.message); - }, - - toMessageElement: function() - { - if (this._element) - return this._element; - - var element = document.createElement("div"); - element.message = this; - element.className = "console-message"; - - this._element = element; - - switch (this.level) { - case WebInspector.ConsoleMessage.MessageLevel.Tip: - element.classList.add("console-tip-level"); - element.setAttribute("data-labelprefix", WebInspector.UIString("Tip: ")); - break; - case WebInspector.ConsoleMessage.MessageLevel.Log: - element.classList.add("console-log-level"); - element.setAttribute("data-labelprefix", WebInspector.UIString("Log: ")); - break; - case WebInspector.ConsoleMessage.MessageLevel.Debug: - element.classList.add("console-debug-level"); - element.setAttribute("data-labelprefix", WebInspector.UIString("Debug: ")); - break; - case WebInspector.ConsoleMessage.MessageLevel.Warning: - element.classList.add("console-warning-level"); - element.setAttribute("data-labelprefix", WebInspector.UIString("Warning: ")); - break; - case WebInspector.ConsoleMessage.MessageLevel.Error: - element.classList.add("console-error-level"); - element.setAttribute("data-labelprefix", WebInspector.UIString("Error: ")); - break; - } - - if (this.type === WebInspector.ConsoleMessage.MessageType.StartGroup || this.type === WebInspector.ConsoleMessage.MessageType.StartGroupCollapsed) - element.classList.add("console-group-title"); - - element.appendChild(this.formattedMessage); - - if (this.repeatCount > 1) - this.updateRepeatCount(); - - return element; - }, - - _populateStackTraceTreeElement: function(parentTreeElement) - { - for (var i = 0; i < this._stackTrace.length; i++) { - var frame = this._stackTrace[i]; - - var content = document.createElement("div"); - var messageTextElement = document.createElement("span"); - messageTextElement.className = "console-message-text source-code"; - var functionName = frame.functionName || WebInspector.UIString("(anonymous function)"); - messageTextElement.appendChild(document.createTextNode(functionName)); - content.appendChild(messageTextElement); - - if (frame.url) { - var urlElement = this._linkifyCallFrame(frame); - content.appendChild(urlElement); - } - - var treeElement = new TreeElement(content); - parentTreeElement.appendChild(treeElement); - } - }, - - updateRepeatCount: function() { - if (!this.repeatCountElement) { - this.repeatCountElement = document.createElement("span"); - this.repeatCountElement.className = "bubble"; - - this._element.insertBefore(this.repeatCountElement, this._element.firstChild); - } - this.repeatCountElement.textContent = this.repeatCount; - }, - - toString: function() - { - var sourceString; - switch (this.source) { - case WebInspector.ConsoleMessage.MessageSource.HTML: - sourceString = "HTML"; - break; - case WebInspector.ConsoleMessage.MessageSource.XML: - sourceString = "XML"; - break; - case WebInspector.ConsoleMessage.MessageSource.JS: - sourceString = "JS"; - break; - case WebInspector.ConsoleMessage.MessageSource.Network: - sourceString = "Network"; - break; - case WebInspector.ConsoleMessage.MessageSource.ConsoleAPI: - sourceString = "ConsoleAPI"; - break; - case WebInspector.ConsoleMessage.MessageSource.Other: - sourceString = "Other"; - break; - } - - var typeString; - switch (this.type) { - case WebInspector.ConsoleMessage.MessageType.Log: - typeString = "Log"; - break; - case WebInspector.ConsoleMessage.MessageType.Dir: - typeString = "Dir"; - break; - case WebInspector.ConsoleMessage.MessageType.DirXML: - typeString = "Dir XML"; - break; - case WebInspector.ConsoleMessage.MessageType.Trace: - typeString = "Trace"; - break; - case WebInspector.ConsoleMessage.MessageType.StartGroupCollapsed: - case WebInspector.ConsoleMessage.MessageType.StartGroup: - typeString = "Start Group"; - break; - case WebInspector.ConsoleMessage.MessageType.EndGroup: - typeString = "End Group"; - break; - case WebInspector.ConsoleMessage.MessageType.Assert: - typeString = "Assert"; - break; - case WebInspector.ConsoleMessage.MessageType.Result: - typeString = "Result"; - break; - } - - return sourceString + " " + typeString + " " + this.levelString + ": " + this.formattedMessage.textContent + "\n" + this.url + " line " + this.line; - }, - - get text() - { - return this._messageText; - }, - - isEqual: function(msg) - { - if (!msg) - return false; - - if (this._stackTrace) { - if (!msg._stackTrace) - return false; - var l = this._stackTrace; - var r = msg._stackTrace; - for (var i = 0; i < l.length; i++) { - if (l[i].url !== r[i].url || - l[i].functionName !== r[i].functionName || - l[i].lineNumber !== r[i].lineNumber || - l[i].columnNumber !== r[i].columnNumber) - return false; - } - } - - return (this.source === msg.source) - && (this.type === msg.type) - && (this.level === msg.level) - && (this.line === msg.line) - && (this.url === msg.url) - && (this.message === msg.message) - && (this._request === msg._request); - }, - - get stackTrace() - { - return this._stackTrace; - }, - - /** - * @return {WebInspector.ConsoleMessage} - */ - clone: function() - { - return WebInspector.ConsoleMessage.create(this.source, this.level, this._messageText, this.type, this.url, this.line, this.column, this.repeatCount, this._parameters, this._stackTrace, this._request); - }, - - get levelString() - { - switch (this.level) { - case WebInspector.ConsoleMessage.MessageLevel.Tip: - return "Tip"; - case WebInspector.ConsoleMessage.MessageLevel.Log: - return "Log"; - case WebInspector.ConsoleMessage.MessageLevel.Warning: - return "Warning"; - case WebInspector.ConsoleMessage.MessageLevel.Debug: - return "Debug"; - case WebInspector.ConsoleMessage.MessageLevel.Error: - return "Error"; - } - }, - - get clipboardPrefixString() - { - return "[" + this.levelString + "] "; - }, - - toClipboardString: function(isPrefixOptional) - { - var isTrace = this._shouldDumpStackTrace(); - - var clipboardString = ""; - if (this._formattedMessage && !isTrace) - clipboardString = this._formattedMessage.querySelector("span").innerText; - else - clipboardString = this.type === WebInspector.ConsoleMessage.MessageType.Trace ? "console.trace()" : this._message || this._messageText; - - if (!isPrefixOptional || this.enforcesClipboardPrefixString) - clipboardString = this.clipboardPrefixString + clipboardString; - - if (isTrace) { - this._stackTrace.forEach(function(frame) { - clipboardString += "\n\t" + (frame.functionName || WebInspector.UIString("(anonymous function)")); - if (frame.url) - clipboardString += " (" + WebInspector.displayNameForURL(frame.url) + ", line " + frame.lineNumber + ")"; - }); - } else { - var repeatString = this.repeatCount > 1 ? "x" + this.repeatCount : ""; - - var urlLine = ""; - if (this.url) { - var components = [WebInspector.displayNameForURL(this.url), "line " + this.line]; - if (repeatString) - components.push(repeatString); - urlLine = " (" + components.join(", ") + ")"; - } else if (repeatString) - urlLine = " (" + repeatString + ")"; - - if (urlLine) { - var lines = clipboardString.split("\n"); - lines[0] += urlLine; - clipboardString = lines.join("\n"); - } - } - - return clipboardString; - } -} - -WebInspector.ConsoleMessageImpl.prototype.__proto__ = WebInspector.ConsoleMessage.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ConsoleObserver.js b/Source/WebInspectorUI/UserInterface/ConsoleObserver.js deleted file mode 100644 index 407d2e68d..000000000 --- a/Source/WebInspectorUI/UserInterface/ConsoleObserver.js +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ConsoleObserver = function() -{ - WebInspector.Object.call(this); -}; - -WebInspector.ConsoleObserver.prototype = { - constructor: WebInspector.ConsoleObserver, - - // Events defined by the "Console" domain. - - messageAdded: function(message) - { - if (message.level === "warning" || message.level === "error") - WebInspector.issueManager.issueWasAdded(message.source, message.level, message.text, message.url, message.line, message.column || 0, message.parameters); - - if (message.url === "[native code]") { - if (message.type === "profile") - WebInspector.profileManager.profileWasStartedFromConsole(message.text); - else if (message.type === "profileEnd") - WebInspector.profileManager.profileWasEndedFromConsole(); - } - - if (message.source === "console-api" && message.type === "clear") - return; - - WebInspector.logManager.messageWasAdded(message.source, message.level, message.text, message.type, message.url, message.line, message.column || 0, message.repeatCount, message.parameters, message.stackTrace, message.networkRequestId); - }, - - messageRepeatCountUpdated: function(count) - { - WebInspector.logManager.messageRepeatCountUpdated(count); - }, - - messagesCleared: function() - { - WebInspector.logManager.messagesCleared(); - } -}; - -WebInspector.ConsoleObserver.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ConsolePrompt.css b/Source/WebInspectorUI/UserInterface/ConsolePrompt.css deleted file mode 100644 index 7466d0a34..000000000 --- a/Source/WebInspectorUI/UserInterface/ConsolePrompt.css +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.console-prompt { - background-color: white; -} - -.console-prompt > .CodeMirror { - width: 100%; - height: auto; -} - -.console-prompt > .CodeMirror-scroll { - overflow: hidden; -} diff --git a/Source/WebInspectorUI/UserInterface/ConsolePrompt.js b/Source/WebInspectorUI/UserInterface/ConsolePrompt.js deleted file mode 100644 index 71b132640..000000000 --- a/Source/WebInspectorUI/UserInterface/ConsolePrompt.js +++ /dev/null @@ -1,294 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ConsolePrompt = function(delegate, mimeType, element) -{ - WebInspector.Object.call(this); - - mimeType = parseMIMEType(mimeType).type; - - this._element = element || document.createElement("div"); - this._element.classList.add(WebInspector.ConsolePrompt.StyleClassName); - this._element.classList.add(WebInspector.SyntaxHighlightedStyleClassName); - - this._delegate = delegate || null; - - this._codeMirror = CodeMirror(this.element, { - lineWrapping: true, - mode: mimeType, - indentWithTabs: true, - indentUnit: 4, - matchBrackets: true - }); - - var keyMap = { - "Up": this._handlePreviousKey.bind(this), - "Down": this._handleNextKey.bind(this), - "Ctrl-P": this._handlePreviousKey.bind(this), - "Ctrl-N": this._handleNextKey.bind(this), - "Enter": this._handleEnterKey.bind(this), - "Cmd-Enter": this._handleCommandEnterKey.bind(this) - }; - - this._codeMirror.addKeyMap(keyMap); - - this._completionController = new WebInspector.CodeMirrorCompletionController(this._codeMirror, this); - this._completionController.addExtendedCompletionProvider("javascript", WebInspector.javaScriptRuntimeCompletionProvider); - - this._history = [{}]; - this._historyIndex = 0; -}; - -WebInspector.ConsolePrompt.StyleClassName = "console-prompt"; -WebInspector.ConsolePrompt.MaximumHistorySize = 30; - -WebInspector.ConsolePrompt.prototype = { - constructor: WebInspector.ConsolePrompt, - - // Public - - get element() - { - return this._element; - }, - - get delegate() - { - return this._delegate; - }, - - set delegate(delegate) - { - this._delegate = delegate || null; - }, - - get text() - { - return this._codeMirror.getValue(); - }, - - set text(text) - { - this._codeMirror.setValue(text || ""); - this._codeMirror.clearHistory(); - this._codeMirror.markClean(); - }, - - get history() - { - this._history[this._historyIndex] = this._historyEntryForCurrentText(); - return this._history; - }, - - set history(history) - { - this._history = history instanceof Array ? history.slice(0, WebInspector.ConsolePrompt.MaximumHistorySize) : [{}]; - this._historyIndex = 0; - this._restoreHistoryEntry(0); - }, - - get focused() - { - return this._codeMirror.getWrapperElement().classList.contains("CodeMirror-focused"); - }, - - focus: function() - { - this._codeMirror.focus(); - }, - - shown: function() - { - this._codeMirror.refresh(); - }, - - updateLayout: function() - { - this._codeMirror.refresh(); - }, - - updateCompletions: function(completions, implicitSuffix) - { - this._completionController.updateCompletions(completions, implicitSuffix); - }, - - // Protected - - completionControllerCompletionsNeeded: function(completionController, prefix, defaultCompletions, base, suffix, forced) - { - if (this.delegate && typeof this.delegate.consolePromptCompletionsNeeded === "function") - this.delegate.consolePromptCompletionsNeeded(this, defaultCompletions, base, prefix, suffix, forced); - else - this._completionController.updateCompletions(defaultCompletions); - }, - - completionControllerShouldAllowEscapeCompletion: function(completionController) - { - // Only allow escape to complete if there is text in the prompt. Otherwise allow it to pass through - // so escape to toggle the quick console still works. - return !!this.text; - }, - - // Private - - _handlePreviousKey: function(codeMirror) - { - if (this._codeMirror.somethingSelected()) - return CodeMirror.Pass; - - // Pass unless we are on the first line. - if (this._codeMirror.getCursor().line) - return CodeMirror.Pass; - - var historyEntry = this._history[this._historyIndex + 1]; - if (!historyEntry) - return CodeMirror.Pass; - - this._rememberCurrentTextInHistory(); - - ++this._historyIndex; - - this._restoreHistoryEntry(this._historyIndex); - }, - - _handleNextKey: function(codeMirror) - { - if (this._codeMirror.somethingSelected()) - return CodeMirror.Pass; - - // Pass unless we are on the last line. - if (this._codeMirror.getCursor().line !== this._codeMirror.lastLine()) - return CodeMirror.Pass; - - var historyEntry = this._history[this._historyIndex - 1]; - if (!historyEntry) - return CodeMirror.Pass; - - this._rememberCurrentTextInHistory(); - - --this._historyIndex; - - this._restoreHistoryEntry(this._historyIndex); - }, - - _handleEnterKey: function(codeMirror, forceCommit) - { - var currentText = this.text; - - // Always do nothing when there is just whitespace. - if (!currentText.trim()) - return; - - var cursor = this._codeMirror.getCursor(); - var lastLine = this._codeMirror.lastLine(); - var lastLineLength = this._codeMirror.getLine(lastLine).length; - var cursorIsAtLastPosition = positionsEqual(cursor, {line: lastLine, ch: lastLineLength}); - - function positionsEqual(a, b) - { - console.assert(a); - console.assert(b); - return a.line === b.line && a.ch === b.ch; - } - - function commitTextOrInsertNewLine(commit) - { - if (!commit) { - // Only insert a new line if the previous cursor and the current cursor are in the same position. - if (positionsEqual(cursor, this._codeMirror.getCursor())) - CodeMirror.commands.newlineAndIndent(this._codeMirror); - return; - } - - var historyEntry = this._historyEntryForCurrentText(); - - // Replace the previous entry if it does not have text or if the text is the same. - if (this._history[1] && (!this._history[1].text || this._history[1].text === historyEntry.text)) { - this._history[1] = historyEntry; - this._history[0] = {}; - } else { - // Replace the first history entry and push a new empty one. - this._history[0] = historyEntry; - this._history.unshift({}); - - // Trim the history length if needed. - if (this._history.length > WebInspector.ConsolePrompt.MaximumHistorySize) - this._history = this._history.slice(0, WebInspector.ConsolePrompt.MaximumHistorySize); - } - - this._historyIndex = 0; - - this._codeMirror.setValue(""); - this._codeMirror.clearHistory(); - - if (this.delegate && typeof this.delegate.consolePromptHistoryDidChange === "function") - this.delegate.consolePromptHistoryDidChange(this); - - if (this.delegate && typeof this.delegate.consolePromptTextCommitted === "function") - this.delegate.consolePromptTextCommitted(this, currentText); - } - - if (!forceCommit && this.delegate && typeof this.delegate.consolePromptShouldCommitText === "function") { - this.delegate.consolePromptShouldCommitText(this, currentText, cursorIsAtLastPosition, commitTextOrInsertNewLine.bind(this)); - return; - } - - commitTextOrInsertNewLine.call(this, true); - }, - - _handleCommandEnterKey: function(codeMirror) - { - this._handleEnterKey(codeMirror, true); - }, - - _restoreHistoryEntry: function(index) - { - var historyEntry = this._history[index]; - - this._codeMirror.setValue(historyEntry.text || ""); - - if (historyEntry.undoHistory) - this._codeMirror.setHistory(historyEntry.undoHistory); - else - this._codeMirror.clearHistory(); - - this._codeMirror.setCursor(historyEntry.cursor || {line: 0}); - }, - - _historyEntryForCurrentText: function() - { - return {text: this.text, undoHistory: this._codeMirror.getHistory(), cursor: this._codeMirror.getCursor()}; - }, - - _rememberCurrentTextInHistory: function() - { - this._history[this._historyIndex] = this._historyEntryForCurrentText(); - - if (this.delegate && typeof this.delegate.consolePromptHistoryDidChange === "function") - this.delegate.consolePromptHistoryDidChange(this); - } -}; - -WebInspector.ConsolePrompt.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ContentBrowser.css b/Source/WebInspectorUI/UserInterface/ContentBrowser.css deleted file mode 100644 index bd691d0a2..000000000 --- a/Source/WebInspectorUI/UserInterface/ContentBrowser.css +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.content-browser { - display: -webkit-flex; - -webkit-flex-direction: column; -} - -.content-browser > .content-view-container { - display: -webkit-flex; - -webkit-flex: 1; -} diff --git a/Source/WebInspectorUI/UserInterface/ContentBrowser.js b/Source/WebInspectorUI/UserInterface/ContentBrowser.js deleted file mode 100644 index 7f587a1c4..000000000 --- a/Source/WebInspectorUI/UserInterface/ContentBrowser.js +++ /dev/null @@ -1,532 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ContentBrowser = function(element, delegate, disableBackForward) -{ - WebInspector.Object.call(this); - - this._element = element || document.createElement("div"); - this._element.classList.add(WebInspector.ContentBrowser.StyleClassName); - - this._navigationBar = new WebInspector.NavigationBar; - this._element.appendChild(this._navigationBar.element); - - this._contentViewContainer = new WebInspector.ContentViewContainer; - this._contentViewContainer.addEventListener(WebInspector.ContentViewContainer.Event.CurrentContentViewDidChange, this._currentContentViewDidChange, this); - this._element.appendChild(this._contentViewContainer.element); - - this._findBanner = new WebInspector.FindBanner(this); - this._findKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, "F", this._showFindBanner.bind(this)); - this._findBanner.addEventListener(WebInspector.FindBanner.Event.DidShow, this._findBannerDidShow, this); - this._findBanner.addEventListener(WebInspector.FindBanner.Event.DidHide, this._findBannerDidHide, this); - - this._saveKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, "S", this._save.bind(this)); - this._saveAsKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.Shift | WebInspector.KeyboardShortcut.Modifier.CommandOrControl, "S", this._saveAs.bind(this)); - - if (!disableBackForward) { - this._backKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl | WebInspector.KeyboardShortcut.Modifier.Control, WebInspector.KeyboardShortcut.Key.Left, this._backButtonClicked.bind(this)); - this._forwardKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl | WebInspector.KeyboardShortcut.Modifier.Control, WebInspector.KeyboardShortcut.Key.Right, this._forwardButtonClicked.bind(this)); - - this._backButtonNavigationItem = new WebInspector.ButtonNavigationItem("back", WebInspector.UIString("Back (%s)").format(this._backKeyboardShortcut.displayName), "Images/BackArrow.svg", 9, 9); - this._backButtonNavigationItem.addEventListener(WebInspector.ButtonNavigationItem.Event.Clicked, this._backButtonClicked, this); - this._backButtonNavigationItem.enabled = false; - this._navigationBar.addNavigationItem(this._backButtonNavigationItem); - - this._forwardButtonNavigationItem = new WebInspector.ButtonNavigationItem("forward", WebInspector.UIString("Forward (%s)").format(this._forwardKeyboardShortcut.displayName), "Images/ForwardArrow.svg", 9, 9); - this._forwardButtonNavigationItem.addEventListener(WebInspector.ButtonNavigationItem.Event.Clicked, this._forwardButtonClicked, this); - this._forwardButtonNavigationItem.enabled = false; - this._navigationBar.addNavigationItem(this._forwardButtonNavigationItem); - - this._navigationBar.addNavigationItem(new WebInspector.DividerNavigationItem); - } - - this._hierarchicalPathNavigationItem = new WebInspector.HierarchicalPathNavigationItem; - this._hierarchicalPathNavigationItem.addEventListener(WebInspector.HierarchicalPathNavigationItem.Event.PathComponentWasSelected, this._hierarchicalPathComponentWasSelected, this); - this._navigationBar.addNavigationItem(this._hierarchicalPathNavigationItem); - - this._contentViewSelectionPathNavigationItem = new WebInspector.HierarchicalPathNavigationItem; - - this._navigationBar.addNavigationItem(new WebInspector.FlexibleSpaceNavigationItem); - - WebInspector.ContentView.addEventListener(WebInspector.ContentView.Event.SelectionPathComponentsDidChange, this._contentViewSelectionPathComponentDidChange, this); - WebInspector.ContentView.addEventListener(WebInspector.ContentView.Event.SupplementalRepresentedObjectsDidChange, this._contentViewSupplementalRepresentedObjectsDidChange, this); - WebInspector.ContentView.addEventListener(WebInspector.ContentView.Event.NumberOfSearchResultsDidChange, this._contentViewNumberOfSearchResultsDidChange, this); - WebInspector.ContentView.addEventListener(WebInspector.ContentView.Event.NavigationItemsDidChange, this._contentViewNavigationItemsDidChange, this); - - this._delegate = delegate || null; - - this._currentContentViewNavigationItems = []; -}; - -WebInspector.Object.addConstructorFunctions(WebInspector.ContentBrowser); - -WebInspector.ContentBrowser.StyleClassName = "content-browser"; - -WebInspector.ContentBrowser.Event = { - CurrentRepresentedObjectsDidChange: "content-browser-current-represented-objects-did-change", - CurrentContentViewDidChange: "content-browser-current-content-view-did-change" -}; - -WebInspector.ContentBrowser.prototype = { - constructor: WebInspector.ContentBrowser, - - // Public - - get element() - { - return this._element; - }, - - get navigationBar() - { - return this._navigationBar; - }, - - get contentViewContainer() - { - return this._contentViewContainer; - }, - - get delegate() - { - return this._delegate; - }, - - set delegate(newDelegate) - { - this._delegate = newDelegate || null; - }, - - get currentContentView() - { - return this._contentViewContainer.currentContentView; - }, - - get currentRepresentedObjects() - { - var representedObjects = []; - - var lastComponent = this._hierarchicalPathNavigationItem.lastComponent; - if (lastComponent && lastComponent.representedObject) - representedObjects.push(lastComponent.representedObject); - - lastComponent = this._contentViewSelectionPathNavigationItem.lastComponent; - if (lastComponent && lastComponent.representedObject) - representedObjects.push(lastComponent.representedObject); - - var currentContentView = this.currentContentView; - if (currentContentView) { - var supplementalRepresentedObjects = currentContentView.supplementalRepresentedObjects; - if (supplementalRepresentedObjects && supplementalRepresentedObjects.length) - representedObjects = representedObjects.concat(supplementalRepresentedObjects); - } - - return representedObjects; - }, - - updateLayout: function() - { - this._navigationBar.updateLayout(); - this._contentViewContainer.updateLayout(); - }, - - showContentViewForRepresentedObject: function(representedObject, cookie) - { - var contentView = this.contentViewForRepresentedObject(representedObject); - return this._contentViewContainer.showContentView(contentView, cookie); - }, - - showContentView: function(contentView, cookie) - { - return this._contentViewContainer.showContentView(contentView, cookie); - }, - - contentViewForRepresentedObject: function(representedObject, onlyExisting) - { - return this._contentViewContainer.contentViewForRepresentedObject(representedObject, onlyExisting); - }, - - canGoBack: function() - { - var currentContentView = this.currentContentView; - if (currentContentView && currentContentView.canGoBack()) - return true; - return this._contentViewContainer.canGoBack(); - }, - - canGoForward: function() - { - var currentContentView = this.currentContentView; - if (currentContentView && currentContentView.canGoForward()) - return true; - return this._contentViewContainer.canGoForward(); - }, - - goBack: function() - { - var currentContentView = this.currentContentView; - if (currentContentView && currentContentView.canGoBack()) { - currentContentView.goBack(); - this._updateBackForwardButtons(); - return; - } - - this._contentViewContainer.goBack(); - - // The _updateBackForwardButtons function is called by _currentContentViewDidChange, - // so it does not need to be called here. - }, - - goForward: function() - { - var currentContentView = this.currentContentView; - if (currentContentView && currentContentView.canGoForward()) { - currentContentView.goForward(); - this._updateBackForwardButtons(); - return; - } - - this._contentViewContainer.goForward(); - - // The _updateBackForwardButtons function is called by _currentContentViewDidChange, - // so it does not need to be called here. - }, - - findBannerPerformSearch: function(findBanner, query) - { - var currentContentView = this.currentContentView; - if (!currentContentView || !currentContentView.supportsSearch) - return; - - currentContentView.performSearch(query); - }, - - findBannerSearchCleared: function(findBanner) - { - var currentContentView = this.currentContentView; - if (!currentContentView || !currentContentView.supportsSearch) - return; - - currentContentView.searchCleared(); - }, - - findBannerSearchQueryForSelection: function(findBanner) - { - var currentContentView = this.currentContentView; - if (!currentContentView || !currentContentView.supportsSearch) - return null; - - return currentContentView.searchQueryWithSelection(); - }, - - findBannerRevealPreviousResult: function(findBanner) - { - var currentContentView = this.currentContentView; - if (!currentContentView || !currentContentView.supportsSearch) - return; - - currentContentView.revealPreviousSearchResult(!findBanner.showing); - }, - - findBannerRevealNextResult: function(findBanner) - { - var currentContentView = this.currentContentView; - if (!currentContentView || !currentContentView.supportsSearch) - return; - - currentContentView.revealNextSearchResult(!findBanner.showing); - }, - - // Private - - _backButtonClicked: function(event) - { - this.goBack(); - }, - - _forwardButtonClicked: function(event) - { - this.goForward(); - }, - - _saveDataToFile: function(saveData, forceSaveAs) - { - console.assert(saveData); - if (!saveData) - return; - - if (typeof saveData.customSaveHandler === "function") { - saveData.customSaveHandler(forceSaveAs); - return; - } - - console.assert(saveData.url); - console.assert(typeof saveData.content === "string"); - if (!saveData.url || typeof saveData.content !== "string") - return; - - InspectorFrontendHost.save(saveData.url, saveData.content, false, forceSaveAs || saveData.forceSaveAs); - }, - - _save: function(event) - { - var currentContentView = this.currentContentView; - if (!currentContentView || !currentContentView.supportsSave) - return; - - this._saveDataToFile(currentContentView.saveData); - }, - - _saveAs: function(event) - { - var currentContentView = this.currentContentView; - if (!currentContentView || !currentContentView.supportsSave) - return; - - this._saveDataToFile(currentContentView.saveData, true); - }, - - _showFindBanner: function(event) - { - var currentContentView = this.currentContentView; - if (!currentContentView || !currentContentView.supportsSearch) - return; - - this._findBanner.show(); - }, - - _findBannerDidShow: function(event) - { - var currentContentView = this.currentContentView; - if (!currentContentView || !currentContentView.supportsSearch) - return; - - currentContentView.automaticallyRevealFirstSearchResult = true; - }, - - _findBannerDidHide: function(event) - { - var currentContentView = this.currentContentView; - if (!currentContentView || !currentContentView.supportsSearch) - return; - - currentContentView.automaticallyRevealFirstSearchResult = false; - }, - - _contentViewNumberOfSearchResultsDidChange: function(event) - { - if (event.target !== this.currentContentView) - return; - - this._findBanner.numberOfResults = this.currentContentView.numberOfSearchResults; - }, - - _updateHierarchicalPathNavigationItem: function(representedObject) - { - if (!this.delegate || typeof this.delegate.contentBrowserTreeElementForRepresentedObject !== "function") - return; - - var treeElement = representedObject ? this.delegate.contentBrowserTreeElementForRepresentedObject(this, representedObject) : null; - var pathComponents = []; - - while (treeElement && !treeElement.root) { - var pathComponent = new WebInspector.GeneralTreeElementPathComponent(treeElement); - pathComponents.unshift(pathComponent); - treeElement = treeElement.parent; - } - - this._hierarchicalPathNavigationItem.components = pathComponents; - }, - - _updateContentViewSelectionPathNavigationItem: function(contentView) - { - var selectionPathComponents = contentView ? contentView.selectionPathComponents || [] : []; - this._contentViewSelectionPathNavigationItem.components = selectionPathComponents; - - if (!selectionPathComponents.length) { - this._hierarchicalPathNavigationItem.alwaysShowLastPathComponentSeparator = false; - this._navigationBar.removeNavigationItem(this._contentViewSelectionPathNavigationItem); - return; - } - - // Insert the _contentViewSelectionPathNavigationItem after the _hierarchicalPathNavigationItem, if needed. - if (!this._navigationBar.navigationItems.contains(this._contentViewSelectionPathNavigationItem)) { - var hierarchicalPathItemIndex = this._navigationBar.navigationItems.indexOf(this._hierarchicalPathNavigationItem); - console.assert(hierarchicalPathItemIndex !== -1); - this._navigationBar.insertNavigationItem(this._contentViewSelectionPathNavigationItem, hierarchicalPathItemIndex + 1); - this._hierarchicalPathNavigationItem.alwaysShowLastPathComponentSeparator = true; - } - }, - - _updateBackForwardButtons: function() - { - if (!this._backButtonNavigationItem || !this._forwardButtonNavigationItem) - return; - - this._backButtonNavigationItem.enabled = this.canGoBack(); - this._forwardButtonNavigationItem.enabled = this.canGoForward(); - }, - - _updateContentViewNavigationItems: function() - { - var navigationBar = this.navigationBar; - - // First, we remove the navigation items added by the previous content view. - this._currentContentViewNavigationItems.forEach(function(navigationItem) { - navigationBar.removeNavigationItem(navigationItem); - }); - - var currentContentView = this.currentContentView; - if (!currentContentView) { - this._currentContentViewNavigationItems = []; - return; - } - - var insertionIndex = navigationBar.navigationItems.length; - console.assert(insertionIndex >= 0); - - // Keep track of items we'll be adding to the navigation bar. - var newNavigationItems = []; - - // Go through each of the items of the new content view and add a divider before them. - currentContentView.navigationItems.forEach(function(navigationItem, index) { - // Add dividers before items unless it's the first item and not a button. - if (index !== 0 || navigationItem instanceof WebInspector.ButtonNavigationItem) { - var divider = new WebInspector.DividerNavigationItem; - navigationBar.insertNavigationItem(divider, insertionIndex++); - newNavigationItems.push(divider); - } - navigationBar.insertNavigationItem(navigationItem, insertionIndex++); - newNavigationItems.push(navigationItem); - }); - - // Remember the navigation items we inserted so we can remove them - // for the next content view. - this._currentContentViewNavigationItems = newNavigationItems; - }, - - _updateFindBanner: function(currentContentView) - { - if (!currentContentView) { - this._findBanner.targetElement = null; - this._findBanner.numberOfResults = null; - return; - } - - this._findBanner.targetElement = currentContentView.element; - this._findBanner.numberOfResults = currentContentView.hasPerformedSearch ? currentContentView.numberOfSearchResults : null; - - if (currentContentView.supportsSearch && this._findBanner.searchQuery) { - currentContentView.automaticallyRevealFirstSearchResult = this._findBanner.showing; - currentContentView.performSearch(this._findBanner.searchQuery); - } - }, - - _dispatchCurrentRepresentedObjectsDidChangeEventSoon: function() - { - if (this._currentRepresentedObjectsDidChangeTimeout) - return; - this._currentRepresentedObjectsDidChangeTimeout = setTimeout(this._dispatchCurrentRepresentedObjectsDidChangeEvent.bind(this), 0); - }, - - _dispatchCurrentRepresentedObjectsDidChangeEvent: function() - { - if (this._currentRepresentedObjectsDidChangeTimeout) { - clearTimeout(this._currentRepresentedObjectsDidChangeTimeout); - delete this._currentRepresentedObjectsDidChangeTimeout; - } - - this.dispatchEventToListeners(WebInspector.ContentBrowser.Event.CurrentRepresentedObjectsDidChange); - }, - - _contentViewSelectionPathComponentDidChange: function(event) - { - if (event.target !== this.currentContentView) - return; - - this._updateContentViewSelectionPathNavigationItem(event.target); - this._updateBackForwardButtons(); - - this._updateContentViewNavigationItems(); - - this._navigationBar.updateLayout(); - - this._dispatchCurrentRepresentedObjectsDidChangeEventSoon(); - }, - - _contentViewSupplementalRepresentedObjectsDidChange: function(event) - { - if (event.target !== this.currentContentView) - return; - - this._dispatchCurrentRepresentedObjectsDidChangeEventSoon(); - }, - - _currentContentViewDidChange: function(event) - { - var currentContentView = this.currentContentView; - - this._updateHierarchicalPathNavigationItem(currentContentView ? currentContentView.representedObject : null); - this._updateContentViewSelectionPathNavigationItem(currentContentView); - this._updateBackForwardButtons(); - - this._updateContentViewNavigationItems(); - this._updateFindBanner(currentContentView); - - this._navigationBar.updateLayout(); - - this.dispatchEventToListeners(WebInspector.ContentBrowser.Event.CurrentContentViewDidChange); - - this._dispatchCurrentRepresentedObjectsDidChangeEvent(); - }, - - _contentViewNavigationItemsDidChange: function(event) - { - if (event.target !== this.currentContentView) - return; - - this._updateContentViewNavigationItems(); - this._navigationBar.updateLayout(); - }, - - _hierarchicalPathComponentWasSelected: function(event) - { - console.assert(event.data.pathComponent instanceof WebInspector.GeneralTreeElementPathComponent); - - var treeElement = event.data.pathComponent.generalTreeElement; - var originalTreeElement = treeElement; - - // Some tree elements (like folders) are not viewable. Find the first descendant that is viewable. - while (treeElement && !WebInspector.ContentView.isViewable(treeElement.representedObject)) - treeElement = treeElement.traverseNextTreeElement(false, originalTreeElement, false); - - if (!treeElement) - return; - - this.showContentViewForRepresentedObject(treeElement.representedObject); - } -}; - -WebInspector.ContentBrowser.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ContentFlow.js b/Source/WebInspectorUI/UserInterface/ContentFlow.js deleted file mode 100644 index 726316a79..000000000 --- a/Source/WebInspectorUI/UserInterface/ContentFlow.js +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (C) 2013 Adobe Systems Incorporated. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above - * copyright notice, this list of conditions and the following - * disclaimer. - * 2. Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR - * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF - * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -WebInspector.ContentFlow = function(documentNodeIdentifier, name, overset, contentNodes) -{ - WebInspector.Object.call(this); - - this._documentNodeIdentifier = documentNodeIdentifier; - this._name = name; - this._overset = overset; - this._contentNodes = contentNodes; -}; - -WebInspector.ContentFlow.Event = { - OversetWasChanged: "content-flow-overset-was-changed", - ContentNodeWasAdded: "content-flow-content-node-was-added", - ContentNodeWasRemoved: "content-flow-content-node-was-removed" -}; - -WebInspector.ContentFlow.prototype = { - - constructor: WebInspector.ContentFlow, - __proto__: WebInspector.Object.prototype, - - // Public - - get id() - { - // Use the flow node id, to avoid collisions when we change main document id. - return this._documentNodeIdentifier + ":" + this._name; - }, - - get documentNodeIdentifier() - { - return this._documentNodeIdentifier; - }, - - get name() - { - return this._name; - }, - - get overset() - { - return this._overset; - }, - - set overset(overset) - { - if (this._overset === overset) - return; - this._overset = overset; - this.dispatchEventToListeners(WebInspector.ContentFlow.Event.FlowOversetWasChanged); - }, - - get contentNodes() - { - return this._contentNodes; - }, - - insertContentNodeBefore: function(contentNode, referenceNode) - { - var index = this._contentNodes.indexOf(referenceNode); - console.assert(index !== -1); - this._contentNodes.splice(index, 0, contentNode); - this.dispatchEventToListeners(WebInspector.ContentFlow.Event.ContentNodeWasAdded, {node: contentNode, before: referenceNode}); - }, - - appendContentNode: function(contentNode) - { - this._contentNodes.push(contentNode); - this.dispatchEventToListeners(WebInspector.ContentFlow.Event.ContentNodeWasAdded, {node: contentNode}); - }, - - removeContentNode: function(contentNode) - { - var index = this._contentNodes.indexOf(contentNode); - console.assert(index !== -1); - this._contentNodes.splice(index, 1); - this.dispatchEventToListeners(WebInspector.ContentFlow.Event.ContentNodeWasRemoved, {node: contentNode}); - } -}; diff --git a/Source/WebInspectorUI/UserInterface/ContentFlowDOMTreeContentView.js b/Source/WebInspectorUI/UserInterface/ContentFlowDOMTreeContentView.js deleted file mode 100644 index 3dc0a6f7f..000000000 --- a/Source/WebInspectorUI/UserInterface/ContentFlowDOMTreeContentView.js +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (C) 2013 Adobe Systems Incorporated. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above - * copyright notice, this list of conditions and the following - * disclaimer. - * 2. Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR - * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF - * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -WebInspector.ContentFlowDOMTreeContentView = function(contentFlow) -{ - console.assert(contentFlow); - - WebInspector.DOMTreeContentView.call(this, contentFlow); - - contentFlow.addEventListener(WebInspector.ContentFlow.Event.ContentNodeWasAdded, this._contentNodeWasAdded, this); - contentFlow.addEventListener(WebInspector.ContentFlow.Event.ContentNodeWasRemoved, this._contentNodeWasRemoved, this); - - this._createContentTrees(); -}; - -WebInspector.ContentFlowDOMTreeContentView.prototype = { - constructor: WebInspector.ContentFlowDOMTreeContentView, - __proto__: WebInspector.DOMTreeContentView.prototype, - - // Public - - closed: function() - { - this.representedObject.removeEventListener(WebInspector.ContentFlow.Event.ContentNodeWasAdded, this._contentNodeWasAdded, this); - this.representedObject.removeEventListener(WebInspector.ContentFlow.Event.ContentNodeWasRemoved, this._contentNodeWasRemoved, this); - WebInspector.DOMTreeContentView.prototype.closed.call(this); - }, - - getSearchContextNodes: function(callback) - { - callback(this.domTreeOutline.children.map(function(treeOutline) { - return treeOutline.representedObject.id; - })); - }, - - // Private - - _createContentTrees: function() - { - var contentNodes = this.representedObject.contentNodes; - for (var contentNode of contentNodes) - this.domTreeOutline.appendChild(new WebInspector.DOMTreeElement(contentNode)); - - var documentURL = contentNodes.length ? contentNodes[0].ownerDocument.documentURL : null; - this._restoreSelectedNodeAfterUpdate(documentURL, contentNodes[0]); - }, - - _contentNodeWasAdded: function(event) - { - var treeElement = new WebInspector.DOMTreeElement(event.data.node); - if (!event.data.before) { - this.domTreeOutline.appendChild(treeElement); - return; - } - - var beforeElement = this.domTreeOutline.findTreeElement(event.data.before); - console.assert(beforeElement); - - var index = this.domTreeOutline.children.indexOf(beforeElement); - console.assert(index !== -1); - - this.domTreeOutline.insertChild(treeElement, index); - }, - - _contentNodeWasRemoved: function(event) - { - var treeElement = this.domTreeOutline.findTreeElement(event.data.node); - console.assert(treeElement); - this.domTreeOutline.removeChild(treeElement); - } -}; diff --git a/Source/WebInspectorUI/UserInterface/ContentFlowIcon.css b/Source/WebInspectorUI/UserInterface/ContentFlowIcon.css deleted file mode 100644 index b26e766cc..000000000 --- a/Source/WebInspectorUI/UserInterface/ContentFlowIcon.css +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (C) 2013 Adobe Systems Incorporated. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above - * copyright notice, this list of conditions and the following - * disclaimer. - * 2. Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR - * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF - * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -.content-flow-icon .icon { - content: url(Images/ContentFlow.svg); -} diff --git a/Source/WebInspectorUI/UserInterface/ContentFlowTreeElement.js b/Source/WebInspectorUI/UserInterface/ContentFlowTreeElement.js deleted file mode 100644 index 766ff7ef2..000000000 --- a/Source/WebInspectorUI/UserInterface/ContentFlowTreeElement.js +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (C) 2013 Adobe Systems Incorporated. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above - * copyright notice, this list of conditions and the following - * disclaimer. - * 2. Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR - * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF - * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -WebInspector.ContentFlowTreeElement = function(representedObject) -{ - console.assert(representedObject instanceof WebInspector.ContentFlow); - WebInspector.GeneralTreeElement.call(this, [WebInspector.ContentFlowTreeElement.StyleClassName, WebInspector.ContentFlowTreeElement.ContentFlowIconStyleClassName], representedObject.name, null, representedObject, false); - - this.small = true; -}; - -WebInspector.ContentFlowTreeElement.ContentFlowIconStyleClassName = "content-flow-icon"; - -WebInspector.ContentFlowTreeElement.prototype = { - constructor: WebInspector.ContentFlowTreeElement -}; - -WebInspector.ContentFlowTreeElement.prototype.__proto__ = WebInspector.GeneralTreeElement.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ContentView.css b/Source/WebInspectorUI/UserInterface/ContentView.css deleted file mode 100644 index aafa2adbe..000000000 --- a/Source/WebInspectorUI/UserInterface/ContentView.css +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.content-view > .indeterminate-progress-spinner { - position: absolute; - top: 50%; - left: 50%; - - width: 32px; - height: 32px; - - margin-left: -16px; - margin-right: -16px; -} diff --git a/Source/WebInspectorUI/UserInterface/ContentView.js b/Source/WebInspectorUI/UserInterface/ContentView.js deleted file mode 100644 index 29ab214b7..000000000 --- a/Source/WebInspectorUI/UserInterface/ContentView.js +++ /dev/null @@ -1,318 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ContentView = function(representedObject) -{ - if (this.constructor === WebInspector.ContentView) { - // When instantiated directly return an instance of a type-based concrete subclass. - - console.assert(representedObject); - - if (representedObject instanceof WebInspector.Frame) - return new WebInspector.FrameContentView(representedObject); - - if (representedObject instanceof WebInspector.Resource) - return new WebInspector.ResourceClusterContentView(representedObject); - - if (representedObject instanceof WebInspector.Script) - return new WebInspector.ScriptContentView(representedObject); - - if (representedObject instanceof WebInspector.TimelineRecording) - return new WebInspector.TimelineContentView(representedObject); - - if (representedObject instanceof WebInspector.DOMStorageObject) - return new WebInspector.DOMStorageContentView(representedObject); - - if (representedObject instanceof WebInspector.CookieStorageObject) - return new WebInspector.CookieStorageContentView(representedObject); - - if (representedObject instanceof WebInspector.DatabaseTableObject) - return new WebInspector.DatabaseTableContentView(representedObject); - - if (representedObject instanceof WebInspector.DatabaseObject) - return new WebInspector.DatabaseContentView(representedObject); - - if (representedObject instanceof WebInspector.ApplicationCacheFrame) - return new WebInspector.ApplicationCacheFrameContentView(representedObject); - - if (representedObject instanceof WebInspector.DOMTree) - return new WebInspector.FrameDOMTreeContentView(representedObject); - - if (representedObject instanceof WebInspector.LogObject) - return new WebInspector.LogContentView(representedObject); - - if (representedObject instanceof WebInspector.JavaScriptProfileObject) - return new WebInspector.JavaScriptProfileView(representedObject); - - if (representedObject instanceof WebInspector.CanvasProfileObject) - return new WebInspector.CanvasProfileView(representedObject); - - if (representedObject instanceof WebInspector.ContentFlow) - return new WebInspector.ContentFlowDOMTreeContentView(representedObject); - - if (typeof representedObject === "string" || representedObject instanceof String) - return new WebInspector.TextContentView(representedObject); - - console.assert(!WebInspector.ContentView.isViewable(representedObject)); - - throw "Can't make a ContentView for an unknown representedObject."; - } - - // Concrete object instantiation. - console.assert(this.constructor !== WebInspector.ContentView && this instanceof WebInspector.ContentView); - console.assert(WebInspector.ContentView.isViewable(representedObject)); - - WebInspector.Object.call(this); - - this._representedObject = representedObject; - - this._element = document.createElement("div"); - this._element.classList.add(WebInspector.ContentView.StyleClassName); - - this._parentContainer = null; -}; - -WebInspector.Object.addConstructorFunctions(WebInspector.ContentView); - -WebInspector.ContentView.isViewable = function(representedObject) -{ - if (representedObject instanceof WebInspector.Frame) - return true; - if (representedObject instanceof WebInspector.Resource) - return true; - if (representedObject instanceof WebInspector.Script) - return true; - if (representedObject instanceof WebInspector.TimelineRecording) - return true; - if (representedObject instanceof WebInspector.DOMStorageObject) - return true; - if (representedObject instanceof WebInspector.CookieStorageObject) - return true; - if (representedObject instanceof WebInspector.DatabaseTableObject) - return true; - if (representedObject instanceof WebInspector.DatabaseObject) - return true; - if (representedObject instanceof WebInspector.ApplicationCacheFrame) - return true; - if (representedObject instanceof WebInspector.DOMTree) - return true; - if (representedObject instanceof WebInspector.LogObject) - return true; - if (representedObject instanceof WebInspector.JavaScriptProfileObject) - return true; - if (representedObject instanceof WebInspector.CanvasProfileObject) - return true; - if (representedObject instanceof WebInspector.ContentFlow) - return true; - if (typeof representedObject === "string" || representedObject instanceof String) - return true; - return false; -}; - -WebInspector.ContentView.StyleClassName = "content-view"; - -WebInspector.ContentView.Event = { - SelectionPathComponentsDidChange: "content-view-selection-path-components-did-change", - SupplementalRepresentedObjectsDidChange: "content-view-supplemental-represented-objects-did-change", - NumberOfSearchResultsDidChange: "content-view-number-of-search-results-did-change", - NavigationItemsDidChange: "content-view-navigation-items-did-change" -}; - -WebInspector.ContentView.prototype = { - constructor: WebInspector.ContentView, - - // Public - - get representedObject() - { - return this._representedObject; - }, - - get navigationItems() - { - // Navigation items that will be displayed by the ContentBrowser instance, - // meant to be subclassed. Implemented by subclasses. - return []; - }, - - get allowedNavigationSidebarPanels() - { - // Allow any navigation sidebar panel. - return []; - }, - - get element() - { - return this._element; - }, - - get parentContainer() - { - return this._parentContainer; - }, - - get visible() - { - return this._visible; - }, - - set visible(flag) - { - this._visible = flag; - }, - - get scrollableElements() - { - // Implemented by subclasses. - return []; - }, - - get shouldKeepElementsScrolledToBottom() - { - // Implemented by subclasses. - return false; - }, - - get selectionPathComponents() - { - // Implemented by subclasses. - return []; - }, - - get supplementalRepresentedObjects() - { - // Implemented by subclasses. - return []; - }, - - get supportsSplitContentBrowser() - { - // Implemented by subclasses. - return true; - }, - - updateLayout: function() - { - // Implemented by subclasses. - }, - - shown: function() - { - // Implemented by subclasses. - }, - - hidden: function() - { - // Implemented by subclasses. - }, - - closed: function() - { - // Implemented by subclasses. - }, - - saveToCookie: function(cookie) - { - // Implemented by subclasses. - }, - - restoreFromCookie: function(cookie) - { - // Implemented by subclasses. - }, - - canGoBack: function() - { - // Implemented by subclasses. - return false; - }, - - canGoForward: function() - { - // Implemented by subclasses. - return false; - }, - - goBack: function() - { - // Implemented by subclasses. - }, - - goForward: function() - { - // Implemented by subclasses. - }, - - get supportsSearch() - { - // Implemented by subclasses. - return false; - }, - - get numberOfSearchResults() - { - // Implemented by subclasses. - return null; - }, - - get hasPerformedSearch() - { - // Implemented by subclasses. - return false; - }, - - set automaticallyRevealFirstSearchResult(reveal) - { - // Implemented by subclasses. - }, - - performSearch: function(query) - { - // Implemented by subclasses. - }, - - searchCleared: function() - { - // Implemented by subclasses. - }, - - searchQueryWithSelection: function() - { - // Implemented by subclasses. - return null; - }, - - revealPreviousSearchResult: function(changeFocus) - { - // Implemented by subclasses. - }, - - revealNextSearchResult: function(changeFocus) - { - // Implemented by subclasses. - } -}; - -WebInspector.ContentView.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ContentViewContainer.css b/Source/WebInspectorUI/UserInterface/ContentViewContainer.css deleted file mode 100644 index 3beab1a8c..000000000 --- a/Source/WebInspectorUI/UserInterface/ContentViewContainer.css +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.content-view-container { - position: relative; - overflow: hidden; -} - -.content-view-container > .content-view { - position: absolute; - top: 0; - left: 0; - right: 0; - bottom: 0; - - overflow: hidden; -} diff --git a/Source/WebInspectorUI/UserInterface/ContentViewContainer.js b/Source/WebInspectorUI/UserInterface/ContentViewContainer.js deleted file mode 100644 index a532c0b41..000000000 --- a/Source/WebInspectorUI/UserInterface/ContentViewContainer.js +++ /dev/null @@ -1,413 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ContentViewContainer = function(element) -{ - WebInspector.Object.call(this); - - this._element = element || document.createElement("div"); - this._element.classList.add(WebInspector.ContentViewContainer.StyleClassName); - - this._backForwardList = []; - this._currentIndex = -1; -}; - -WebInspector.ContentViewContainer.StyleClassName = "content-view-container"; - -WebInspector.ContentViewContainer.Event = { - CurrentContentViewDidChange: "content-view-container-current-content-view-did-change" -}; - -WebInspector.ContentViewContainer.prototype = { - constructor: WebInspector.ContentViewContainer, - - // Public - - get element() - { - return this._element; - }, - - get currentIndex() - { - return this._currentIndex; - }, - - get backForwardList() - { - return this._backForwardList; - }, - - get currentContentView() - { - if (this._currentIndex < 0 || this._currentIndex > this._backForwardList.length - 1) - return null; - return this._backForwardList[this._currentIndex].contentView; - }, - - get currentBackForwardEntry() - { - if (this._currentIndex < 0 || this._currentIndex > this._backForwardList.length - 1) - return null; - return this._backForwardList[this._currentIndex]; - }, - - updateLayout: function() - { - var currentContentView = this.currentContentView; - if (currentContentView) - currentContentView.updateLayout(); - }, - - contentViewForRepresentedObject: function(representedObject, onlyExisting) - { - console.assert(representedObject); - if (!representedObject) - return null; - - // Iterate over all the known content views for the representedObject (if any) and find one that doesn't - // have a parent container or has this container as its parent. - var contentView = null; - for (var i = 0; representedObject.__contentViews && i < representedObject.__contentViews.length; ++i) { - var currentContentView = representedObject.__contentViews[i]; - if (!currentContentView._parentContainer || currentContentView._parentContainer === this) { - contentView = currentContentView; - break; - } - } - - console.assert(!contentView || contentView instanceof WebInspector.ContentView); - if (contentView instanceof WebInspector.ContentView) - return contentView; - - // Return early to avoid creating a new content view when onlyExisting is true. - if (onlyExisting) - return null; - - try { - // No existing content view found, make a new one. - contentView = new WebInspector.ContentView(representedObject); - } catch (e) { - console.error(e); - return null; - } - - // Remember this content view for future calls. - if (!representedObject.__contentViews) - representedObject.__contentViews = []; - representedObject.__contentViews.push(contentView); - - return contentView; - }, - - showContentViewForRepresentedObject: function(representedObject) - { - var contentView = this.contentViewForRepresentedObject(representedObject); - if (!contentView) - return null; - - this.showContentView(contentView); - - return contentView; - }, - - showContentView: function(contentView, cookie) - { - console.assert(contentView instanceof WebInspector.ContentView); - if (!(contentView instanceof WebInspector.ContentView)) - return null; - - // Don't allow showing a content view that is already associated with another container. - // Showing a content view that is already associated with this container is allowed. - console.assert(!contentView.parentContainer || contentView.parentContainer === this); - if (contentView.parentContainer && contentView.parentContainer !== this) - return null; - - var currentEntry = this.currentBackForwardEntry; - var provisionalEntry = new WebInspector.BackForwardEntry(contentView, cookie); - // Don't do anything if we would have added an identical back/forward list entry. - if (currentEntry && currentEntry.contentView === contentView && Object.shallowEqual(provisionalEntry.cookie, currentEntry.cookie)) - return currentEntry.contentView; - - // Showing a content view will truncate the back/forward list after the current index and insert the content view - // at the end of the list. Finally, the current index will be updated to point to the end of the back/forward list. - - // Increment the current index to where we will insert the content view. - var newIndex = this._currentIndex + 1; - - // Insert the content view at the new index. This will remove any content views greater than or equal to the index. - var removedEntries = this._backForwardList.splice(newIndex, this._backForwardList.length - newIndex, provisionalEntry); - - console.assert(newIndex === this._backForwardList.length - 1); - console.assert(this._backForwardList[newIndex] === provisionalEntry); - - // Disassociate with the removed content views. - for (var i = 0; i < removedEntries.length; ++i) { - // Skip disassociation if this content view is still in the back/forward list. - var shouldDissociateContentView = this._backForwardList.some(function(existingEntry) { - return existingEntry.contentView === removedEntries[i].contentView; - }); - if (shouldDissociateContentView) - this._disassociateFromContentView(removedEntries[i]); - } - - // Associate with the new content view. - contentView._parentContainer = this; - - this.showBackForwardEntryForIndex(newIndex); - - return contentView; - }, - - showBackForwardEntryForIndex: function(index) - { - console.assert(index >= 0 && index <= this._backForwardList.length - 1); - if (index < 0 || index > this._backForwardList.length - 1) - return; - - if (this._currentIndex === index) - return; - - // Hide the currently visible content view. - var previousEntry = this.currentBackForwardEntry; - if (previousEntry) - this._hideEntry(previousEntry); - - this._currentIndex = index; - var currentEntry = this.currentBackForwardEntry; - console.assert(currentEntry); - - this._showEntry(currentEntry); - - this.dispatchEventToListeners(WebInspector.ContentViewContainer.Event.CurrentContentViewDidChange); - }, - - replaceContentView: function(oldContentView, newContentView) - { - console.assert(oldContentView instanceof WebInspector.ContentView); - if (!(oldContentView instanceof WebInspector.ContentView)) - return; - - console.assert(newContentView instanceof WebInspector.ContentView); - if (!(newContentView instanceof WebInspector.ContentView)) - return; - - console.assert(oldContentView.parentContainer === this); - if (oldContentView.parentContainer !== this) - return; - - console.assert(!newContentView.parentContainer || newContentView.parentContainer === this); - if (newContentView.parentContainer && newContentView.parentContainer !== this) - return; - - var currentlyShowing = (this.currentContentView === oldContentView); - if (currentlyShowing) - this._hideEntry(this.currentBackForwardEntry); - - // Disassociate with the old content view. - this._disassociateFromContentView(oldContentView); - - // Associate with the new content view. - newContentView._parentContainer = this; - - // Replace all occurrences of oldContentView with newContentView in the back/forward list. - for (var i = 0; i < this._backForwardList.length; ++i) { - if (this._backForwardList[i].contentView === oldContentView) - this._backForwardList[i].contentView = newContentView; - } - - // Re-show the current entry, because its content view instance was replaced. - if (currentlyShowing) { - this._showEntry(this.currentBackForwardEntry); - this.dispatchEventToListeners(WebInspector.ContentViewContainer.Event.CurrentContentViewDidChange); - } - }, - - closeAllContentViewsOfPrototype: function(constructor) - { - if (!this._backForwardList.length) { - console.assert(this._currentIndex === -1); - return; - } - - // Do a check to see if all the content views are instances of this prototype. - // If they all are we can use the quicker closeAllContentViews method. - var allSamePrototype = true; - for (var i = this._backForwardList.length - 1; i >= 0; --i) { - if (!(this._backForwardList[i].contentView instanceof constructor)) { - allSamePrototype = false; - break; - } - } - - if (allSamePrototype) { - this.closeAllContentViews(); - return; - } - - var oldCurrentContentView = this.currentContentView; - - var backForwardListDidChange = false; - // Hide and disassociate with all the content views that are instances of the constructor. - for (var i = this._backForwardList.length - 1; i >= 0; --i) { - var entry = this._backForwardList[i]; - if (!(entry.contentView instanceof constructor)) - continue; - - if (entry.contentView === oldCurrentContentView) - this._hideEntry(entry); - - if (this._currentIndex >= i) { - // Decrement the currentIndex since we will remove an item in the back/forward array - // that it the current index or comes before it. - --this._currentIndex; - } - - this._disassociateFromContentView(entry.contentView); - - // Remove the item from the back/forward list. - this._backForwardList.splice(i, 1); - backForwardListDidChange = true; - } - - var currentEntry = this.currentBackForwardEntry; - console.assert(currentEntry || (!currentEntry && this._currentIndex === -1)); - - if (currentEntry && currentEntry.contentView !== oldCurrentContentView || backForwardListDidChange) { - this._showEntry(currentEntry); - this.dispatchEventToListeners(WebInspector.ContentViewContainer.Event.CurrentContentViewDidChange); - } - }, - - closeAllContentViews: function() - { - if (!this._backForwardList.length) { - console.assert(this._currentIndex === -1); - return; - } - - // Hide and disassociate with all the content views. - for (var i = 0; i < this._backForwardList.length; ++i) { - var entry = this._backForwardList[i]; - if (i === this._currentIndex) - this._hideEntry(entry); - this._disassociateFromContentView(entry.contentView); - } - - this._backForwardList = []; - this._currentIndex = -1; - - this.dispatchEventToListeners(WebInspector.ContentViewContainer.Event.CurrentContentViewDidChange); - }, - - canGoBack: function() - { - return this._currentIndex > 0; - }, - - canGoForward: function() - { - return this._currentIndex < this._backForwardList.length - 1; - }, - - goBack: function() - { - if (!this.canGoBack()) - return; - this.showBackForwardEntryForIndex(this._currentIndex - 1); - }, - - goForward: function() - { - if (!this.canGoForward()) - return; - this.showBackForwardEntryForIndex(this._currentIndex + 1); - }, - - shown: function() - { - var currentEntry = this.currentBackForwardEntry; - if (!currentEntry) - return; - - this._showEntry(currentEntry); - }, - - hidden: function() - { - var currentEntry = this.currentBackForwardEntry; - if (!currentEntry) - return; - - this._hideEntry(currentEntry); - }, - - // Private - - _addContentViewElement: function(contentView) - { - if (contentView.element.parentNode !== this._element) - this._element.appendChild(contentView.element); - }, - - _removeContentViewElement: function(contentView) - { - if (contentView.element.parentNode) - contentView.element.parentNode.removeChild(contentView.element); - }, - - _disassociateFromContentView: function(contentView) - { - console.assert(!contentView.visible); - - contentView._parentContainer = null; - - var representedObject = contentView.representedObject; - if (!representedObject || !representedObject.__contentViews) - return; - - representedObject.__contentViews.remove(contentView); - - contentView.closed(); - }, - - _showEntry: function(entry) - { - console.assert(entry instanceof WebInspector.BackForwardEntry); - - this._addContentViewElement(entry.contentView); - entry.prepareToShow(); - }, - - _hideEntry: function(entry) - { - console.assert(entry instanceof WebInspector.BackForwardEntry); - - entry.prepareToHide(); - this._removeContentViewElement(entry.contentView); - } -}; - -WebInspector.ContentViewContainer.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ContextMenu.js b/Source/WebInspectorUI/UserInterface/ContextMenu.js deleted file mode 100644 index 16c862cad..000000000 --- a/Source/WebInspectorUI/UserInterface/ContextMenu.js +++ /dev/null @@ -1,299 +0,0 @@ -/* - * Copyright (C) 2009 Google Inc. All rights reserved. - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/** - * @constructor - * @param {WebInspector.ContextSubMenuItem} topLevelMenu - * @param {string} type - * @param {string=} label - * @param {boolean=} disabled - * @param {boolean=} checked - */ -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; - }, - - /** - * @return {boolean} - */ - isEnabled: function() - { - return !this._disabled; - }, - - /** - * @param {boolean} enabled - */ - 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 }; - } - } -} - -/** - * @constructor - * @extends {WebInspector.ContextMenuItem} - * @param topLevelMenu - * @param {string=} label - * @param {boolean=} disabled - */ -WebInspector.ContextSubMenuItem = function(topLevelMenu, label, disabled) -{ - WebInspector.ContextMenuItem.call(this, topLevelMenu, "subMenu", label, disabled); - this._items = []; -} - -WebInspector.ContextSubMenuItem.prototype = { - /** - * @param {string} label - * @param {function} handler - * @param {boolean=} disabled - * @return {WebInspector.ContextMenuItem} - */ - 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; - }, - - /** - * @param {string} label - * @param {boolean=} disabled - * @return {WebInspector.ContextMenuItem} - */ - appendSubMenuItem: function(label, disabled) - { - var item = new WebInspector.ContextSubMenuItem(this._contextMenu, label, disabled); - this._pushItem(item); - return item; - }, - - /** - * @param {boolean=} disabled - */ - 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); - }, - - /** - * @return {boolean} - */ - 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 -} - -/** - * @constructor - * @extends {WebInspector.ContextSubMenuItem} - */ -WebInspector.ContextMenu = function(event) { - WebInspector.ContextSubMenuItem.call(this, this, ""); - this._event = event; - this._handlers = {}; - this._id = 0; -} - -WebInspector.ContextMenu.prototype = { - - // Public - - nextId: function() - { - return this._id++; - }, - - show: function() - { - console.assert(this._event instanceof MouseEvent); - - var menuObject = this._buildDescriptor(); - - if (menuObject.length) { - WebInspector._contextMenu = this; - if (this._event.type !== "contextmenu" && typeof InspectorFrontendHost.dispatchEventAsContextMenuEvent === "function") { - this._menuObject = menuObject; - this._event.target.addEventListener("contextmenu", this, true); - InspectorFrontendHost.dispatchEventAsContextMenuEvent(this._event); - } else - InspectorFrontendHost.showContextMenu(this._event, menuObject); - } - if (this._event) - this._event.stopImmediatePropagation(); - }, - - // Protected - - handleEvent: function(event) - { - this._event.target.removeEventListener("contextmenu", this, true); - InspectorFrontendHost.showContextMenu(event, this._menuObject); - delete this._menuObject; - - event.stopImmediatePropagation(); - }, - - // Private - - _setHandler: function(id, handler) - { - if (handler) - this._handlers[id] = handler; - }, - - _buildDescriptor: function() - { - var result = []; - for (var i = 0; i < this._items.length; ++i) - result.push(this._items[i]._buildDescriptor()); - return result; - }, - - _itemSelected: function(id) - { - if (this._handlers[id]) - this._handlers[id].call(this); - }, - - /** - * @param {Object} target - */ - appendApplicableItems: function(target) - { - for (var i = 0; i < WebInspector.ContextMenu._providers.length; ++i) { - var provider = WebInspector.ContextMenu._providers[i]; - this.appendSeparator(); - provider.appendApplicableItems(this._event, this, target); - this.appendSeparator(); - } - }, - - __proto__: WebInspector.ContextSubMenuItem.prototype -} - -/** - * @interface - */ -WebInspector.ContextMenu.Provider = function() -{ -} - -WebInspector.ContextMenu.Provider.prototype = { - /** - * @param {WebInspector.ContextMenu} contextMenu - * @param {Object} target - */ - appendApplicableItems: function(event, contextMenu, target) { } -} - -/** - * @param {WebInspector.ContextMenu.Provider} provider - */ -WebInspector.ContextMenu.registerProvider = function(provider) -{ - WebInspector.ContextMenu._providers.push(provider); -} - -WebInspector.ContextMenu._providers = []; - -WebInspector.contextMenuItemSelected = function(id) -{ - if (WebInspector._contextMenu) - WebInspector._contextMenu._itemSelected(id); -} - -WebInspector.contextMenuCleared = function() -{ - // FIXME: Unfortunately, contextMenuCleared is invoked between show and item selected - // so we can't delete last menu object from WebInspector. Fix the contract. -} diff --git a/Source/WebInspectorUI/UserInterface/ControlToolbarItem.css b/Source/WebInspectorUI/UserInterface/ControlToolbarItem.css deleted file mode 100644 index 20fa427c0..000000000 --- a/Source/WebInspectorUI/UserInterface/ControlToolbarItem.css +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.toolbar .item.control { - -webkit-align-items: center; - -webkit-justify-content: center; - - padding: 3px 2px; - - opacity: 0.5; -} - -.toolbar.small-size .item.control { - padding: 2px; -} - -.toolbar.icon-and-label-horizontal .item.control, -.toolbar.icon-only .item.control { - padding: 0 2px; -} - -.toolbar .item.control:hover { - opacity: 0.8; -} - -.toolbar .item.control:active { - opacity: 1; -} - -.toolbar .item.control > .glyph { - width: 16px; - height: 16px; - - background-repeat: no-repeat; - background-position: center center; -} - -body.window-inactive .toolbar .item.control { - opacity: 0.35; -} - -.toolbar .item.control.disabled { - opacity: 0.35 !important; -} - -body.window-inactive .toolbar .item.control.disabled { - opacity: 0.2 !important; -} diff --git a/Source/WebInspectorUI/UserInterface/ControlToolbarItem.js b/Source/WebInspectorUI/UserInterface/ControlToolbarItem.js deleted file mode 100644 index 1497c2bdc..000000000 --- a/Source/WebInspectorUI/UserInterface/ControlToolbarItem.js +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ControlToolbarItem = function(identifier, toolTip, image, imageWidth, imageHeight) -{ - WebInspector.ButtonNavigationItem.call(this, identifier, toolTip, image, imageWidth, imageHeight, false); -}; - -WebInspector.ControlToolbarItem.StyleClassName = "control"; - -WebInspector.ControlToolbarItem.prototype = { - constructor: WebInspector.ControlToolbarItem, - - // Private - - _additionalClassNames: [WebInspector.ControlToolbarItem.StyleClassName], -}; - -WebInspector.ControlToolbarItem.prototype.__proto__ = WebInspector.ButtonNavigationItem.prototype; diff --git a/Source/WebInspectorUI/UserInterface/Controllers/AnalyzerManager.js b/Source/WebInspectorUI/UserInterface/Controllers/AnalyzerManager.js new file mode 100644 index 000000000..99c62738c --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/AnalyzerManager.js @@ -0,0 +1,122 @@ +/* + * Copyright (C) 2014 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.AnalyzerManager = class AnalyzerManager extends WebInspector.Object +{ + constructor() + { + super(); + + this._eslintConfig = { + env: { + "browser": true, + "node": false + }, + globals: { + "document": true + }, + rules: { + "consistent-return": 2, + "curly": 0, + "eqeqeq": 0, + "new-parens": 0, + "no-comma-dangle": 0, + "no-console": 0, + "no-constant-condition": 0, + "no-extra-bind": 2, + "no-extra-semi": 2, + "no-proto": 0, + "no-return-assign": 2, + "no-trailing-spaces": 2, + "no-underscore-dangle": 0, + "no-unused-expressions": 2, + "no-wrap-func": 2, + "semi": 2, + "space-infix-ops": 2, + "space-return-throw-case": 2, + "strict": 0, + "valid-typeof": 2 + } + }; + + this._sourceCodeMessagesMap = new WeakMap; + + WebInspector.SourceCode.addEventListener(WebInspector.SourceCode.Event.ContentDidChange, this._handleSourceCodeContentDidChange, this); + } + + // Public + + getAnalyzerMessagesForSourceCode(sourceCode) + { + return new Promise(function(resolve, reject) { + var analyzer = WebInspector.AnalyzerManager._typeAnalyzerMap.get(sourceCode.type); + if (!analyzer) { + reject(new Error("This resource type cannot be analyzed.")); + return; + } + + if (this._sourceCodeMessagesMap.has(sourceCode)) { + resolve(this._sourceCodeMessagesMap.get(sourceCode)); + return; + } + + function retrieveAnalyzerMessages(properties) + { + var analyzerMessages = []; + var rawAnalyzerMessages = analyzer.verify(sourceCode.content, this._eslintConfig); + + // Raw line and column numbers are one-based. SourceCodeLocation expects them to be zero-based so we subtract 1 from each. + for (var rawAnalyzerMessage of rawAnalyzerMessages) + analyzerMessages.push(new WebInspector.AnalyzerMessage(new WebInspector.SourceCodeLocation(sourceCode, rawAnalyzerMessage.line - 1, rawAnalyzerMessage.column - 1), rawAnalyzerMessage.message, rawAnalyzerMessage.ruleId)); + + this._sourceCodeMessagesMap.set(sourceCode, analyzerMessages); + + resolve(analyzerMessages); + } + + sourceCode.requestContent().then(retrieveAnalyzerMessages.bind(this)).catch(handlePromiseException); + }.bind(this)); + } + + sourceCodeCanBeAnalyzed(sourceCode) + { + return sourceCode.type === WebInspector.Resource.Type.Script; + } + + // Private + + _handleSourceCodeContentDidChange(event) + { + var sourceCode = event.target; + + // Since sourceCode has changed, remove it and its messages from the map so getAnalyzerMessagesForSourceCode will have to reanalyze the next time it is called. + this._sourceCodeMessagesMap.delete(sourceCode); + } +}; + +WebInspector.AnalyzerManager._typeAnalyzerMap = new Map; + +// Web Inspector: JavaScript source text editor should have a linter +// WebInspector.AnalyzerManager._typeAnalyzerMap.set(WebInspector.Resource.Type.Script, eslint); diff --git a/Source/WebInspectorUI/UserInterface/Controllers/Annotator.js b/Source/WebInspectorUI/UserInterface/Controllers/Annotator.js new file mode 100644 index 000000000..3e87bb5a4 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/Annotator.js @@ -0,0 +1,110 @@ +/* + * Copyright (C) 2014 Apple Inc. All rights reserved. + * Copyright (C) 2014 Saam Barati + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.Annotator = class Annotator extends WebInspector.Object +{ + constructor(sourceCodeTextEditor) + { + super(); + + console.assert(sourceCodeTextEditor instanceof WebInspector.SourceCodeTextEditor, sourceCodeTextEditor); + + this._sourceCodeTextEditor = sourceCodeTextEditor; + this._timeoutIdentifier = null; + this._isActive = false; + } + + // Public + + get sourceCodeTextEditor() + { + return this._sourceCodeTextEditor; + } + + isActive() + { + return this._isActive; + } + + pause() + { + this._clearTimeoutIfNeeded(); + this._isActive = false; + } + + resume() + { + this._clearTimeoutIfNeeded(); + this._isActive = true; + this.insertAnnotations(); + } + + refresh() + { + console.assert(this._isActive); + if (!this._isActive) + return; + + this._clearTimeoutIfNeeded(); + this.insertAnnotations(); + } + + reset() + { + this._clearTimeoutIfNeeded(); + this._isActive = true; + this.clearAnnotations(); + this.insertAnnotations(); + } + + clear() + { + this.pause(); + this.clearAnnotations(); + } + + // Protected + + insertAnnotations() + { + // Implemented by subclasses. + } + + clearAnnotations() + { + // Implemented by subclasses. + } + + // Private + + _clearTimeoutIfNeeded() + { + if (this._timeoutIdentifier) { + clearTimeout(this._timeoutIdentifier); + this._timeoutIdentifier = null; + } + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Controllers/ApplicationCacheManager.js b/Source/WebInspectorUI/UserInterface/Controllers/ApplicationCacheManager.js new file mode 100644 index 000000000..61a55a9f7 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/ApplicationCacheManager.js @@ -0,0 +1,204 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.ApplicationCacheManager = class ApplicationCacheManager extends WebInspector.Object +{ + constructor() + { + super(); + + if (window.ApplicationCacheAgent) + ApplicationCacheAgent.enable(); + + WebInspector.Frame.addEventListener(WebInspector.Frame.Event.MainResourceDidChange, this._mainResourceDidChange, this); + WebInspector.Frame.addEventListener(WebInspector.Frame.Event.ChildFrameWasRemoved, this._childFrameWasRemoved, this); + + this._online = true; + + this.initialize(); + } + + // Public + + initialize() + { + this._applicationCacheObjects = {}; + + if (window.ApplicationCacheAgent) + ApplicationCacheAgent.getFramesWithManifests(this._framesWithManifestsLoaded.bind(this)); + } + + get applicationCacheObjects() + { + var applicationCacheObjects = []; + for (var id in this._applicationCacheObjects) + applicationCacheObjects.push(this._applicationCacheObjects[id]); + return applicationCacheObjects; + } + + networkStateUpdated(isNowOnline) + { + this._online = isNowOnline; + + this.dispatchEventToListeners(WebInspector.ApplicationCacheManager.Event.NetworkStateUpdated, {online: this._online}); + } + + get online() + { + return this._online; + } + + applicationCacheStatusUpdated(frameId, manifestURL, status) + { + var frame = WebInspector.frameResourceManager.frameForIdentifier(frameId); + if (!frame) + return; + + this._frameManifestUpdated(frame, manifestURL, status); + } + + requestApplicationCache(frame, callback) + { + function callbackWrapper(error, applicationCache) + { + if (error) { + callback(null); + return; + } + + callback(applicationCache); + } + + ApplicationCacheAgent.getApplicationCacheForFrame(frame.id, callbackWrapper); + } + + // Private + + _mainResourceDidChange(event) + { + console.assert(event.target instanceof WebInspector.Frame); + + if (event.target.isMainFrame()) { + // If we are dealing with the main frame, we want to clear our list of objects, because we are navigating to a new page. + this.initialize(); + + this.dispatchEventToListeners(WebInspector.ApplicationCacheManager.Event.Cleared); + + return; + } + + if (window.ApplicationCacheAgent) + ApplicationCacheAgent.getManifestForFrame(event.target.id, this._manifestForFrameLoaded.bind(this, event.target.id)); + } + + _childFrameWasRemoved(event) + { + this._frameManifestRemoved(event.data.childFrame); + } + + _manifestForFrameLoaded(frameId, error, manifestURL) + { + if (error) + return; + + var frame = WebInspector.frameResourceManager.frameForIdentifier(frameId); + if (!frame) + return; + + if (!manifestURL) + this._frameManifestRemoved(frame); + } + + _framesWithManifestsLoaded(error, framesWithManifests) + { + if (error) + return; + + for (var i = 0; i < framesWithManifests.length; ++i) { + var frame = WebInspector.frameResourceManager.frameForIdentifier(framesWithManifests[i].frameId); + if (!frame) + continue; + + this._frameManifestUpdated(frame, framesWithManifests[i].manifestURL, framesWithManifests[i].status); + } + } + + _frameManifestUpdated(frame, manifestURL, status) + { + if (status === WebInspector.ApplicationCacheManager.Status.Uncached) { + this._frameManifestRemoved(frame); + return; + } + + if (!manifestURL) + return; + + var manifestFrame = this._applicationCacheObjects[frame.id]; + if (manifestFrame && manifestURL !== manifestFrame.manifest.manifestURL) + this._frameManifestRemoved(frame); + + var oldStatus = manifestFrame ? manifestFrame.status : -1; + var statusChanged = manifestFrame && status !== oldStatus; + if (manifestFrame) + manifestFrame.status = status; + + if (!this._applicationCacheObjects[frame.id]) { + var cacheManifest = new WebInspector.ApplicationCacheManifest(manifestURL); + this._applicationCacheObjects[frame.id] = new WebInspector.ApplicationCacheFrame(frame, cacheManifest, status); + + this.dispatchEventToListeners(WebInspector.ApplicationCacheManager.Event.FrameManifestAdded, {frameManifest: this._applicationCacheObjects[frame.id]}); + } + + if (statusChanged) + this.dispatchEventToListeners(WebInspector.ApplicationCacheManager.Event.FrameManifestStatusChanged, {frameManifest: this._applicationCacheObjects[frame.id]}); + } + + _frameManifestRemoved(frame) + { + if (!this._applicationCacheObjects[frame.id]) + return; + + delete this._applicationCacheObjects[frame.id]; + + this.dispatchEventToListeners(WebInspector.ApplicationCacheManager.Event.FrameManifestRemoved, {frame}); + } +}; + +WebInspector.ApplicationCacheManager.Event = { + Cleared: "application-cache-manager-cleared", + FrameManifestAdded: "application-cache-manager-frame-manifest-added", + FrameManifestRemoved: "application-cache-manager-frame-manifest-removed", + FrameManifestStatusChanged: "application-cache-manager-frame-manifest-status-changed", + NetworkStateUpdated: "application-cache-manager-network-state-updated" +}; + +WebInspector.ApplicationCacheManager.Status = { + Uncached: 0, + Idle: 1, + Checking: 2, + Downloading: 3, + UpdateReady: 4, + Obsolete: 5 +}; diff --git a/Source/WebInspectorUI/UserInterface/Controllers/BasicBlockAnnotator.js b/Source/WebInspectorUI/UserInterface/Controllers/BasicBlockAnnotator.js new file mode 100644 index 000000000..b4b86f9d3 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/BasicBlockAnnotator.js @@ -0,0 +1,131 @@ +/* + * Copyright (C) 2015 Apple Inc. All rights reserved. + * Copyright (C) 2015 Saam Barati + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.BasicBlockAnnotator = class BasicBlockAnnotator extends WebInspector.Annotator +{ + constructor(sourceCodeTextEditor, script) + { + super(sourceCodeTextEditor); + + this._script = script; + this._basicBlockMarkers = new Map; // Only contains unexecuted basic blocks. + } + + // Protected + + clearAnnotations() + { + for (var key of this._basicBlockMarkers.keys()) + this._clearRangeForBasicBlockMarker(key); + } + + insertAnnotations() + { + if (!this.isActive()) + return; + this._annotateBasicBlockExecutionRanges(); + } + + // Private + + _annotateBasicBlockExecutionRanges() + { + var sourceID = this._script.id; + var startTime = Date.now(); + + this._script.target.RuntimeAgent.getBasicBlocks(sourceID, function(error, basicBlocks) { + if (error) { + console.error("Error in getting basic block locations: " + error); + return; + } + + if (!this.isActive()) + return; + + var {startOffset, endOffset} = this.sourceCodeTextEditor.visibleRangeOffsets(); + basicBlocks = basicBlocks.filter(function(block) { + // Viewport: [--] + // Block: [--] + if (block.startOffset > endOffset) + return false; + + // Viewport: [--] + // Block: [--] + if (block.endOffset < startOffset) + return false; + + return true; + }); + + for (var block of basicBlocks) { + var key = block.startOffset + ":" + block.endOffset; + var hasKey = this._basicBlockMarkers.has(key); + var hasExecuted = block.hasExecuted; + if (hasKey && hasExecuted) + this._clearRangeForBasicBlockMarker(key); + else if (!hasKey && !hasExecuted) { + var marker = this._highlightTextForBasicBlock(block); + this._basicBlockMarkers.set(key, marker); + } + } + + var totalTime = Date.now() - startTime; + var timeoutTime = Number.constrain(30 * totalTime, 500, 5000); + this._timeoutIdentifier = setTimeout(this.insertAnnotations.bind(this), timeoutTime); + }.bind(this)); + } + + _highlightTextForBasicBlock(basicBlock) + { + console.assert(basicBlock.startOffset <= basicBlock.endOffset && basicBlock.startOffset >= 0 && basicBlock.endOffset >= 0, "" + basicBlock.startOffset + ":" + basicBlock.endOffset); + console.assert(!basicBlock.hasExecuted); + + var startPosition = this.sourceCodeTextEditor.originalOffsetToCurrentPosition(basicBlock.startOffset); + var endPosition = this.sourceCodeTextEditor.originalOffsetToCurrentPosition(basicBlock.endOffset); + if (this._isTextRangeOnlyClosingBrace(startPosition, endPosition)) + return null; + + var marker = this.sourceCodeTextEditor.addStyleToTextRange(startPosition, endPosition, WebInspector.BasicBlockAnnotator.HasNotExecutedClassName); + return marker; + } + + _isTextRangeOnlyClosingBrace(startPosition, endPosition) + { + var isOnlyClosingBrace = /^\s*\}$/; + return isOnlyClosingBrace.test(this.sourceCodeTextEditor.getTextInRange(startPosition, endPosition)); + } + + _clearRangeForBasicBlockMarker(key) + { + console.assert(this._basicBlockMarkers.has(key)); + var marker = this._basicBlockMarkers.get(key); + if (marker) + marker.clear(); + this._basicBlockMarkers.delete(key); + } +}; + +WebInspector.BasicBlockAnnotator.HasNotExecutedClassName = "basic-block-has-not-executed"; diff --git a/Source/WebInspectorUI/UserInterface/Controllers/BranchManager.js b/Source/WebInspectorUI/UserInterface/Controllers/BranchManager.js new file mode 100644 index 000000000..6dc8de1ca --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/BranchManager.js @@ -0,0 +1,110 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.BranchManager = class BranchManager extends WebInspector.Object +{ + constructor() + { + super(); + + WebInspector.Frame.addEventListener(WebInspector.Frame.Event.MainResourceDidChange, this._mainResourceDidChange, this); + + this.initialize(); + } + + // Public + + initialize() + { + this._originalBranch = new WebInspector.Branch(WebInspector.UIString("Original"), null, true); + this._currentBranch = this._originalBranch.fork(WebInspector.UIString("Working Copy")); + this._branches = [this._originalBranch, this._currentBranch]; + } + + get branches() + { + return this._branches; + } + + get currentBranch() + { + return this._currentBranch; + } + + set currentBranch(branch) + { + console.assert(branch instanceof WebInspector.Branch); + if (!(branch instanceof WebInspector.Branch)) + return; + + this._currentBranch.revert(); + + this._currentBranch = branch; + + this._currentBranch.apply(); + } + + createBranch(displayName, fromBranch) + { + if (!fromBranch) + fromBranch = this._originalBranch; + + console.assert(fromBranch instanceof WebInspector.Branch); + if (!(fromBranch instanceof WebInspector.Branch)) + return null; + + var newBranch = fromBranch.fork(displayName); + this._branches.push(newBranch); + return newBranch; + } + + deleteBranch(branch) + { + console.assert(branch instanceof WebInspector.Branch); + if (!(branch instanceof WebInspector.Branch)) + return; + + console.assert(branch !== this._originalBranch); + if (branch === this._originalBranch) + return; + + this._branches.remove(branch); + + if (branch === this._currentBranch) + this._currentBranch = this._originalBranch; + } + + // Private + + _mainResourceDidChange(event) + { + console.assert(event.target instanceof WebInspector.Frame); + + if (!event.target.isMainFrame()) + return; + + this.initialize(); + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Controllers/BreakpointLogMessageLexer.js b/Source/WebInspectorUI/UserInterface/Controllers/BreakpointLogMessageLexer.js new file mode 100644 index 000000000..071704a6b --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/BreakpointLogMessageLexer.js @@ -0,0 +1,197 @@ +/* + * Copyright (C) 2016 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.BreakpointLogMessageLexer = class BreakpointLogMessageLexer extends WebInspector.Object +{ + constructor() + { + super(); + + this._stateFunctions = { + [WebInspector.BreakpointLogMessageLexer.State.Expression]: this._expression, + [WebInspector.BreakpointLogMessageLexer.State.PlainText]: this._plainText, + [WebInspector.BreakpointLogMessageLexer.State.PossiblePlaceholder]: this._possiblePlaceholder, + [WebInspector.BreakpointLogMessageLexer.State.RegExpOrStringLiteral]: this._regExpOrStringLiteral, + }; + + this.reset(); + } + + // Public + + tokenize(input) + { + this.reset(); + this._input = input; + + while (this._index < this._input.length) { + let stateFunction = this._stateFunctions[this._states.lastValue]; + console.assert(stateFunction); + if (!stateFunction) { + this.reset(); + return null; + } + + stateFunction.call(this); + } + + // Needed for trailing plain text. + this._finishPlainText(); + + return this._tokens; + } + + reset() + { + this._input = ""; + this._buffer = ""; + + this._index = 0; + this._states = [WebInspector.BreakpointLogMessageLexer.State.PlainText]; + this._literalStartCharacter = ""; + this._curlyBraceDepth = 0; + this._tokens = []; + } + + // Private + + _finishPlainText() + { + this._appendToken(WebInspector.BreakpointLogMessageLexer.TokenType.PlainText); + } + + _finishExpression() + { + this._appendToken(WebInspector.BreakpointLogMessageLexer.TokenType.Expression); + } + + _appendToken(type) + { + if (!this._buffer) + return; + + this._tokens.push({type, data: this._buffer}); + this._buffer = ""; + } + + _consume() + { + console.assert(this._index < this._input.length); + + let character = this._peek(); + this._index++; + return character; + } + + _peek() + { + return this._input[this._index] || null; + } + + // States + + _expression() + { + let character = this._consume(); + + if (character === "}") { + if (this._curlyBraceDepth === 0) { + this._finishExpression(); + + console.assert(this._states.lastValue === WebInspector.BreakpointLogMessageLexer.State.Expression); + this._states.pop(); + return; + } + + this._curlyBraceDepth--; + } + + this._buffer += character; + + if (character === "/" || character === "\"" || character === "'") { + this._literalStartCharacter = character; + this._states.push(WebInspector.BreakpointLogMessageLexer.State.RegExpOrStringLiteral); + } else if (character === "{") + this._curlyBraceDepth++; + } + + _plainText() + { + let character = this._peek(); + + if (character === "$") + this._states.push(WebInspector.BreakpointLogMessageLexer.State.PossiblePlaceholder); + else { + this._buffer += character; + this._consume(); + } + } + + _possiblePlaceholder() + { + let character = this._consume(); + console.assert(character === "$"); + let nextCharacter = this._peek(); + + console.assert(this._states.lastValue === WebInspector.BreakpointLogMessageLexer.State.PossiblePlaceholder); + this._states.pop(); + + if (nextCharacter === "{") { + this._finishPlainText(); + this._consume(); + this._states.push(WebInspector.BreakpointLogMessageLexer.State.Expression); + } else + this._buffer += character; + } + + _regExpOrStringLiteral() + { + let character = this._consume(); + this._buffer += character; + + if (character === "\\") { + if (this._peek() !== null) + this._buffer += this._consume(); + return; + } + + if (character === this._literalStartCharacter) { + console.assert(this._states.lastValue === WebInspector.BreakpointLogMessageLexer.State.RegExpOrStringLiteral); + this._states.pop(); + } + } +}; + +WebInspector.BreakpointLogMessageLexer.State = { + Expression: Symbol("expression"), + PlainText: Symbol("plain-text"), + PossiblePlaceholder: Symbol("possible-placeholder"), + RegExpOrStringLiteral: Symbol("regexp-or-string-literal"), +}; + +WebInspector.BreakpointLogMessageLexer.TokenType = { + PlainText: "token-type-plain-text", + Expression: "token-type-expression", +}; diff --git a/Source/WebInspectorUI/UserInterface/Controllers/BreakpointPopoverController.js b/Source/WebInspectorUI/UserInterface/Controllers/BreakpointPopoverController.js new file mode 100644 index 000000000..1b30fc98c --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/BreakpointPopoverController.js @@ -0,0 +1,382 @@ +/* + * Copyright (C) 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.BreakpointPopoverController = class BreakpointPopoverController extends WebInspector.Object +{ + constructor() + { + super(); + + this._breakpoint = null; + this._popover = null; + this._popoverContentElement = null; + } + + // Public + + appendContextMenuItems(contextMenu, breakpoint, breakpointDisplayElement) + { + console.assert(document.body.contains(breakpointDisplayElement), "Breakpoint popover display element must be in the DOM."); + + const editBreakpoint = () => { + console.assert(!this._popover, "Breakpoint popover already exists."); + if (this._popover) + return; + + this._createPopoverContent(breakpoint); + this._popover = new WebInspector.Popover(this); + this._popover.content = this._popoverContentElement; + + let bounds = WebInspector.Rect.rectFromClientRect(breakpointDisplayElement.getBoundingClientRect()); + bounds.origin.x -= 1; // Move the anchor left one pixel so it looks more centered. + this._popover.present(bounds.pad(2), [WebInspector.RectEdge.MAX_Y]); + }; + + const removeBreakpoint = () => { + WebInspector.debuggerManager.removeBreakpoint(breakpoint); + }; + + const toggleBreakpoint = () => { + breakpoint.disabled = !breakpoint.disabled; + }; + + const toggleAutoContinue = () => { + breakpoint.autoContinue = !breakpoint.autoContinue; + }; + + const revealOriginalSourceCodeLocation = () => { + WebInspector.showOriginalOrFormattedSourceCodeLocation(breakpoint.sourceCodeLocation); + }; + + if (WebInspector.debuggerManager.isBreakpointEditable(breakpoint)) + contextMenu.appendItem(WebInspector.UIString("Edit Breakpoint…"), editBreakpoint); + + if (breakpoint.autoContinue && !breakpoint.disabled) { + contextMenu.appendItem(WebInspector.UIString("Disable Breakpoint"), toggleBreakpoint); + contextMenu.appendItem(WebInspector.UIString("Cancel Automatic Continue"), toggleAutoContinue); + } else if (!breakpoint.disabled) + contextMenu.appendItem(WebInspector.UIString("Disable Breakpoint"), toggleBreakpoint); + else + contextMenu.appendItem(WebInspector.UIString("Enable Breakpoint"), toggleBreakpoint); + + if (!breakpoint.autoContinue && !breakpoint.disabled && breakpoint.actions.length) + contextMenu.appendItem(WebInspector.UIString("Set to Automatically Continue"), toggleAutoContinue); + + if (WebInspector.debuggerManager.isBreakpointRemovable(breakpoint)) { + contextMenu.appendSeparator(); + contextMenu.appendItem(WebInspector.UIString("Delete Breakpoint"), removeBreakpoint); + } + + if (breakpoint._sourceCodeLocation.hasMappedLocation()) { + contextMenu.appendSeparator(); + contextMenu.appendItem(WebInspector.UIString("Reveal in Original Resource"), revealOriginalSourceCodeLocation); + } + } + + // CodeMirrorCompletionController delegate + + completionControllerShouldAllowEscapeCompletion() + { + return false; + } + + // Private + + _createPopoverContent(breakpoint) + { + console.assert(!this._popoverContentElement, "Popover content element already exists."); + if (this._popoverContentElement) + return; + + this._breakpoint = breakpoint; + this._popoverContentElement = document.createElement("div"); + this._popoverContentElement.className = "edit-breakpoint-popover-content"; + + let checkboxElement = document.createElement("input"); + checkboxElement.type = "checkbox"; + checkboxElement.checked = !this._breakpoint.disabled; + checkboxElement.addEventListener("change", this._popoverToggleEnabledCheckboxChanged.bind(this)); + + let checkboxLabel = document.createElement("label"); + checkboxLabel.className = "toggle"; + checkboxLabel.appendChild(checkboxElement); + checkboxLabel.append(this._breakpoint.sourceCodeLocation.displayLocationString()); + + let table = document.createElement("table"); + + let conditionRow = table.appendChild(document.createElement("tr")); + let conditionHeader = conditionRow.appendChild(document.createElement("th")); + let conditionData = conditionRow.appendChild(document.createElement("td")); + let conditionLabel = conditionHeader.appendChild(document.createElement("label")); + conditionLabel.textContent = WebInspector.UIString("Condition"); + let conditionEditorElement = conditionData.appendChild(document.createElement("div")); + conditionEditorElement.classList.add("edit-breakpoint-popover-condition", WebInspector.SyntaxHighlightedStyleClassName); + + this._conditionCodeMirror = WebInspector.CodeMirrorEditor.create(conditionEditorElement, { + extraKeys: {Tab: false}, + lineWrapping: false, + mode: "text/javascript", + matchBrackets: true, + placeholder: WebInspector.UIString("Conditional expression"), + scrollbarStyle: null, + value: this._breakpoint.condition || "", + }); + + let conditionCodeMirrorInputField = this._conditionCodeMirror.getInputField(); + conditionCodeMirrorInputField.id = "codemirror-condition-input-field"; + conditionLabel.setAttribute("for", conditionCodeMirrorInputField.id); + + this._conditionCodeMirrorEscapeOrEnterKeyHandler = this._conditionCodeMirrorEscapeOrEnterKey.bind(this); + this._conditionCodeMirror.addKeyMap({ + "Esc": this._conditionCodeMirrorEscapeOrEnterKeyHandler, + "Enter": this._conditionCodeMirrorEscapeOrEnterKeyHandler, + }); + + this._conditionCodeMirror.on("change", this._conditionCodeMirrorChanged.bind(this)); + this._conditionCodeMirror.on("beforeChange", this._conditionCodeMirrorBeforeChange.bind(this)); + + let completionController = new WebInspector.CodeMirrorCompletionController(this._conditionCodeMirror, this); + completionController.addExtendedCompletionProvider("javascript", WebInspector.javaScriptRuntimeCompletionProvider); + + // CodeMirror needs a refresh after the popover displays, to layout, otherwise it doesn't appear. + setTimeout(() => { + this._conditionCodeMirror.refresh(); + this._conditionCodeMirror.focus(); + }, 0); + + // COMPATIBILITY (iOS 7): Debugger.setBreakpoint did not support options. + if (DebuggerAgent.setBreakpoint.supports("options")) { + // COMPATIBILITY (iOS 9): Legacy backends don't support breakpoint ignore count. Since support + // can't be tested directly, check for CSS.getSupportedSystemFontFamilyNames. + // FIXME: Use explicit version checking once https://webkit.org/b/148680 is fixed. + if (CSSAgent.getSupportedSystemFontFamilyNames) { + let ignoreCountRow = table.appendChild(document.createElement("tr")); + let ignoreCountHeader = ignoreCountRow.appendChild(document.createElement("th")); + let ignoreCountLabel = ignoreCountHeader.appendChild(document.createElement("label")); + let ignoreCountData = ignoreCountRow.appendChild(document.createElement("td")); + this._ignoreCountInput = ignoreCountData.appendChild(document.createElement("input")); + this._ignoreCountInput.id = "edit-breakpoint-popover-ignore"; + this._ignoreCountInput.type = "number"; + this._ignoreCountInput.min = 0; + this._ignoreCountInput.value = 0; + this._ignoreCountInput.addEventListener("change", this._popoverIgnoreInputChanged.bind(this)); + + ignoreCountLabel.setAttribute("for", this._ignoreCountInput.id); + ignoreCountLabel.textContent = WebInspector.UIString("Ignore"); + + this._ignoreCountText = ignoreCountData.appendChild(document.createElement("span")); + this._updateIgnoreCountText(); + } + + let actionRow = table.appendChild(document.createElement("tr")); + let actionHeader = actionRow.appendChild(document.createElement("th")); + let actionData = this._actionsContainer = actionRow.appendChild(document.createElement("td")); + let actionLabel = actionHeader.appendChild(document.createElement("label")); + actionLabel.textContent = WebInspector.UIString("Action"); + + if (!this._breakpoint.actions.length) + this._popoverActionsCreateAddActionButton(); + else { + this._popoverContentElement.classList.add(WebInspector.BreakpointPopoverController.WidePopoverClassName); + for (let i = 0; i < this._breakpoint.actions.length; ++i) { + let breakpointActionView = new WebInspector.BreakpointActionView(this._breakpoint.actions[i], this, true); + this._popoverActionsInsertBreakpointActionView(breakpointActionView, i); + } + } + + let optionsRow = this._popoverOptionsRowElement = table.appendChild(document.createElement("tr")); + if (!this._breakpoint.actions.length) + optionsRow.classList.add(WebInspector.BreakpointPopoverController.HiddenStyleClassName); + let optionsHeader = optionsRow.appendChild(document.createElement("th")); + let optionsData = optionsRow.appendChild(document.createElement("td")); + let optionsLabel = optionsHeader.appendChild(document.createElement("label")); + let optionsCheckbox = this._popoverOptionsCheckboxElement = optionsData.appendChild(document.createElement("input")); + let optionsCheckboxLabel = optionsData.appendChild(document.createElement("label")); + optionsCheckbox.id = "edit-breakpoint-popoover-auto-continue"; + optionsCheckbox.type = "checkbox"; + optionsCheckbox.checked = this._breakpoint.autoContinue; + optionsCheckbox.addEventListener("change", this._popoverToggleAutoContinueCheckboxChanged.bind(this)); + optionsLabel.textContent = WebInspector.UIString("Options"); + optionsCheckboxLabel.setAttribute("for", optionsCheckbox.id); + optionsCheckboxLabel.textContent = WebInspector.UIString("Automatically continue after evaluating"); + } + + this._popoverContentElement.appendChild(checkboxLabel); + this._popoverContentElement.appendChild(table); + } + + _popoverToggleEnabledCheckboxChanged(event) + { + this._breakpoint.disabled = !event.target.checked; + } + + _conditionCodeMirrorChanged(codeMirror, change) + { + this._breakpoint.condition = (codeMirror.getValue() || "").trim(); + } + + _conditionCodeMirrorBeforeChange(codeMirror, change) + { + if (change.update) { + let newText = change.text.join("").replace(/\n/g, ""); + change.update(change.from, change.to, [newText]); + } + + return true; + } + + _conditionCodeMirrorEscapeOrEnterKey() + { + if (!this._popover) + return; + + this._popover.dismiss(); + } + + _popoverIgnoreInputChanged(event) + { + let ignoreCount = 0; + if (event.target.value) { + ignoreCount = parseInt(event.target.value, 10); + if (isNaN(ignoreCount) || ignoreCount < 0) + ignoreCount = 0; + } + + this._ignoreCountInput.value = ignoreCount; + this._breakpoint.ignoreCount = ignoreCount; + + this._updateIgnoreCountText(); + } + + _popoverToggleAutoContinueCheckboxChanged(event) + { + this._breakpoint.autoContinue = event.target.checked; + } + + _popoverActionsCreateAddActionButton() + { + this._popoverContentElement.classList.remove(WebInspector.BreakpointPopoverController.WidePopoverClassName); + this._actionsContainer.removeChildren(); + + let addActionButton = this._actionsContainer.appendChild(document.createElement("button")); + addActionButton.textContent = WebInspector.UIString("Add Action"); + addActionButton.addEventListener("click", this._popoverActionsAddActionButtonClicked.bind(this)); + } + + _popoverActionsAddActionButtonClicked(event) + { + this._popoverContentElement.classList.add(WebInspector.BreakpointPopoverController.WidePopoverClassName); + this._actionsContainer.removeChildren(); + + let newAction = this._breakpoint.createAction(WebInspector.Breakpoint.DefaultBreakpointActionType); + let newBreakpointActionView = new WebInspector.BreakpointActionView(newAction, this); + this._popoverActionsInsertBreakpointActionView(newBreakpointActionView, -1); + this._popoverOptionsRowElement.classList.remove(WebInspector.BreakpointPopoverController.HiddenStyleClassName); + this._popover.update(); + } + + _popoverActionsInsertBreakpointActionView(breakpointActionView, index) + { + if (index === -1) + this._actionsContainer.appendChild(breakpointActionView.element); + else { + let nextElement = this._actionsContainer.children[index + 1] || null; + this._actionsContainer.insertBefore(breakpointActionView.element, nextElement); + } + } + + _updateIgnoreCountText() + { + if (this._breakpoint.ignoreCount === 1) + this._ignoreCountText.textContent = WebInspector.UIString("time before stopping"); + else + this._ignoreCountText.textContent = WebInspector.UIString("times before stopping"); + } + + breakpointActionViewAppendActionView(breakpointActionView, newAction) + { + let newBreakpointActionView = new WebInspector.BreakpointActionView(newAction, this); + + let index = 0; + let children = this._actionsContainer.children; + for (let i = 0; children.length; ++i) { + if (children[i] === breakpointActionView.element) { + index = i; + break; + } + } + + this._popoverActionsInsertBreakpointActionView(newBreakpointActionView, index); + this._popoverOptionsRowElement.classList.remove(WebInspector.BreakpointPopoverController.HiddenStyleClassName); + + this._popover.update(); + } + + breakpointActionViewRemoveActionView(breakpointActionView) + { + breakpointActionView.element.remove(); + + if (!this._actionsContainer.children.length) { + this._popoverActionsCreateAddActionButton(); + this._popoverOptionsRowElement.classList.add(WebInspector.BreakpointPopoverController.HiddenStyleClassName); + this._popoverOptionsCheckboxElement.checked = false; + } + + this._popover.update(); + } + + breakpointActionViewResized(breakpointActionView) + { + this._popover.update(); + } + + willDismissPopover(popover) + { + console.assert(this._popover === popover); + this._popoverContentElement = null; + this._popoverOptionsRowElement = null; + this._popoverOptionsCheckboxElement = null; + this._actionsContainer = null; + this._popover = null; + } + + didDismissPopover(popover) + { + // Remove Evaluate and Probe actions that have no data. + let emptyActions = this._breakpoint.actions.filter(function(action) { + if (action.type !== WebInspector.BreakpointAction.Type.Evaluate && action.type !== WebInspector.BreakpointAction.Type.Probe) + return false; + return !(action.data && action.data.trim()); + }); + + for (let action of emptyActions) + this._breakpoint.removeAction(action); + + this._breakpoint = null; + } +}; + +WebInspector.BreakpointPopoverController.WidePopoverClassName = "wide"; +WebInspector.BreakpointPopoverController.HiddenStyleClassName = "hidden"; diff --git a/Source/WebInspectorUI/UserInterface/Controllers/CSSStyleManager.js b/Source/WebInspectorUI/UserInterface/Controllers/CSSStyleManager.js new file mode 100644 index 000000000..8e101e31f --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/CSSStyleManager.js @@ -0,0 +1,551 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.CSSStyleManager = class CSSStyleManager extends WebInspector.Object +{ + constructor() + { + super(); + + if (window.CSSAgent) + CSSAgent.enable(); + + WebInspector.Frame.addEventListener(WebInspector.Frame.Event.MainResourceDidChange, this._mainResourceDidChange, this); + WebInspector.Frame.addEventListener(WebInspector.Frame.Event.ResourceWasAdded, this._resourceAdded, this); + WebInspector.Resource.addEventListener(WebInspector.SourceCode.Event.ContentDidChange, this._resourceContentDidChange, this); + WebInspector.Resource.addEventListener(WebInspector.Resource.Event.TypeDidChange, this._resourceTypeDidChange, this); + + WebInspector.DOMNode.addEventListener(WebInspector.DOMNode.Event.AttributeModified, this._nodeAttributesDidChange, this); + WebInspector.DOMNode.addEventListener(WebInspector.DOMNode.Event.AttributeRemoved, this._nodeAttributesDidChange, this); + WebInspector.DOMNode.addEventListener(WebInspector.DOMNode.Event.EnabledPseudoClassesChanged, this._nodePseudoClassesDidChange, this); + + this._colorFormatSetting = new WebInspector.Setting("default-color-format", WebInspector.Color.Format.Original); + + this._styleSheetIdentifierMap = new Map; + this._styleSheetFrameURLMap = new Map; + this._nodeStylesMap = {}; + + // COMPATIBILITY (iOS 9): Legacy backends did not send stylesheet + // added/removed events and must be fetched manually. + this._fetchedInitialStyleSheets = window.CSSAgent && window.CSSAgent.hasEvent("styleSheetAdded"); + } + + // Static + + static protocolStyleSheetOriginToEnum(origin) + { + switch (origin) { + case CSSAgent.StyleSheetOrigin.Regular: + return WebInspector.CSSStyleSheet.Type.Author; + case CSSAgent.StyleSheetOrigin.User: + return WebInspector.CSSStyleSheet.Type.User; + case CSSAgent.StyleSheetOrigin.UserAgent: + return WebInspector.CSSStyleSheet.Type.UserAgent; + case CSSAgent.StyleSheetOrigin.Inspector: + return WebInspector.CSSStyleSheet.Type.Inspector; + default: + console.assert(false, "Unknown CSS.StyleSheetOrigin", origin); + return CSSAgent.StyleSheetOrigin.Regular; + } + } + + static protocolMediaSourceToEnum(source) + { + switch (source) { + case CSSAgent.CSSMediaSource.MediaRule: + return WebInspector.CSSMedia.Type.MediaRule; + case CSSAgent.CSSMediaSource.ImportRule: + return WebInspector.CSSMedia.Type.ImportRule; + case CSSAgent.CSSMediaSource.LinkedSheet: + return WebInspector.CSSMedia.Type.LinkedStyleSheet; + case CSSAgent.CSSMediaSource.InlineSheet: + return WebInspector.CSSMedia.Type.InlineStyleSheet; + default: + console.assert(false, "Unknown CSS.CSSMediaSource", source); + return WebInspector.CSSMedia.Type.MediaRule; + } + } + + // Public + + get preferredColorFormat() + { + return this._colorFormatSetting.value; + } + + get styleSheets() + { + return [...this._styleSheetIdentifierMap.values()]; + } + + canForcePseudoClasses() + { + return window.CSSAgent && !!CSSAgent.forcePseudoState; + } + + propertyNameHasOtherVendorPrefix(name) + { + if (!name || name.length < 4 || name.charAt(0) !== "-") + return false; + + var match = name.match(/^(?:-moz-|-ms-|-o-|-epub-)/); + if (!match) + return false; + + return true; + } + + propertyValueHasOtherVendorKeyword(value) + { + var match = value.match(/(?:-moz-|-ms-|-o-|-epub-)[-\w]+/); + if (!match) + return false; + + return true; + } + + canonicalNameForPropertyName(name) + { + if (!name || name.length < 8 || name.charAt(0) !== "-") + return name; + + var match = name.match(/^(?:-webkit-|-khtml-|-apple-)(.+)/); + if (!match) + return name; + + return match[1]; + } + + fetchStyleSheetsIfNeeded() + { + if (this._fetchedInitialStyleSheets) + return; + + this._fetchInfoForAllStyleSheets(function() {}); + } + + styleSheetForIdentifier(id) + { + let styleSheet = this._styleSheetIdentifierMap.get(id); + if (styleSheet) + return styleSheet; + + styleSheet = new WebInspector.CSSStyleSheet(id); + this._styleSheetIdentifierMap.set(id, styleSheet); + return styleSheet; + } + + stylesForNode(node) + { + if (node.id in this._nodeStylesMap) + return this._nodeStylesMap[node.id]; + + var styles = new WebInspector.DOMNodeStyles(node); + this._nodeStylesMap[node.id] = styles; + return styles; + } + + preferredInspectorStyleSheetForFrame(frame, callback) + { + var inspectorStyleSheets = this._inspectorStyleSheetsForFrame(frame); + for (let styleSheet of inspectorStyleSheets) { + if (styleSheet[WebInspector.CSSStyleManager.PreferredInspectorStyleSheetSymbol]) { + callback(styleSheet); + return; + } + } + + if (CSSAgent.createStyleSheet) { + CSSAgent.createStyleSheet(frame.id, function(error, styleSheetId) { + let styleSheet = WebInspector.cssStyleManager.styleSheetForIdentifier(styleSheetId); + styleSheet[WebInspector.CSSStyleManager.PreferredInspectorStyleSheetSymbol] = true; + callback(styleSheet); + }); + return; + } + + // COMPATIBILITY (iOS 9): CSS.createStyleSheet did not exist. + // Legacy backends can only create the Inspector StyleSheet through CSS.addRule. + // Exploit that to create the Inspector StyleSheet for the document.body node in + // this frame, then get the StyleSheet for the new rule. + + let expression = appendWebInspectorSourceURL("document"); + let contextId = frame.pageExecutionContext.id; + RuntimeAgent.evaluate.invoke({expression, objectGroup: "", includeCommandLineAPI: false, doNotPauseOnExceptionsAndMuteConsole: true, contextId, returnByValue: false, generatePreview: false}, documentAvailable); + + function documentAvailable(error, documentRemoteObjectPayload) + { + if (error) { + callback(null); + return; + } + + let remoteObject = WebInspector.RemoteObject.fromPayload(documentRemoteObjectPayload); + remoteObject.pushNodeToFrontend(documentNodeAvailable.bind(null, remoteObject)); + } + + function documentNodeAvailable(remoteObject, documentNodeId) + { + remoteObject.release(); + + if (!documentNodeId) { + callback(null); + return; + } + + DOMAgent.querySelector(documentNodeId, "body", bodyNodeAvailable); + } + + function bodyNodeAvailable(error, bodyNodeId) + { + if (error) { + console.error(error); + callback(null); + return; + } + + let selector = ""; // Intentionally empty. + CSSAgent.addRule(bodyNodeId, selector, cssRuleAvailable); + } + + function cssRuleAvailable(error, payload) + { + if (error || !payload.ruleId) { + callback(null); + return; + } + + let styleSheetId = payload.ruleId.styleSheetId; + let styleSheet = WebInspector.cssStyleManager.styleSheetForIdentifier(styleSheetId); + if (!styleSheet) { + callback(null); + return; + } + + styleSheet[WebInspector.CSSStyleManager.PreferredInspectorStyleSheetSymbol] = true; + + console.assert(styleSheet.isInspectorStyleSheet()); + console.assert(styleSheet.parentFrame === frame); + + callback(styleSheet); + } + } + + mediaTypeChanged() + { + // Act the same as if media queries changed. + this.mediaQueryResultChanged(); + } + + // Protected + + mediaQueryResultChanged() + { + // Called from WebInspector.CSSObserver. + + for (var key in this._nodeStylesMap) + this._nodeStylesMap[key].mediaQueryResultDidChange(); + } + + styleSheetChanged(styleSheetIdentifier) + { + // Called from WebInspector.CSSObserver. + var styleSheet = this.styleSheetForIdentifier(styleSheetIdentifier); + console.assert(styleSheet); + + // Do not observe inline styles + if (styleSheet.isInlineStyleAttributeStyleSheet()) + return; + + styleSheet.noteContentDidChange(); + this._updateResourceContent(styleSheet); + } + + styleSheetAdded(styleSheetInfo) + { + console.assert(!this._styleSheetIdentifierMap.has(styleSheetInfo.styleSheetId), "Attempted to add a CSSStyleSheet but identifier was already in use"); + let styleSheet = this.styleSheetForIdentifier(styleSheetInfo.styleSheetId); + let parentFrame = WebInspector.frameResourceManager.frameForIdentifier(styleSheetInfo.frameId); + let origin = WebInspector.CSSStyleManager.protocolStyleSheetOriginToEnum(styleSheetInfo.origin); + styleSheet.updateInfo(styleSheetInfo.sourceURL, parentFrame, origin, styleSheetInfo.isInline, styleSheetInfo.startLine, styleSheetInfo.startColumn); + + this.dispatchEventToListeners(WebInspector.CSSStyleManager.Event.StyleSheetAdded, {styleSheet}); + } + + styleSheetRemoved(styleSheetIdentifier) + { + let styleSheet = this._styleSheetIdentifierMap.get(styleSheetIdentifier); + console.assert(styleSheet, "Attempted to remove a CSSStyleSheet that was not tracked"); + if (!styleSheet) + return; + + this._styleSheetIdentifierMap.delete(styleSheetIdentifier); + + this.dispatchEventToListeners(WebInspector.CSSStyleManager.Event.StyleSheetRemoved, {styleSheet}); + } + + // Private + + _inspectorStyleSheetsForFrame(frame) + { + let styleSheets = []; + + for (let styleSheet of this.styleSheets) { + if (styleSheet.isInspectorStyleSheet() && styleSheet.parentFrame === frame) + styleSheets.push(styleSheet); + } + + return styleSheets; + } + + _nodePseudoClassesDidChange(event) + { + var node = event.target; + + for (var key in this._nodeStylesMap) { + var nodeStyles = this._nodeStylesMap[key]; + if (nodeStyles.node !== node && !nodeStyles.node.isDescendant(node)) + continue; + nodeStyles.pseudoClassesDidChange(node); + } + } + + _nodeAttributesDidChange(event) + { + var node = event.target; + + for (var key in this._nodeStylesMap) { + var nodeStyles = this._nodeStylesMap[key]; + if (nodeStyles.node !== node && !nodeStyles.node.isDescendant(node)) + continue; + nodeStyles.attributeDidChange(node, event.data.name); + } + } + + _mainResourceDidChange(event) + { + console.assert(event.target instanceof WebInspector.Frame); + + if (!event.target.isMainFrame()) + return; + + // Clear our maps when the main frame navigates. + + this._fetchedInitialStyleSheets = window.CSSAgent && window.CSSAgent.hasEvent("styleSheetAdded"); + this._styleSheetIdentifierMap.clear(); + this._styleSheetFrameURLMap.clear(); + this._nodeStylesMap = {}; + } + + _resourceAdded(event) + { + console.assert(event.target instanceof WebInspector.Frame); + + var resource = event.data.resource; + console.assert(resource); + + if (resource.type !== WebInspector.Resource.Type.Stylesheet) + return; + + this._clearStyleSheetsForResource(resource); + } + + _resourceTypeDidChange(event) + { + console.assert(event.target instanceof WebInspector.Resource); + + var resource = event.target; + if (resource.type !== WebInspector.Resource.Type.Stylesheet) + return; + + this._clearStyleSheetsForResource(resource); + } + + _clearStyleSheetsForResource(resource) + { + // Clear known stylesheets for this URL and frame. This will cause the stylesheets to + // be updated next time _fetchInfoForAllStyleSheets is called. + this._styleSheetIdentifierMap.delete(this._frameURLMapKey(resource.parentFrame, resource.url)); + } + + _frameURLMapKey(frame, url) + { + return frame.id + ":" + url; + } + + _lookupStyleSheetForResource(resource, callback) + { + this._lookupStyleSheet(resource.parentFrame, resource.url, callback); + } + + _lookupStyleSheet(frame, url, callback) + { + console.assert(frame instanceof WebInspector.Frame); + + let key = this._frameURLMapKey(frame, url); + + function styleSheetsFetched() + { + callback(this._styleSheetFrameURLMap.get(key) || null); + } + + let styleSheet = this._styleSheetFrameURLMap.get(key) || null; + if (styleSheet) + callback(styleSheet); + else + this._fetchInfoForAllStyleSheets(styleSheetsFetched.bind(this)); + } + + _fetchInfoForAllStyleSheets(callback) + { + console.assert(typeof callback === "function"); + + function processStyleSheets(error, styleSheets) + { + this._styleSheetFrameURLMap.clear(); + + if (error) { + callback(); + return; + } + + for (let styleSheetInfo of styleSheets) { + let parentFrame = WebInspector.frameResourceManager.frameForIdentifier(styleSheetInfo.frameId); + let origin = WebInspector.CSSStyleManager.protocolStyleSheetOriginToEnum(styleSheetInfo.origin); + + // COMPATIBILITY (iOS 9): The info did not have 'isInline', 'startLine', and 'startColumn', so make false and 0 in these cases. + let isInline = styleSheetInfo.isInline || false; + let startLine = styleSheetInfo.startLine || 0; + let startColumn = styleSheetInfo.startColumn || 0; + + let styleSheet = this.styleSheetForIdentifier(styleSheetInfo.styleSheetId); + styleSheet.updateInfo(styleSheetInfo.sourceURL, parentFrame, origin, isInline, startLine, startColumn); + + let key = this._frameURLMapKey(parentFrame, styleSheetInfo.sourceURL); + this._styleSheetFrameURLMap.set(key, styleSheet); + } + + callback(); + } + + CSSAgent.getAllStyleSheets(processStyleSheets.bind(this)); + } + + _resourceContentDidChange(event) + { + var resource = event.target; + if (resource === this._ignoreResourceContentDidChangeEventForResource) + return; + + // Ignore if it isn't a CSS stylesheet. + if (resource.type !== WebInspector.Resource.Type.Stylesheet || resource.syntheticMIMEType !== "text/css") + return; + + function applyStyleSheetChanges() + { + function styleSheetFound(styleSheet) + { + resource.__pendingChangeTimeout = undefined; + + console.assert(styleSheet); + if (!styleSheet) + return; + + // To prevent updating a TextEditor's content while the user is typing in it we want to + // ignore the next _updateResourceContent call. + resource.__ignoreNextUpdateResourceContent = true; + + WebInspector.branchManager.currentBranch.revisionForRepresentedObject(styleSheet).content = resource.content; + } + + this._lookupStyleSheetForResource(resource, styleSheetFound.bind(this)); + } + + if (resource.__pendingChangeTimeout) + clearTimeout(resource.__pendingChangeTimeout); + resource.__pendingChangeTimeout = setTimeout(applyStyleSheetChanges.bind(this), 500); + } + + _updateResourceContent(styleSheet) + { + console.assert(styleSheet); + + function fetchedStyleSheetContent(parameters) + { + var styleSheet = parameters.sourceCode; + var content = parameters.content; + + styleSheet.__pendingChangeTimeout = undefined; + + console.assert(styleSheet.url); + if (!styleSheet.url) + return; + + var resource = styleSheet.parentFrame.resourceForURL(styleSheet.url); + if (!resource) + return; + + // Only try to update stylesheet resources. Other resources, like documents, can contain + // multiple stylesheets and we don't have the source ranges to update those. + if (resource.type !== WebInspector.Resource.Type.Stylesheet) + return; + + if (resource.__ignoreNextUpdateResourceContent) { + resource.__ignoreNextUpdateResourceContent = false; + return; + } + + this._ignoreResourceContentDidChangeEventForResource = resource; + WebInspector.branchManager.currentBranch.revisionForRepresentedObject(resource).content = content; + this._ignoreResourceContentDidChangeEventForResource = null; + } + + function styleSheetReady() + { + styleSheet.requestContent().then(fetchedStyleSheetContent.bind(this)); + } + + function applyStyleSheetChanges() + { + if (styleSheet.url) + styleSheetReady.call(this); + else + this._fetchInfoForAllStyleSheets(styleSheetReady.bind(this)); + } + + if (styleSheet.__pendingChangeTimeout) + clearTimeout(styleSheet.__pendingChangeTimeout); + styleSheet.__pendingChangeTimeout = setTimeout(applyStyleSheetChanges.bind(this), 500); + } +}; + +WebInspector.CSSStyleManager.Event = { + StyleSheetAdded: "css-style-manager-style-sheet-added", + StyleSheetRemoved: "css-style-manager-style-sheet-removed", +}; + +WebInspector.CSSStyleManager.PseudoElementNames = ["before", "after"]; +WebInspector.CSSStyleManager.ForceablePseudoClasses = ["active", "focus", "hover", "visited"]; +WebInspector.CSSStyleManager.PreferredInspectorStyleSheetSymbol = Symbol("css-style-manager-preferred-inspector-stylesheet"); diff --git a/Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorBezierEditingController.js b/Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorBezierEditingController.js new file mode 100644 index 000000000..e79da97f9 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorBezierEditingController.js @@ -0,0 +1,68 @@ +/* + * Copyright (C) 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.CodeMirrorBezierEditingController = class CodeMirrorBezierEditingController extends WebInspector.CodeMirrorEditingController +{ + constructor(codeMirror, marker) + { + super(codeMirror, marker); + } + + // Public + + get initialValue() + { + return WebInspector.CubicBezier.fromString(this.text); + } + + get cssClassName() + { + return "cubic-bezier"; + } + + popoverWillPresent(popover) + { + this._bezierEditor = new WebInspector.BezierEditor; + this._bezierEditor.addEventListener(WebInspector.BezierEditor.Event.BezierChanged, this._bezierEditorBezierChanged, this); + popover.content = this._bezierEditor.element; + } + + popoverDidPresent(popover) + { + this._bezierEditor.bezier = this.value; + } + + popoverDidDismiss(popover) + { + this._bezierEditor.removeListeners(); + } + + // Private + + _bezierEditorBezierChanged(event) + { + this.value = event.data.bezier; + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorColorEditingController.js b/Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorColorEditingController.js new file mode 100644 index 000000000..b45846fd5 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorColorEditingController.js @@ -0,0 +1,64 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.CodeMirrorColorEditingController = class CodeMirrorColorEditingController extends WebInspector.CodeMirrorEditingController +{ + constructor(codeMirror, marker) + { + super(codeMirror, marker); + } + + // Public + + get initialValue() + { + return WebInspector.Color.fromString(this.text); + } + + get cssClassName() + { + return "color"; + } + + popoverWillPresent(popover) + { + this._colorPicker = new WebInspector.ColorPicker; + this._colorPicker.addEventListener(WebInspector.ColorPicker.Event.ColorChanged, this._colorPickerColorChanged, this); + this._colorPicker.addEventListener(WebInspector.ColorPicker.Event.FormatChanged, (event) => popover.update()); + popover.content = this._colorPicker.element; + } + + popoverDidPresent(popover) + { + this._colorPicker.color = this._value; + } + + // Private + + _colorPickerColorChanged(event) + { + this.value = event.target.color; + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorCompletionController.css b/Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorCompletionController.css new file mode 100644 index 000000000..eff18cfb1 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorCompletionController.css @@ -0,0 +1,29 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +.CodeMirror .CodeMirror-lines .completion-hint { + text-decoration: none !important; + opacity: 0.4; +} diff --git a/Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorCompletionController.js b/Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorCompletionController.js new file mode 100644 index 000000000..33d7ccbd6 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorCompletionController.js @@ -0,0 +1,875 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.CodeMirrorCompletionController = class CodeMirrorCompletionController extends WebInspector.Object +{ + constructor(codeMirror, delegate, stopCharactersRegex) + { + super(); + + console.assert(codeMirror); + + this._codeMirror = codeMirror; + this._stopCharactersRegex = stopCharactersRegex || null; + this._delegate = delegate || null; + + this._startOffset = NaN; + this._endOffset = NaN; + this._lineNumber = NaN; + this._prefix = ""; + this._noEndingSemicolon = false; + this._completions = []; + this._extendedCompletionProviders = {}; + + this._suggestionsView = new WebInspector.CompletionSuggestionsView(this); + + this._keyMap = { + "Up": this._handleUpKey.bind(this), + "Down": this._handleDownKey.bind(this), + "Right": this._handleRightOrEnterKey.bind(this), + "Esc": this._handleEscapeKey.bind(this), + "Enter": this._handleRightOrEnterKey.bind(this), + "Tab": this._handleTabKey.bind(this), + "Cmd-A": this._handleHideKey.bind(this), + "Cmd-Z": this._handleHideKey.bind(this), + "Shift-Cmd-Z": this._handleHideKey.bind(this), + "Cmd-Y": this._handleHideKey.bind(this) + }; + + this._handleChangeListener = this._handleChange.bind(this); + this._handleCursorActivityListener = this._handleCursorActivity.bind(this); + this._handleHideActionListener = this._handleHideAction.bind(this); + + this._codeMirror.addKeyMap(this._keyMap); + + this._codeMirror.on("change", this._handleChangeListener); + this._codeMirror.on("cursorActivity", this._handleCursorActivityListener); + this._codeMirror.on("blur", this._handleHideActionListener); + this._codeMirror.on("scroll", this._handleHideActionListener); + + this._updatePromise = null; + } + + // Public + + get delegate() + { + return this._delegate; + } + + addExtendedCompletionProvider(modeName, provider) + { + this._extendedCompletionProviders[modeName] = provider; + } + + updateCompletions(completions, implicitSuffix) + { + if (isNaN(this._startOffset) || isNaN(this._endOffset) || isNaN(this._lineNumber)) + return; + + if (!completions || !completions.length) { + this.hideCompletions(); + return; + } + + this._completions = completions; + + if (typeof implicitSuffix === "string") + this._implicitSuffix = implicitSuffix; + + var from = {line: this._lineNumber, ch: this._startOffset}; + var to = {line: this._lineNumber, ch: this._endOffset}; + + var firstCharCoords = this._codeMirror.cursorCoords(from); + var lastCharCoords = this._codeMirror.cursorCoords(to); + var bounds = new WebInspector.Rect(firstCharCoords.left, firstCharCoords.top, lastCharCoords.right - firstCharCoords.left, firstCharCoords.bottom - firstCharCoords.top); + + // Try to restore the previous selected index, otherwise just select the first. + var index = this._currentCompletion ? completions.indexOf(this._currentCompletion) : 0; + if (index === -1) + index = 0; + + if (this._forced || completions.length > 1 || completions[index] !== this._prefix) { + // Update and show the suggestion list. + this._suggestionsView.update(completions, index); + this._suggestionsView.show(bounds); + } else if (this._implicitSuffix) { + // The prefix and the completion exactly match, but there is an implicit suffix. + // Just hide the suggestion list and keep the completion hint for the implicit suffix. + this._suggestionsView.hide(); + } else { + // The prefix and the completion exactly match, hide the completions. Return early so + // the completion hint isn't updated. + this.hideCompletions(); + return; + } + + this._applyCompletionHint(completions[index]); + + this._resolveUpdatePromise(WebInspector.CodeMirrorCompletionController.UpdatePromise.CompletionsFound); + } + + isCompletionChange(change) + { + return this._ignoreChange || change.origin === WebInspector.CodeMirrorCompletionController.CompletionOrigin || change.origin === WebInspector.CodeMirrorCompletionController.DeleteCompletionOrigin; + } + + isShowingCompletions() + { + return this._suggestionsView.visible || (this._completionHintMarker && this._completionHintMarker.find()); + } + + isHandlingClickEvent() + { + return this._suggestionsView.isHandlingClickEvent(); + } + + hideCompletions() + { + this._suggestionsView.hide(); + + this._removeCompletionHint(); + + this._startOffset = NaN; + this._endOffset = NaN; + this._lineNumber = NaN; + this._prefix = ""; + this._completions = []; + this._implicitSuffix = ""; + this._forced = false; + + delete this._currentCompletion; + delete this._ignoreNextCursorActivity; + + this._resolveUpdatePromise(WebInspector.CodeMirrorCompletionController.UpdatePromise.NoCompletionsFound); + } + + close() + { + this._codeMirror.removeKeyMap(this._keyMap); + + this._codeMirror.off("change", this._handleChangeListener); + this._codeMirror.off("cursorActivity", this._handleCursorActivityListener); + this._codeMirror.off("blur", this._handleHideActionListener); + this._codeMirror.off("scroll", this._handleHideActionListener); + } + + completeAtCurrentPositionIfNeeded(force) + { + this._resolveUpdatePromise(WebInspector.CodeMirrorCompletionController.UpdatePromise.Canceled); + + var update = this._updatePromise = new WebInspector.WrappedPromise; + + this._completeAtCurrentPosition(force); + + return update.promise; + } + + // Protected + + completionSuggestionsSelectedCompletion(suggestionsView, completionText) + { + this._applyCompletionHint(completionText); + } + + completionSuggestionsClickedCompletion(suggestionsView, completionText) + { + // The clicked suggestion causes the editor to loose focus. Restore it so the user can keep typing. + this._codeMirror.focus(); + + this._applyCompletionHint(completionText); + this._commitCompletionHint(); + } + + set noEndingSemicolon(noEndingSemicolon) + { + this._noEndingSemicolon = noEndingSemicolon; + } + + // Private + + _resolveUpdatePromise(message) + { + if (!this._updatePromise) + return; + + this._updatePromise.resolve(message); + this._updatePromise = null; + } + + get _currentReplacementText() + { + return this._currentCompletion + this._implicitSuffix; + } + + _hasPendingCompletion() + { + return !isNaN(this._startOffset) && !isNaN(this._endOffset) && !isNaN(this._lineNumber); + } + + _notifyCompletionsHiddenSoon() + { + function notify() + { + if (this._completionHintMarker) + return; + + if (this._delegate && typeof this._delegate.completionControllerCompletionsHidden === "function") + this._delegate.completionControllerCompletionsHidden(this); + } + + if (this._notifyCompletionsHiddenIfNeededTimeout) + clearTimeout(this._notifyCompletionsHiddenIfNeededTimeout); + this._notifyCompletionsHiddenIfNeededTimeout = setTimeout(notify.bind(this), WebInspector.CodeMirrorCompletionController.CompletionsHiddenDelay); + } + + _createCompletionHintMarker(position, text) + { + var container = document.createElement("span"); + container.classList.add(WebInspector.CodeMirrorCompletionController.CompletionHintStyleClassName); + container.textContent = text; + + this._completionHintMarker = this._codeMirror.setUniqueBookmark(position, {widget: container, insertLeft: true}); + } + + _applyCompletionHint(completionText) + { + console.assert(completionText); + if (!completionText) + return; + + function update() + { + this._currentCompletion = completionText; + + this._removeCompletionHint(true, true); + + var replacementText = this._currentReplacementText; + + var from = {line: this._lineNumber, ch: this._startOffset}; + var cursor = {line: this._lineNumber, ch: this._endOffset}; + var currentText = this._codeMirror.getRange(from, cursor); + + this._createCompletionHintMarker(cursor, replacementText.replace(currentText, "")); + } + + this._ignoreChange = true; + this._ignoreNextCursorActivity = true; + + this._codeMirror.operation(update.bind(this)); + + delete this._ignoreChange; + } + + _commitCompletionHint() + { + function update() + { + this._removeCompletionHint(true, true); + + var replacementText = this._currentReplacementText; + + var from = {line: this._lineNumber, ch: this._startOffset}; + var cursor = {line: this._lineNumber, ch: this._endOffset}; + var to = {line: this._lineNumber, ch: this._startOffset + replacementText.length}; + + var lastChar = this._currentCompletion.charAt(this._currentCompletion.length - 1); + var isClosing = ")]}".indexOf(lastChar); + if (isClosing !== -1) + to.ch -= 1 + this._implicitSuffix.length; + + this._codeMirror.replaceRange(replacementText, from, cursor, WebInspector.CodeMirrorCompletionController.CompletionOrigin); + + // Don't call _removeLastChangeFromHistory here to allow the committed completion to be undone. + + this._codeMirror.setCursor(to); + + this.hideCompletions(); + } + + this._ignoreChange = true; + this._ignoreNextCursorActivity = true; + + this._codeMirror.operation(update.bind(this)); + + delete this._ignoreChange; + } + + _removeLastChangeFromHistory() + { + var history = this._codeMirror.getHistory(); + + // We don't expect a undone history. But if there is one clear it. If could lead to undefined behavior. + console.assert(!history.undone.length); + history.undone = []; + + // Pop the last item from the done history. + console.assert(history.done.length); + history.done.pop(); + + this._codeMirror.setHistory(history); + } + + _removeCompletionHint(nonatomic, dontRestorePrefix) + { + if (!this._completionHintMarker) + return; + + this._notifyCompletionsHiddenSoon(); + + function clearMarker(marker) + { + if (!marker) + return; + + var range = marker.find(); + if (range) + marker.clear(); + + return null; + } + + function update() + { + this._completionHintMarker = clearMarker(this._completionHintMarker); + + if (dontRestorePrefix) + return; + + console.assert(!isNaN(this._startOffset)); + console.assert(!isNaN(this._endOffset)); + console.assert(!isNaN(this._lineNumber)); + + var from = {line: this._lineNumber, ch: this._startOffset}; + var to = {line: this._lineNumber, ch: this._endOffset}; + + this._codeMirror.replaceRange(this._prefix, from, to, WebInspector.CodeMirrorCompletionController.DeleteCompletionOrigin); + this._removeLastChangeFromHistory(); + } + + if (nonatomic) { + update.call(this); + return; + } + + this._ignoreChange = true; + + this._codeMirror.operation(update.bind(this)); + + delete this._ignoreChange; + } + + _scanStringForExpression(modeName, string, startOffset, direction, allowMiddleAndEmpty, includeStopCharacter, ignoreInitialUnmatchedOpenBracket, stopCharactersRegex) + { + console.assert(direction === -1 || direction === 1); + + var stopCharactersRegex = stopCharactersRegex || this._stopCharactersRegex || WebInspector.CodeMirrorCompletionController.DefaultStopCharactersRegexModeMap[modeName] || WebInspector.CodeMirrorCompletionController.GenericStopCharactersRegex; + + function isStopCharacter(character) + { + return stopCharactersRegex.test(character); + } + + function isOpenBracketCharacter(character) + { + return WebInspector.CodeMirrorCompletionController.OpenBracketCharactersRegex.test(character); + } + + function isCloseBracketCharacter(character) + { + return WebInspector.CodeMirrorCompletionController.CloseBracketCharactersRegex.test(character); + } + + function matchingBracketCharacter(character) + { + return WebInspector.CodeMirrorCompletionController.MatchingBrackets[character]; + } + + var endOffset = Math.min(startOffset, string.length); + + var endOfLineOrWord = endOffset === string.length || isStopCharacter(string.charAt(endOffset)); + + if (!endOfLineOrWord && !allowMiddleAndEmpty) + return null; + + var bracketStack = []; + var bracketOffsetStack = []; + + var startOffset = endOffset; + var firstOffset = endOffset + direction; + for (var i = firstOffset; direction > 0 ? i < string.length : i >= 0; i += direction) { + var character = string.charAt(i); + + // Ignore stop characters when we are inside brackets. + if (isStopCharacter(character) && !bracketStack.length) + break; + + if (isCloseBracketCharacter(character)) { + bracketStack.push(character); + bracketOffsetStack.push(i); + } else if (isOpenBracketCharacter(character)) { + if ((!ignoreInitialUnmatchedOpenBracket || i !== firstOffset) && (!bracketStack.length || matchingBracketCharacter(character) !== bracketStack.lastValue)) + break; + + bracketOffsetStack.pop(); + bracketStack.pop(); + } + + startOffset = i + (direction > 0 ? 1 : 0); + } + + if (bracketOffsetStack.length) + startOffset = bracketOffsetStack.pop() + 1; + + if (includeStopCharacter && startOffset > 0 && startOffset < string.length) + startOffset += direction; + + if (direction > 0) { + var tempEndOffset = endOffset; + endOffset = startOffset; + startOffset = tempEndOffset; + } + + return {string: string.substring(startOffset, endOffset), startOffset, endOffset}; + } + + _completeAtCurrentPosition(force) + { + if (this._codeMirror.somethingSelected()) { + this.hideCompletions(); + return; + } + + this._removeCompletionHint(true, true); + + var cursor = this._codeMirror.getCursor(); + var token = this._codeMirror.getTokenAt(cursor); + + // Don't try to complete inside comments. + if (token.type && /\bcomment\b/.test(token.type)) { + this.hideCompletions(); + return; + } + + var mode = this._codeMirror.getMode(); + var innerMode = CodeMirror.innerMode(mode, token.state).mode; + var modeName = innerMode.alternateName || innerMode.name; + + var lineNumber = cursor.line; + var lineString = this._codeMirror.getLine(lineNumber); + + var backwardScanResult = this._scanStringForExpression(modeName, lineString, cursor.ch, -1, force); + if (!backwardScanResult) { + this.hideCompletions(); + return; + } + + var forwardScanResult = this._scanStringForExpression(modeName, lineString, cursor.ch, 1, true, true); + var suffix = forwardScanResult.string; + + this._ignoreNextCursorActivity = true; + + this._startOffset = backwardScanResult.startOffset; + this._endOffset = backwardScanResult.endOffset; + this._lineNumber = lineNumber; + this._prefix = backwardScanResult.string; + this._completions = []; + this._implicitSuffix = ""; + this._forced = force; + + var baseExpressionStopCharactersRegex = WebInspector.CodeMirrorCompletionController.BaseExpressionStopCharactersRegexModeMap[modeName]; + if (baseExpressionStopCharactersRegex) + var baseScanResult = this._scanStringForExpression(modeName, lineString, this._startOffset, -1, true, false, true, baseExpressionStopCharactersRegex); + + if (!force && !backwardScanResult.string && (!baseScanResult || !baseScanResult.string)) { + this.hideCompletions(); + return; + } + + var defaultCompletions = []; + + switch (modeName) { + case "css": + defaultCompletions = this._generateCSSCompletions(token, baseScanResult ? baseScanResult.string : null, suffix); + break; + case "javascript": + defaultCompletions = this._generateJavaScriptCompletions(token, baseScanResult ? baseScanResult.string : null, suffix); + break; + } + + var extendedCompletionsProvider = this._extendedCompletionProviders[modeName]; + if (extendedCompletionsProvider) { + extendedCompletionsProvider.completionControllerCompletionsNeeded(this, defaultCompletions, baseScanResult ? baseScanResult.string : null, this._prefix, suffix, force); + return; + } + + if (this._delegate && typeof this._delegate.completionControllerCompletionsNeeded === "function") + this._delegate.completionControllerCompletionsNeeded(this, this._prefix, defaultCompletions, baseScanResult ? baseScanResult.string : null, suffix, force); + else + this.updateCompletions(defaultCompletions); + } + + _generateCSSCompletions(mainToken, base, suffix) + { + // We only support completion inside CSS block context. + if (mainToken.state.state === "media" || mainToken.state.state === "top" || mainToken.state.state === "parens") + return []; + + // Don't complete in the middle of a property name. + if (/^[a-z]/i.test(suffix)) + return []; + + var token = mainToken; + var lineNumber = this._lineNumber; + + // Scan backwards looking for the current property. + while (token.state.state === "prop") { + // Found the beginning of the line. Go to the previous line. + if (!token.start) { + --lineNumber; + + // No more lines, stop. + if (lineNumber < 0) + break; + } + + // Get the previous token. + token = this._codeMirror.getTokenAt({line: lineNumber, ch: token.start ? token.start : Number.MAX_VALUE}); + } + + // If we have a property token and it's not the main token, then we are working on + // the value for that property and should complete allowed values. + if (mainToken !== token && token.type && /\bproperty\b/.test(token.type)) { + var propertyName = token.string; + + // If there is a suffix and it isn't a semicolon, then we should use a space since + // the user is editing in the middle. Likewise if the suffix starts with an open + // paren we are changing a function name so don't add a suffix. + this._implicitSuffix = " "; + if (suffix === ";") + this._implicitSuffix = this._noEndingSemicolon ? "" : ";"; + else if (suffix.startsWith("(")) + this._implicitSuffix = ""; + + // Don't use an implicit suffix if it would be the same as the existing suffix. + if (this._implicitSuffix === suffix) + this._implicitSuffix = ""; + + let completions = WebInspector.CSSKeywordCompletions.forProperty(propertyName).startsWith(this._prefix); + + if (suffix.startsWith("(")) + completions = completions.map((x) => x.replace(/\(\)$/, "")); + + return completions; + } + + this._implicitSuffix = suffix !== ":" ? ": " : ""; + + // Complete property names. + return WebInspector.CSSCompletions.cssNameCompletions.startsWith(this._prefix); + } + + _generateJavaScriptCompletions(mainToken, base, suffix) + { + // If there is a base expression then we should not attempt to match any keywords or variables. + // Allow only open bracket characters at the end of the base, otherwise leave completions with + // a base up to the delegate to figure out. + if (base && !/[({[]$/.test(base)) + return []; + + var matchingWords = []; + + var prefix = this._prefix; + + var localState = mainToken.state.localState ? mainToken.state.localState : mainToken.state; + + var declaringVariable = localState.lexical.type === "vardef"; + var insideSwitch = localState.lexical.prev ? localState.lexical.prev.info === "switch" : false; + var insideBlock = localState.lexical.prev ? localState.lexical.prev.type === "}" : false; + var insideParenthesis = localState.lexical.type === ")"; + var insideBrackets = localState.lexical.type === "]"; + + // FIXME: Include module keywords if we know this is a module environment. + // var moduleKeywords = ["default", "export", "import"]; + + var allKeywords = [ + "break", "case", "catch", "class", "const", "continue", "debugger", "default", + "delete", "do", "else", "extends", "false", "finally", "for", "function", + "if", "in", "Infinity", "instanceof", "let", "NaN", "new", "null", "of", + "return", "static", "super", "switch", "this", "throw", "true", "try", + "typeof", "undefined", "var", "void", "while", "with", "yield" + ]; + var valueKeywords = ["false", "Infinity", "NaN", "null", "this", "true", "undefined"]; + + var allowedKeywordsInsideBlocks = allKeywords.keySet(); + var allowedKeywordsWhenDeclaringVariable = valueKeywords.keySet(); + var allowedKeywordsInsideParenthesis = valueKeywords.concat(["class", "function"]).keySet(); + var allowedKeywordsInsideBrackets = allowedKeywordsInsideParenthesis; + var allowedKeywordsOnlyInsideSwitch = ["case", "default"].keySet(); + + function matchKeywords(keywords) + { + matchingWords = matchingWords.concat(keywords.filter(function(word) { + if (!insideSwitch && word in allowedKeywordsOnlyInsideSwitch) + return false; + if (insideBlock && !(word in allowedKeywordsInsideBlocks)) + return false; + if (insideBrackets && !(word in allowedKeywordsInsideBrackets)) + return false; + if (insideParenthesis && !(word in allowedKeywordsInsideParenthesis)) + return false; + if (declaringVariable && !(word in allowedKeywordsWhenDeclaringVariable)) + return false; + return word.startsWith(prefix); + })); + } + + function matchVariables() + { + function filterVariables(variables) + { + for (var variable = variables; variable; variable = variable.next) { + // Don't match the variable if this token is in a variable declaration. + // Otherwise the currently typed text will always match and that isn't useful. + if (declaringVariable && variable.name === prefix) + continue; + + if (variable.name.startsWith(prefix) && !matchingWords.includes(variable.name)) + matchingWords.push(variable.name); + } + } + + var context = localState.context; + while (context) { + if (context.vars) + filterVariables(context.vars); + context = context.prev; + } + + if (localState.localVars) + filterVariables(localState.localVars); + if (localState.globalVars) + filterVariables(localState.globalVars); + } + + switch (suffix.substring(0, 1)) { + case "": + case " ": + matchVariables(); + matchKeywords(allKeywords); + break; + + case ".": + case "[": + matchVariables(); + matchKeywords(["false", "Infinity", "NaN", "this", "true"]); + break; + + case "(": + matchVariables(); + matchKeywords(["catch", "else", "for", "function", "if", "return", "switch", "throw", "while", "with", "yield"]); + break; + + case "{": + matchKeywords(["do", "else", "finally", "return", "try", "yield"]); + break; + + case ":": + if (insideSwitch) + matchKeywords(["case", "default"]); + break; + + case ";": + matchVariables(); + matchKeywords(valueKeywords); + matchKeywords(["break", "continue", "debugger", "return", "void"]); + break; + } + + return matchingWords; + } + + _handleUpKey(codeMirror) + { + if (!this._hasPendingCompletion()) + return CodeMirror.Pass; + + if (!this.isShowingCompletions()) + return; + + this._suggestionsView.selectPrevious(); + } + + _handleDownKey(codeMirror) + { + if (!this._hasPendingCompletion()) + return CodeMirror.Pass; + + if (!this.isShowingCompletions()) + return; + + this._suggestionsView.selectNext(); + } + + _handleRightOrEnterKey(codeMirror) + { + if (!this._hasPendingCompletion()) + return CodeMirror.Pass; + + if (!this.isShowingCompletions()) + return; + + this._commitCompletionHint(); + } + + _handleEscapeKey(codeMirror) + { + var delegateImplementsShouldAllowEscapeCompletion = this._delegate && typeof this._delegate.completionControllerShouldAllowEscapeCompletion === "function"; + if (this._hasPendingCompletion()) + this.hideCompletions(); + else if (this._codeMirror.getOption("readOnly")) + return CodeMirror.Pass; + else if (!delegateImplementsShouldAllowEscapeCompletion || this._delegate.completionControllerShouldAllowEscapeCompletion(this)) + this._completeAtCurrentPosition(true); + else + return CodeMirror.Pass; + } + + _handleTabKey(codeMirror) + { + if (!this._hasPendingCompletion()) + return CodeMirror.Pass; + + if (!this.isShowingCompletions()) + return; + + console.assert(this._completions.length); + if (!this._completions.length) + return; + + console.assert(this._currentCompletion); + if (!this._currentCompletion) + return; + + // Commit the current completion if there is only one suggestion. + if (this._completions.length === 1) { + this._commitCompletionHint(); + return; + } + + var prefixLength = this._prefix.length; + + var commonPrefix = this._completions[0]; + for (var i = 1; i < this._completions.length; ++i) { + var completion = this._completions[i]; + var lastIndex = Math.min(commonPrefix.length, completion.length); + for (var j = prefixLength; j < lastIndex; ++j) { + if (commonPrefix[j] !== completion[j]) { + commonPrefix = commonPrefix.substr(0, j); + break; + } + } + } + + // Commit the current completion if there is no common prefix that is longer. + if (commonPrefix === this._prefix) { + this._commitCompletionHint(); + return; + } + + // Set the prefix to the common prefix so _applyCompletionHint will insert the + // common prefix as commited text. Adjust _endOffset to match the new prefix. + this._prefix = commonPrefix; + this._endOffset = this._startOffset + commonPrefix.length; + + this._applyCompletionHint(this._currentCompletion); + } + + _handleChange(codeMirror, change) + { + if (this.isCompletionChange(change)) + return; + + this._ignoreNextCursorActivity = true; + + if (!change.origin || change.origin.charAt(0) !== "+") { + this.hideCompletions(); + return; + } + + // Only complete on delete if we are showing completions already. + if (change.origin === "+delete" && !this._hasPendingCompletion()) + return; + + this._completeAtCurrentPosition(false); + } + + _handleCursorActivity(codeMirror) + { + if (this._ignoreChange) + return; + + if (this._ignoreNextCursorActivity) { + delete this._ignoreNextCursorActivity; + return; + } + + this.hideCompletions(); + } + + _handleHideKey(codeMirror) + { + this.hideCompletions(); + + return CodeMirror.Pass; + } + + _handleHideAction(codeMirror) + { + // Clicking a suggestion causes the editor to blur. We don't want to hide completions in this case. + if (this.isHandlingClickEvent()) + return; + + this.hideCompletions(); + } +}; + +WebInspector.CodeMirrorCompletionController.UpdatePromise = { + Canceled: "code-mirror-completion-controller-canceled", + CompletionsFound: "code-mirror-completion-controller-completions-found", + NoCompletionsFound: "code-mirror-completion-controller-no-completions-found" +}; + +WebInspector.CodeMirrorCompletionController.GenericStopCharactersRegex = /[\s=:;,]/; +WebInspector.CodeMirrorCompletionController.DefaultStopCharactersRegexModeMap = {"css": /[\s:;,{}()]/, "javascript": /[\s=:;,!+\-*/%&|^~?<>.{}()[\]]/}; +WebInspector.CodeMirrorCompletionController.BaseExpressionStopCharactersRegexModeMap = {"javascript": /[\s=:;,!+\-*/%&|^~?<>]/}; +WebInspector.CodeMirrorCompletionController.OpenBracketCharactersRegex = /[({[]/; +WebInspector.CodeMirrorCompletionController.CloseBracketCharactersRegex = /[)}\]]/; +WebInspector.CodeMirrorCompletionController.MatchingBrackets = {"{": "}", "(": ")", "[": "]", "}": "{", ")": "(", "]": "["}; +WebInspector.CodeMirrorCompletionController.CompletionHintStyleClassName = "completion-hint"; +WebInspector.CodeMirrorCompletionController.CompletionsHiddenDelay = 250; +WebInspector.CodeMirrorCompletionController.CompletionTypingDelay = 250; +WebInspector.CodeMirrorCompletionController.CompletionOrigin = "+completion"; +WebInspector.CodeMirrorCompletionController.DeleteCompletionOrigin = "+delete-completion"; diff --git a/Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorDragToAdjustNumberController.css b/Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorDragToAdjustNumberController.css new file mode 100644 index 000000000..d67d6b361 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorDragToAdjustNumberController.css @@ -0,0 +1,28 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +.CodeMirror.drag-to-adjust .CodeMirror-lines { + cursor: col-resize; +} diff --git a/Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorDragToAdjustNumberController.js b/Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorDragToAdjustNumberController.js new file mode 100644 index 000000000..a8105998a --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorDragToAdjustNumberController.js @@ -0,0 +1,121 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.CodeMirrorDragToAdjustNumberController = class CodeMirrorDragToAdjustNumberController extends WebInspector.Object +{ + constructor(codeMirror) + { + super(); + + this._codeMirror = codeMirror; + + this._dragToAdjustController = new WebInspector.DragToAdjustController(this); + } + + // Public + + get enabled() + { + return this._dragToAdjustController.enabled; + } + + set enabled(enabled) + { + if (this.enabled === enabled) + return; + + this._dragToAdjustController.element = this._codeMirror.getWrapperElement(); + this._dragToAdjustController.enabled = enabled; + } + + // Protected + + dragToAdjustControllerActiveStateChanged(dragToAdjustController) + { + if (!dragToAdjustController.active) + this._hoveredTokenInfo = null; + } + + dragToAdjustControllerCanBeActivated(dragToAdjustController) + { + return !this._codeMirror.getOption("readOnly"); + } + + dragToAdjustControllerCanBeAdjusted(dragToAdjustController) + { + + return this._hoveredTokenInfo && this._hoveredTokenInfo.containsNumber; + } + + dragToAdjustControllerWasAdjustedByAmount(dragToAdjustController, amount) + { + this._codeMirror.alterNumberInRange(amount, this._hoveredTokenInfo.startPosition, this._hoveredTokenInfo.endPosition, false); + } + + dragToAdjustControllerDidReset(dragToAdjustController) + { + this._hoveredTokenInfo = null; + } + + dragToAdjustControllerCanAdjustObjectAtPoint(dragToAdjustController, point) + { + var position = this._codeMirror.coordsChar({left: point.x, top: point.y}); + var token = this._codeMirror.getTokenAt(position); + + if (!token || !token.type || !token.string) { + if (this._hoveredTokenInfo) + dragToAdjustController.reset(); + return false; + } + + // Stop right here if we're hovering the same token as we were last time. + if (this._hoveredTokenInfo && this._hoveredTokenInfo.line === position.line && + this._hoveredTokenInfo.token.start === token.start && this._hoveredTokenInfo.token.end === token.end) + return this._hoveredTokenInfo.token.type.indexOf("number") !== -1; + + var containsNumber = token.type.indexOf("number") !== -1; + this._hoveredTokenInfo = { + token, + line: position.line, + containsNumber, + startPosition: { + ch: token.start, + line: position.line + }, + endPosition: { + ch: token.end, + line: position.line + } + }; + + return containsNumber; + } +}; + +CodeMirror.defineOption("dragToAdjustNumbers", true, function(codeMirror, value, oldValue) { + if (!codeMirror.dragToAdjustNumberController) + codeMirror.dragToAdjustNumberController = new WebInspector.CodeMirrorDragToAdjustNumberController(codeMirror); + codeMirror.dragToAdjustNumberController.enabled = value; +}); diff --git a/Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorEditingController.js b/Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorEditingController.js new file mode 100644 index 000000000..3496ac437 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorEditingController.js @@ -0,0 +1,200 @@ +/* + * Copyright (C) 2014 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.CodeMirrorEditingController = class CodeMirrorEditingController extends WebInspector.Object +{ + constructor(codeMirror, marker) + { + super(); + + this._codeMirror = codeMirror; + this._marker = marker; + this._delegate = null; + + this._range = marker.range; + + // The value must support .toString() and .copy() methods. + this._value = this.initialValue; + + this._keyboardShortcutEsc = new WebInspector.KeyboardShortcut(null, WebInspector.KeyboardShortcut.Key.Escape); + } + + // Public + + get marker() + { + return this._marker; + } + + get range() + { + return this._range; + } + + get value() + { + return this._value; + } + + set value(value) + { + this.text = value.toString(); + this._value = value; + } + + get delegate() + { + return this._delegate; + } + + set delegate(delegate) + { + this._delegate = delegate; + } + + get text() + { + var from = {line: this._range.startLine, ch: this._range.startColumn}; + var to = {line: this._range.endLine, ch: this._range.endColumn}; + return this._codeMirror.getRange(from, to); + } + + set text(text) + { + var from = {line: this._range.startLine, ch: this._range.startColumn}; + var to = {line: this._range.endLine, ch: this._range.endColumn}; + this._codeMirror.replaceRange(text, from, to); + + var lines = text.split("\n"); + var endLine = this._range.startLine + lines.length - 1; + var endColumn = lines.length > 1 ? lines.lastValue.length : this._range.startColumn + text.length; + this._range = new WebInspector.TextRange(this._range.startLine, this._range.startColumn, endLine, endColumn); + } + + get initialValue() + { + // Implemented by subclasses. + return this.text; + } + + get cssClassName() + { + // Implemented by subclasses. + return ""; + } + + get popover() + { + return this._popover; + } + + get popoverPreferredEdges() + { + // Best to display the popover to the left or above the edited range since its end position may change, but not its start + // position. This way we minimize the chances of overlaying the edited range as it changes. + return [WebInspector.RectEdge.MIN_X, WebInspector.RectEdge.MIN_Y, WebInspector.RectEdge.MAX_Y, WebInspector.RectEdge.MAX_X]; + } + + popoverTargetFrameWithRects(rects) + { + return WebInspector.Rect.unionOfRects(rects); + } + + presentHoverMenu() + { + if (!this.cssClassName) + return; + + this._hoverMenu = new WebInspector.HoverMenu(this); + this._hoverMenu.element.classList.add(this.cssClassName); + this._rects = this._marker.rects; + this._hoverMenu.present(this._rects); + } + + dismissHoverMenu(discrete) + { + if (!this._hoverMenu) + return; + + this._hoverMenu.dismiss(discrete); + } + + popoverWillPresent(popover) + { + // Implemented by subclasses. + } + + popoverDidPresent(popover) + { + // Implemented by subclasses. + } + + popoverDidDismiss(popover) + { + // Implemented by subclasses. + } + + // Protected + + handleKeydownEvent(event) + { + if (!this._keyboardShortcutEsc.matchesEvent(event) || !this._popover.visible) + return false; + + this.value = this._originalValue; + this._popover.dismiss(); + + return true; + } + + hoverMenuButtonWasPressed(hoverMenu) + { + this._popover = new WebInspector.Popover(this); + this.popoverWillPresent(this._popover); + this._popover.present(this.popoverTargetFrameWithRects(this._rects).pad(2), this.popoverPreferredEdges); + this.popoverDidPresent(this._popover); + + WebInspector.addWindowKeydownListener(this); + + hoverMenu.dismiss(); + + if (this._delegate && typeof this._delegate.editingControllerDidStartEditing === "function") + this._delegate.editingControllerDidStartEditing(this); + + this._originalValue = this._value.copy(); + } + + didDismissPopover(popover) + { + delete this._popover; + delete this._originalValue; + + WebInspector.removeWindowKeydownListener(this); + this.popoverDidDismiss(); + + if (this._delegate && typeof this._delegate.editingControllerDidFinishEditing === "function") + this._delegate.editingControllerDidFinishEditing(this); + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorGradientEditingController.js b/Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorGradientEditingController.js new file mode 100644 index 000000000..7ff38e0e7 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorGradientEditingController.js @@ -0,0 +1,83 @@ +/* + * Copyright (C) 2014 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.CodeMirrorGradientEditingController = class CodeMirrorGradientEditingController extends WebInspector.CodeMirrorEditingController +{ + constructor(codeMirror, marker) + { + super(codeMirror, marker); + } + + // Public + + get initialValue() + { + return WebInspector.Gradient.fromString(this.text); + } + + get cssClassName() + { + return "gradient"; + } + + get popoverPreferredEdges() + { + // Since the gradient editor can resize to be quite tall, let's avoid displaying the popover + // above the edited value so that it may not change which edge it attaches to upon editing a stop. + return [WebInspector.RectEdge.MIN_X, WebInspector.RectEdge.MAX_Y, WebInspector.RectEdge.MAX_X]; + } + + popoverTargetFrameWithRects(rects) + { + // If a gradient is defined across several lines, we probably want to use the first line only + // as a target frame for the editor since we may reformat the gradient value to fit on a single line. + return rects[0]; + } + + popoverWillPresent(popover) + { + function handleColorPickerToggled(event) + { + popover.update(); + } + + this._gradientEditor = new WebInspector.GradientEditor; + this._gradientEditor.addEventListener(WebInspector.GradientEditor.Event.GradientChanged, this._gradientEditorGradientChanged, this); + this._gradientEditor.addEventListener(WebInspector.GradientEditor.Event.ColorPickerToggled, handleColorPickerToggled, this); + popover.content = this._gradientEditor.element; + } + + popoverDidPresent(popover) + { + this._gradientEditor.gradient = this.value; + } + + // Private + + _gradientEditorGradientChanged(event) + { + this.value = event.data.gradient; + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorSpringEditingController.js b/Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorSpringEditingController.js new file mode 100644 index 000000000..7f1f91f14 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorSpringEditingController.js @@ -0,0 +1,63 @@ +/* + * Copyright (C) 2016 Devin Rousso . All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.CodeMirrorSpringEditingController = class CodeMirrorSpringEditingController extends WebInspector.CodeMirrorEditingController +{ + // Public + + get initialValue() + { + return WebInspector.Spring.fromString(this.text); + } + + get cssClassName() + { + return "spring"; + } + + popoverWillPresent(popover) + { + this._springEditor = new WebInspector.SpringEditor; + this._springEditor.addEventListener(WebInspector.SpringEditor.Event.SpringChanged, this._springEditorSpringChanged, this); + popover.content = this._springEditor.element; + } + + popoverDidPresent(popover) + { + this._springEditor.spring = this.value; + } + + popoverDidDismiss(popover) + { + this._springEditor.removeListeners(); + } + + // Private + + _springEditorSpringChanged(event) + { + this.value = event.data.spring; + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorTextKillController.js b/Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorTextKillController.js new file mode 100644 index 000000000..8cd0b7300 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorTextKillController.js @@ -0,0 +1,138 @@ +/* + * Copyright (C) 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.CodeMirrorTextKillController = class CodeMirrorTextKillController extends WebInspector.Object +{ + constructor(codeMirror) + { + super(); + + console.assert(codeMirror); + + this._codeMirror = codeMirror; + this._expectingChangeEventForKill = false; + this._nextKillStartsNewSequence = true; + this._shouldPrependToKillRing = false; + + this._handleTextChangeListener = this._handleTextChange.bind(this); + this._handleEditorBlurListener = this._handleEditorBlur.bind(this); + this._handleSelectionOrCaretChangeListener = this._handleSelectionOrCaretChange.bind(this); + + // FIXME: these keybindings match CodeMirror's default keymap for OS X. + // They should probably be altered for Windows / Linux someday. + this._codeMirror.addKeyMap({ + // Overrides for the 'emacsy' keymap. + "Ctrl-K": this._handleTextKillCommand.bind(this, "killLine", false), + "Alt-D": this._handleTextKillCommand.bind(this, "delWordAfter", false), + // Overrides for the 'macDefault' keymap. + "Alt-Delete": this._handleTextKillCommand.bind(this, "delGroupAfter", false), + "Cmd-Backspace": this._handleTextKillCommand.bind(this, "delWrappedLineLeft", true), + "Cmd-Delete": this._handleTextKillCommand.bind(this, "delWrappedLineRight", false), + "Alt-Backspace": this._handleTextKillCommand.bind(this, "delGroupBefore", true), + "Ctrl-Alt-Backspace": this._handleTextKillCommand.bind(this, "delGroupAfter", false), + }); + } + + _handleTextKillCommand(command, prependsToKillRing, codeMirror) + { + // Read-only mode is dynamic in some editors, so check every time + // and ignore the shortcut if in read-only mode. + if (this._codeMirror.getOption("readOnly")) + return; + + this._shouldPrependToKillRing = prependsToKillRing; + + // Don't add the listener if it's still registered because + // a previous empty kill didn't generate change events. + if (!this._expectingChangeEventForKill) + this._codeMirror.on("changes", this._handleTextChangeListener); + + this._expectingChangeEventForKill = true; + this._codeMirror.execCommand(command); + } + + _handleTextChange(codeMirror, changes) + { + this._codeMirror.off("changes", this._handleTextChangeListener); + + // Sometimes a second change event fires after removing the listener + // if you perform an "empty kill" and type after moving the caret. + if (!this._expectingChangeEventForKill) + return; + + this._expectingChangeEventForKill = false; + + // It doesn't make sense to get more than one change per kill. + console.assert(changes.length === 1); + let change = changes[0]; + + // If an "empty kill" is followed by up/down or typing, + // the empty kill won't fire a change event, then we'll get an + // unrelated change event that shouldn't be treated as a kill. + if (change.origin !== "+delete") + return; + + // When killed text includes a newline, CodeMirror returns + // strange change objects. Special-case for when this could happen. + let killedText; + if (change.to.line === change.from.line + 1 && change.removed.length === 2) { + // An entire line was deleted, including newline (deleteLine). + if (change.removed[0].length && !change.removed[1].length) + killedText = change.removed[0] + "\n"; + // A newline was killed by itself (Ctrl-K). + else + killedText = "\n"; + } else { + console.assert(change.removed.length === 1); + killedText = change.removed[0]; + } + + InspectorFrontendHost.killText(killedText, this._shouldPrependToKillRing, this._nextKillStartsNewSequence); + + // If the editor loses focus or the caret / selection changes + // (not as a result of the kill), then the next kill should + // start a new kill ring sequence. + this._nextKillStartsNewSequence = false; + this._codeMirror.on("blur", this._handleEditorBlurListener); + this._codeMirror.on("cursorActivity", this._handleSelectionOrCaretChangeListener); + } + + _handleEditorBlur(codeMirror) + { + this._nextKillStartsNewSequence = true; + this._codeMirror.off("blur", this._handleEditorBlurListener); + this._codeMirror.off("cursorActivity", this._handleSelectionOrCaretChangeListener); + } + + _handleSelectionOrCaretChange(codeMirror) + { + if (this._expectingChangeEventForKill) + return; + + this._nextKillStartsNewSequence = true; + this._codeMirror.off("blur", this._handleEditorBlurListener); + this._codeMirror.off("cursorActivity", this._handleSelectionOrCaretChangeListener); + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorTokenTrackingController.css b/Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorTokenTrackingController.css new file mode 100644 index 000000000..516755d1c --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorTokenTrackingController.css @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +.CodeMirror .jump-to-symbol-highlight { + color: blue !important; + text-decoration: underline !important; + cursor: pointer !important; + -webkit-text-stroke-width: 0 !important; +} diff --git a/Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorTokenTrackingController.js b/Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorTokenTrackingController.js new file mode 100644 index 000000000..4d4fdac99 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/CodeMirrorTokenTrackingController.js @@ -0,0 +1,618 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.CodeMirrorTokenTrackingController = class CodeMirrorTokenTrackingController extends WebInspector.Object +{ + constructor(codeMirror, delegate) + { + super(); + + console.assert(codeMirror); + + this._codeMirror = codeMirror; + this._delegate = delegate || null; + this._mode = WebInspector.CodeMirrorTokenTrackingController.Mode.None; + + this._mouseOverDelayDuration = 0; + this._mouseOutReleaseDelayDuration = 0; + this._classNameForHighlightedRange = null; + + this._enabled = false; + this._tracking = false; + this._previousTokenInfo = null; + this._hoveredMarker = null; + + const hidePopover = this._hidePopover.bind(this); + + this._codeMirror.addKeyMap({ + "Cmd-Enter": this._handleCommandEnterKey.bind(this), + "Esc": hidePopover + }); + + this._codeMirror.on("cursorActivity", hidePopover); + } + + // Public + + get delegate() + { + return this._delegate; + } + + set delegate(x) + { + this._delegate = x; + } + + get enabled() + { + return this._enabled; + } + + set enabled(enabled) + { + if (this._enabled === enabled) + return; + + this._enabled = enabled; + + var wrapper = this._codeMirror.getWrapperElement(); + if (enabled) { + wrapper.addEventListener("mouseenter", this); + wrapper.addEventListener("mouseleave", this); + this._updateHoveredTokenInfo({left: WebInspector.mouseCoords.x, top: WebInspector.mouseCoords.y}); + this._startTracking(); + } else { + wrapper.removeEventListener("mouseenter", this); + wrapper.removeEventListener("mouseleave", this); + this._stopTracking(); + } + } + + get mode() + { + return this._mode; + } + + set mode(mode) + { + var oldMode = this._mode; + + this._mode = mode || WebInspector.CodeMirrorTokenTrackingController.Mode.None; + + if (oldMode !== this._mode && this._tracking && this._previousTokenInfo) + this._processNewHoveredToken(this._previousTokenInfo); + } + + get mouseOverDelayDuration() + { + return this._mouseOverDelayDuration; + } + + set mouseOverDelayDuration(x) + { + console.assert(x >= 0); + this._mouseOverDelayDuration = Math.max(x, 0); + } + + get mouseOutReleaseDelayDuration() + { + return this._mouseOutReleaseDelayDuration; + } + + set mouseOutReleaseDelayDuration(x) + { + console.assert(x >= 0); + this._mouseOutReleaseDelayDuration = Math.max(x, 0); + } + + get classNameForHighlightedRange() + { + return this._classNameForHighlightedRange; + } + + set classNameForHighlightedRange(x) + { + this._classNameForHighlightedRange = x || null; + } + + get candidate() + { + return this._candidate; + } + + get hoveredMarker() + { + return this._hoveredMarker; + } + + set hoveredMarker(hoveredMarker) + { + this._hoveredMarker = hoveredMarker; + } + + highlightLastHoveredRange() + { + if (this._candidate) + this.highlightRange(this._candidate.hoveredTokenRange); + } + + highlightRange(range) + { + // Nothing to do if we're trying to highlight the same range. + if (this._codeMirrorMarkedText && this._codeMirrorMarkedText.className === this._classNameForHighlightedRange) { + var highlightedRange = this._codeMirrorMarkedText.find(); + if (!highlightedRange) + return; + if (WebInspector.compareCodeMirrorPositions(highlightedRange.from, range.start) === 0 && + WebInspector.compareCodeMirrorPositions(highlightedRange.to, range.end) === 0) + return; + } + + this.removeHighlightedRange(); + + var className = this._classNameForHighlightedRange || ""; + this._codeMirrorMarkedText = this._codeMirror.markText(range.start, range.end, {className}); + + window.addEventListener("mousemove", this, true); + } + + removeHighlightedRange() + { + if (!this._codeMirrorMarkedText) + return; + + this._codeMirrorMarkedText.clear(); + this._codeMirrorMarkedText = null; + + window.removeEventListener("mousemove", this, true); + } + + // Private + + _startTracking() + { + if (this._tracking) + return; + + this._tracking = true; + + var wrapper = this._codeMirror.getWrapperElement(); + wrapper.addEventListener("mousemove", this, true); + wrapper.addEventListener("mouseout", this, false); + wrapper.addEventListener("mousedown", this, false); + wrapper.addEventListener("mouseup", this, false); + window.addEventListener("blur", this, true); + } + + _stopTracking() + { + if (!this._tracking) + return; + + this._tracking = false; + this._candidate = null; + + var wrapper = this._codeMirror.getWrapperElement(); + wrapper.removeEventListener("mousemove", this, true); + wrapper.removeEventListener("mouseout", this, false); + wrapper.removeEventListener("mousedown", this, false); + wrapper.removeEventListener("mouseup", this, false); + window.removeEventListener("blur", this, true); + window.removeEventListener("mousemove", this, true); + + this._resetTrackingStates(); + } + + handleEvent(event) + { + switch (event.type) { + case "mouseenter": + this._mouseEntered(event); + break; + case "mouseleave": + this._mouseLeft(event); + break; + case "mousemove": + if (event.currentTarget === window) + this._mouseMovedWithMarkedText(event); + else + this._mouseMovedOverEditor(event); + break; + case "mouseout": + // Only deal with a mouseout event that has the editor wrapper as the target. + if (!event.currentTarget.contains(event.relatedTarget)) + this._mouseMovedOutOfEditor(event); + break; + case "mousedown": + this._mouseButtonWasPressedOverEditor(event); + break; + case "mouseup": + this._mouseButtonWasReleasedOverEditor(event); + break; + case "blur": + this._windowLostFocus(event); + break; + } + } + + _handleCommandEnterKey(codeMirror) + { + const tokenInfo = this._getTokenInfoForPosition(codeMirror.getCursor("head")); + tokenInfo.triggeredBy = WebInspector.CodeMirrorTokenTrackingController.TriggeredBy.Keyboard; + this._processNewHoveredToken(tokenInfo); + } + + _hidePopover() + { + if (!this._candidate) + return CodeMirror.Pass; + + if (this._delegate && typeof this._delegate.tokenTrackingControllerHighlightedRangeReleased === "function") { + const forceHidePopover = true; + this._delegate.tokenTrackingControllerHighlightedRangeReleased(this, forceHidePopover); + } + } + + _mouseEntered(event) + { + if (!this._tracking) + this._startTracking(); + } + + _mouseLeft(event) + { + this._stopTracking(); + } + + _mouseMovedWithMarkedText(event) + { + if (this._candidate && this._candidate.triggeredBy === WebInspector.CodeMirrorTokenTrackingController.TriggeredBy.Keyboard) + return; + + var shouldRelease = !event.target.classList.contains(this._classNameForHighlightedRange); + if (shouldRelease && this._delegate && typeof this._delegate.tokenTrackingControllerCanReleaseHighlightedRange === "function") + shouldRelease = this._delegate.tokenTrackingControllerCanReleaseHighlightedRange(this, event.target); + + if (shouldRelease) { + if (!this._markedTextMouseoutTimer) + this._markedTextMouseoutTimer = setTimeout(this._markedTextIsNoLongerHovered.bind(this), this._mouseOutReleaseDelayDuration); + return; + } + + if (this._markedTextMouseoutTimer) + clearTimeout(this._markedTextMouseoutTimer); + + this._markedTextMouseoutTimer = 0; + } + + _markedTextIsNoLongerHovered() + { + if (this._delegate && typeof this._delegate.tokenTrackingControllerHighlightedRangeReleased === "function") + this._delegate.tokenTrackingControllerHighlightedRangeReleased(this); + + this._markedTextMouseoutTimer = 0; + } + + _mouseMovedOverEditor(event) + { + this._updateHoveredTokenInfo({left: event.pageX, top: event.pageY}); + } + + _updateHoveredTokenInfo(mouseCoords) + { + // Get the position in the text and the token at that position. + var position = this._codeMirror.coordsChar(mouseCoords); + var token = this._codeMirror.getTokenAt(position); + + if (!token || !token.type || !token.string) { + if (this._hoveredMarker && this._delegate && typeof this._delegate.tokenTrackingControllerMouseOutOfHoveredMarker === "function") { + if (!this._codeMirror.findMarksAt(position).includes(this._hoveredMarker.codeMirrorTextMarker)) + this._delegate.tokenTrackingControllerMouseOutOfHoveredMarker(this, this._hoveredMarker); + } + + this._resetTrackingStates(); + return; + } + + // Stop right here if we're hovering the same token as we were last time. + if (this._previousTokenInfo && + this._previousTokenInfo.position.line === position.line && + this._previousTokenInfo.token.start === token.start && + this._previousTokenInfo.token.end === token.end) + return; + + // We have a new hovered token. + var tokenInfo = this._previousTokenInfo = this._getTokenInfoForPosition(position); + + if (/\bmeta\b/.test(token.type)) { + let nextTokenPosition = Object.shallowCopy(position); + nextTokenPosition.ch = tokenInfo.token.end + 1; + + let nextToken = this._codeMirror.getTokenAt(nextTokenPosition); + if (nextToken && nextToken.type && !/\bmeta\b/.test(nextToken.type)) { + console.assert(tokenInfo.token.end === nextToken.start); + + tokenInfo.token.type = nextToken.type; + tokenInfo.token.string = tokenInfo.token.string + nextToken.string; + tokenInfo.token.end = nextToken.end; + } + } else { + let previousTokenPosition = Object.shallowCopy(position); + previousTokenPosition.ch = tokenInfo.token.start - 1; + + let previousToken = this._codeMirror.getTokenAt(previousTokenPosition); + if (previousToken && previousToken.type && /\bmeta\b/.test(previousToken.type)) { + console.assert(tokenInfo.token.start === previousToken.end); + + tokenInfo.token.string = previousToken.string + tokenInfo.token.string; + tokenInfo.token.start = previousToken.start; + } + } + + if (this._tokenHoverTimer) + clearTimeout(this._tokenHoverTimer); + + this._tokenHoverTimer = 0; + + if (this._codeMirrorMarkedText || !this._mouseOverDelayDuration) + this._processNewHoveredToken(tokenInfo); + else + this._tokenHoverTimer = setTimeout(this._processNewHoveredToken.bind(this, tokenInfo), this._mouseOverDelayDuration); + } + + _getTokenInfoForPosition(position) + { + var token = this._codeMirror.getTokenAt(position); + var innerMode = CodeMirror.innerMode(this._codeMirror.getMode(), token.state); + var codeMirrorModeName = innerMode.mode.alternateName || innerMode.mode.name; + return { + token, + position, + innerMode, + modeName: codeMirrorModeName + }; + } + + _mouseMovedOutOfEditor(event) + { + if (this._tokenHoverTimer) + clearTimeout(this._tokenHoverTimer); + + this._tokenHoverTimer = 0; + this._previousTokenInfo = null; + this._selectionMayBeInProgress = false; + } + + _mouseButtonWasPressedOverEditor(event) + { + this._selectionMayBeInProgress = true; + } + + _mouseButtonWasReleasedOverEditor(event) + { + this._selectionMayBeInProgress = false; + this._mouseMovedOverEditor(event); + + if (this._codeMirrorMarkedText && this._previousTokenInfo) { + var position = this._codeMirror.coordsChar({left: event.pageX, top: event.pageY}); + var marks = this._codeMirror.findMarksAt(position); + for (var i = 0; i < marks.length; ++i) { + if (marks[i] === this._codeMirrorMarkedText) { + if (this._delegate && typeof this._delegate.tokenTrackingControllerHighlightedRangeWasClicked === "function") + this._delegate.tokenTrackingControllerHighlightedRangeWasClicked(this); + + break; + } + } + } + } + + _windowLostFocus(event) + { + this._resetTrackingStates(); + } + + _processNewHoveredToken(tokenInfo) + { + console.assert(tokenInfo); + + if (this._selectionMayBeInProgress) + return; + + this._candidate = null; + + switch (this._mode) { + case WebInspector.CodeMirrorTokenTrackingController.Mode.NonSymbolTokens: + this._candidate = this._processNonSymbolToken(tokenInfo); + break; + case WebInspector.CodeMirrorTokenTrackingController.Mode.JavaScriptExpression: + case WebInspector.CodeMirrorTokenTrackingController.Mode.JavaScriptTypeInformation: + this._candidate = this._processJavaScriptExpression(tokenInfo); + break; + case WebInspector.CodeMirrorTokenTrackingController.Mode.MarkedTokens: + this._candidate = this._processMarkedToken(tokenInfo); + break; + } + + if (!this._candidate) + return; + + this._candidate.triggeredBy = tokenInfo.triggeredBy; + + if (this._markedTextMouseoutTimer) + clearTimeout(this._markedTextMouseoutTimer); + + this._markedTextMouseoutTimer = 0; + + if (this._delegate && typeof this._delegate.tokenTrackingControllerNewHighlightCandidate === "function") + this._delegate.tokenTrackingControllerNewHighlightCandidate(this, this._candidate); + } + + _processNonSymbolToken(tokenInfo) + { + // Ignore any symbol tokens. + var type = tokenInfo.token.type; + if (!type) + return null; + + var startPosition = {line: tokenInfo.position.line, ch: tokenInfo.token.start}; + var endPosition = {line: tokenInfo.position.line, ch: tokenInfo.token.end}; + + return { + hoveredToken: tokenInfo.token, + hoveredTokenRange: {start: startPosition, end: endPosition}, + }; + } + + _processJavaScriptExpression(tokenInfo) + { + // Only valid within JavaScript. + if (tokenInfo.modeName !== "javascript") + return null; + + var startPosition = {line: tokenInfo.position.line, ch: tokenInfo.token.start}; + var endPosition = {line: tokenInfo.position.line, ch: tokenInfo.token.end}; + + function tokenIsInRange(token, range) + { + return token.line >= range.start.line && token.ch >= range.start.ch && + token.line <= range.end.line && token.ch <= range.end.ch; + } + + // If the hovered token is within a selection, use the selection as our expression. + if (this._codeMirror.somethingSelected()) { + var selectionRange = { + start: this._codeMirror.getCursor("start"), + end: this._codeMirror.getCursor("end") + }; + + if (tokenIsInRange(startPosition, selectionRange) || tokenIsInRange(endPosition, selectionRange)) { + return { + hoveredToken: tokenInfo.token, + hoveredTokenRange: selectionRange, + expression: this._codeMirror.getSelection(), + expressionRange: selectionRange, + }; + } + } + + // We only handle vars, definitions, properties, and the keyword 'this'. + var type = tokenInfo.token.type; + var isProperty = type.indexOf("property") !== -1; + var isKeyword = type.indexOf("keyword") !== -1; + if (!isProperty && !isKeyword && type.indexOf("variable") === -1 && type.indexOf("def") === -1) + return null; + + // Not object literal property names, but yes if an object literal shorthand property, which is a variable. + let state = tokenInfo.innerMode.state; + if (isProperty && state.lexical && state.lexical.type === "}") { + // Peek ahead to see if the next token is "}" or ",". If it is, we are a shorthand and therefore a variable. + let shorthand = false; + let mode = tokenInfo.innerMode.mode; + let position = {line: tokenInfo.position.line, ch: tokenInfo.token.end}; + WebInspector.walkTokens(this._codeMirror, mode, position, function(tokenType, string) { + if (tokenType) + return false; + if (string === "(") + return false; + if (string === "," || string === "}") { + shorthand = true; + return false; + } + return true; + }); + + if (!shorthand) + return null; + } + + // Only the "this" keyword. + if (isKeyword && tokenInfo.token.string !== "this") + return null; + + // Work out the full hovered expression. + var expression = tokenInfo.token.string; + var expressionStartPosition = {line: tokenInfo.position.line, ch: tokenInfo.token.start}; + while (true) { + var token = this._codeMirror.getTokenAt(expressionStartPosition); + if (!token) + break; + + var isDot = !token.type && token.string === "."; + var isExpression = token.type && token.type.includes("m-javascript"); + if (!isDot && !isExpression) + break; + + // Disallow operators. We want the hovered expression to be just a single operand. + // Also, some operators can modify values, such as pre-increment and assignment operators. + if (isExpression && token.type.includes("operator")) + break; + + expression = token.string + expression; + expressionStartPosition.ch = token.start; + } + + // Return the candidate for this token and expression. + return { + hoveredToken: tokenInfo.token, + hoveredTokenRange: {start: startPosition, end: endPosition}, + expression, + expressionRange: {start: expressionStartPosition, end: endPosition}, + }; + } + + _processMarkedToken(tokenInfo) + { + return this._processNonSymbolToken(tokenInfo); + } + + _resetTrackingStates() + { + if (this._tokenHoverTimer) + clearTimeout(this._tokenHoverTimer); + + this._tokenHoverTimer = 0; + + this._selectionMayBeInProgress = false; + this._previousTokenInfo = null; + this.removeHighlightedRange(); + } +}; + +WebInspector.CodeMirrorTokenTrackingController.JumpToSymbolHighlightStyleClassName = "jump-to-symbol-highlight"; + +WebInspector.CodeMirrorTokenTrackingController.Mode = { + None: "none", + NonSymbolTokens: "non-symbol-tokens", + JavaScriptExpression: "javascript-expression", + JavaScriptTypeInformation: "javascript-type-information", + MarkedTokens: "marked-tokens" +}; + +WebInspector.CodeMirrorTokenTrackingController.TriggeredBy = { + Keyboard: "keyboard", + Hover: "hover" +}; diff --git a/Source/WebInspectorUI/UserInterface/Controllers/DOMTreeManager.js b/Source/WebInspectorUI/UserInterface/Controllers/DOMTreeManager.js new file mode 100644 index 000000000..c7c4003de --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/DOMTreeManager.js @@ -0,0 +1,795 @@ +/* + * Copyright (C) 2009, 2010 Google Inc. All rights reserved. + * Copyright (C) 2009 Joseph Pecoraro + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.DOMTreeManager = class DOMTreeManager extends WebInspector.Object +{ + constructor() + { + super(); + + this._idToDOMNode = {}; + this._document = null; + this._attributeLoadNodeIds = {}; + this._flows = new Map; + this._contentNodesToFlowsMap = new Map; + this._restoreSelectedNodeIsAllowed = true; + this._loadNodeAttributesTimeout = 0; + + WebInspector.Frame.addEventListener(WebInspector.Frame.Event.MainResourceDidChange, this._mainResourceDidChange, this); + } + + // Static + + static _flowPayloadHashKey(flowPayload) + { + // Use the flow node id, to avoid collisions when we change main document id. + return flowPayload.documentNodeId + ":" + flowPayload.name; + } + + // Public + + requestDocument(callback) + { + if (this._document) { + 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 (let callback of this._pendingDocumentRequestCallbacks) + callback(this._document); + + this._pendingDocumentRequestCallbacks = null; + } + + DOMAgent.getDocument(onDocumentAvailable.bind(this)); + } + + pushNodeToFrontend(objectId, callback) + { + this._dispatchWhenDocumentAvailable(DOMAgent.requestNode.bind(DOMAgent, objectId), callback); + } + + pushNodeByPathToFrontend(path, callback) + { + this._dispatchWhenDocumentAvailable(DOMAgent.pushNodeByPathToFrontend.bind(DOMAgent, path), callback); + } + + // Private + + _wrapClientCallback(callback) + { + if (!callback) + return null; + + return function(error, result) { + if (error) + console.error("Error during DOMAgent operation: " + error); + callback(error ? null : result); + }; + } + + _dispatchWhenDocumentAvailable(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(nodeId, name, value) + { + var node = this._idToDOMNode[nodeId]; + if (!node) + return; + + node._setAttribute(name, value); + this.dispatchEventToListeners(WebInspector.DOMTreeManager.Event.AttributeModified, {node, name}); + node.dispatchEventToListeners(WebInspector.DOMNode.Event.AttributeModified, {name}); + } + + _attributeRemoved(nodeId, name) + { + var node = this._idToDOMNode[nodeId]; + if (!node) + return; + + node._removeAttribute(name); + this.dispatchEventToListeners(WebInspector.DOMTreeManager.Event.AttributeRemoved, {node, name}); + node.dispatchEventToListeners(WebInspector.DOMNode.Event.AttributeRemoved, {name}); + } + + _inlineStyleInvalidated(nodeIds) + { + for (var nodeId of nodeIds) + this._attributeLoadNodeIds[nodeId] = true; + if (this._loadNodeAttributesTimeout) + return; + this._loadNodeAttributesTimeout = setTimeout(this._loadNodeAttributes.bind(this), 0); + } + + _loadNodeAttributes() + { + function callback(nodeId, error, attributes) + { + if (error) { + console.error("Error during DOMAgent operation: " + error); + return; + } + var node = this._idToDOMNode[nodeId]; + if (node) { + node._setAttributesPayload(attributes); + this.dispatchEventToListeners(WebInspector.DOMTreeManager.Event.AttributeModified, {node, name: "style"}); + node.dispatchEventToListeners(WebInspector.DOMNode.Event.AttributeModified, {name: "style"}); + } + } + + this._loadNodeAttributesTimeout = 0; + + for (var nodeId in this._attributeLoadNodeIds) { + var nodeIdAsNumber = parseInt(nodeId); + DOMAgent.getAttributes(nodeIdAsNumber, callback.bind(this, nodeIdAsNumber)); + } + this._attributeLoadNodeIds = {}; + } + + _characterDataModified(nodeId, newValue) + { + var node = this._idToDOMNode[nodeId]; + node._nodeValue = newValue; + this.dispatchEventToListeners(WebInspector.DOMTreeManager.Event.CharacterDataModified, {node}); + } + + nodeForId(nodeId) + { + return this._idToDOMNode[nodeId]; + } + + _documentUpdated() + { + this._setDocument(null); + } + + _setDocument(payload) + { + this._idToDOMNode = {}; + if (payload && "nodeId" in payload) + this._document = new WebInspector.DOMNode(this, null, false, payload); + else + this._document = null; + this.dispatchEventToListeners(WebInspector.DOMTreeManager.Event.DocumentUpdated, this._document); + } + + _setDetachedRoot(payload) + { + new WebInspector.DOMNode(this, null, false, payload); + } + + _setChildNodes(parentId, payloads) + { + if (!parentId && payloads.length) { + this._setDetachedRoot(payloads[0]); + return; + } + + var parent = this._idToDOMNode[parentId]; + parent._setChildrenPayload(payloads); + } + + _childNodeCountUpdated(nodeId, newValue) + { + var node = this._idToDOMNode[nodeId]; + node.childNodeCount = newValue; + this.dispatchEventToListeners(WebInspector.DOMTreeManager.Event.ChildNodeCountUpdated, node); + } + + _childNodeInserted(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.DOMTreeManager.Event.NodeInserted, {node, parent}); + } + + _childNodeRemoved(parentId, nodeId) + { + var parent = this._idToDOMNode[parentId]; + var node = this._idToDOMNode[nodeId]; + parent._removeChild(node); + this._unbind(node); + this.dispatchEventToListeners(WebInspector.DOMTreeManager.Event.NodeRemoved, {node, parent}); + } + + _customElementStateChanged(elementId, newState) + { + const node = this._idToDOMNode[elementId]; + node._customElementState = newState; + this.dispatchEventToListeners(WebInspector.DOMTreeManager.Event.CustomElementStateChanged, {node}); + } + + _pseudoElementAdded(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.DOMTreeManager.Event.NodeInserted, {node, parent}); + } + + _pseudoElementRemoved(parentId, pseudoElementId) + { + var pseudoElement = this._idToDOMNode[pseudoElementId]; + if (!pseudoElement) + return; + + var parent = pseudoElement.parentNode; + console.assert(parent); + console.assert(parent.id === parentId); + if (!parent) + return; + + parent._removeChild(pseudoElement); + this._unbind(pseudoElement); + this.dispatchEventToListeners(WebInspector.DOMTreeManager.Event.NodeRemoved, {node: pseudoElement, parent}); + } + + _unbind(node) + { + this._removeContentNodeFromFlowIfNeeded(node); + + delete this._idToDOMNode[node.id]; + + for (let i = 0; node.children && i < node.children.length; ++i) + this._unbind(node.children[i]); + + let templateContent = node.templateContent(); + if (templateContent) + this._unbind(templateContent); + + for (let pseudoElement of node.pseudoElements().values()) + this._unbind(pseudoElement); + + // FIXME: Handle shadow roots. + } + + get restoreSelectedNodeIsAllowed() + { + return this._restoreSelectedNodeIsAllowed; + } + + inspectElement(nodeId) + { + var node = this._idToDOMNode[nodeId]; + if (!node || !node.ownerDocument) + return; + + this.dispatchEventToListeners(WebInspector.DOMTreeManager.Event.DOMNodeWasInspected, {node}); + + this._inspectModeEnabled = false; + this.dispatchEventToListeners(WebInspector.DOMTreeManager.Event.InspectModeStateChanged); + } + + inspectNodeObject(remoteObject) + { + this._restoreSelectedNodeIsAllowed = false; + + function nodeAvailable(nodeId) + { + remoteObject.release(); + + console.assert(nodeId); + if (!nodeId) + return; + + this.inspectElement(nodeId); + + // Re-resolve the node in the console's object group when adding to the console. + let domNode = this.nodeForId(nodeId); + WebInspector.RemoteObject.resolveNode(domNode, WebInspector.RuntimeManager.ConsoleObjectGroup, function(remoteObject) { + if (!remoteObject) + return; + let specialLogStyles = true; + let shouldRevealConsole = false; + WebInspector.consoleLogViewController.appendImmediateExecutionWithResult(WebInspector.UIString("Selected Element"), remoteObject, specialLogStyles, shouldRevealConsole); + }); + } + + remoteObject.pushNodeToFrontend(nodeAvailable.bind(this)); + } + + performSearch(query, searchCallback) + { + this.cancelSearch(); + + function callback(error, searchId, resultsCount) + { + this._searchId = searchId; + searchCallback(resultsCount); + } + DOMAgent.performSearch(query, callback.bind(this)); + } + + searchResult(index, callback) + { + function mycallback(error, nodeIds) + { + if (error) { + console.error(error); + callback(null); + return; + } + if (nodeIds.length !== 1) + return; + + callback(this._idToDOMNode[nodeIds[0]]); + } + + if (this._searchId) + DOMAgent.getSearchResults(this._searchId, index, index + 1, mycallback.bind(this)); + else + callback(null); + } + + cancelSearch() + { + if (this._searchId) { + DOMAgent.discardSearchResults(this._searchId); + this._searchId = undefined; + } + } + + querySelector(nodeId, selectors, callback) + { + DOMAgent.querySelector(nodeId, selectors, this._wrapClientCallback(callback)); + } + + querySelectorAll(nodeId, selectors, callback) + { + DOMAgent.querySelectorAll(nodeId, selectors, this._wrapClientCallback(callback)); + } + + highlightDOMNode(nodeId, mode) + { + if (this._hideDOMNodeHighlightTimeout) { + clearTimeout(this._hideDOMNodeHighlightTimeout); + this._hideDOMNodeHighlightTimeout = undefined; + } + + this._highlightedDOMNodeId = nodeId; + if (nodeId) + DOMAgent.highlightNode.invoke({nodeId, highlightConfig: this._buildHighlightConfig(mode)}); + else + DOMAgent.hideHighlight(); + } + + highlightSelector(selectorText, frameId, mode) + { + // COMPATIBILITY (iOS 8): DOM.highlightSelector did not exist. + if (!DOMAgent.highlightSelector) + return; + + DOMAgent.highlightSelector(this._buildHighlightConfig(mode), selectorText, frameId); + } + + highlightRect(rect, usePageCoordinates) + { + DOMAgent.highlightRect.invoke({ + x: rect.x, + y: rect.y, + width: rect.width, + height: rect.height, + color: {r: 111, g: 168, b: 220, a: 0.66}, + outlineColor: {r: 255, g: 229, b: 153, a: 0.66}, + usePageCoordinates + }); + } + + hideDOMNodeHighlight() + { + this.highlightDOMNode(0); + } + + highlightDOMNodeForTwoSeconds(nodeId) + { + this.highlightDOMNode(nodeId); + this._hideDOMNodeHighlightTimeout = setTimeout(this.hideDOMNodeHighlight.bind(this), 2000); + } + + get inspectModeEnabled() + { + return this._inspectModeEnabled; + } + + set inspectModeEnabled(enabled) + { + if (enabled === this._inspectModeEnabled) + return; + + DOMAgent.setInspectModeEnabled(enabled, this._buildHighlightConfig(), (error) => { + this._inspectModeEnabled = error ? false : enabled; + this.dispatchEventToListeners(WebInspector.DOMTreeManager.Event.InspectModeStateChanged); + }); + } + + _buildHighlightConfig(mode = "all") + { + let highlightConfig = {showInfo: mode === "all"}; + + if (mode === "all" || mode === "content") + highlightConfig.contentColor = {r: 111, g: 168, b: 220, a: 0.66}; + + if (mode === "all" || mode === "padding") + highlightConfig.paddingColor = {r: 147, g: 196, b: 125, a: 0.66}; + + if (mode === "all" || mode === "border") + highlightConfig.borderColor = {r: 255, g: 229, b: 153, a: 0.66}; + + if (mode === "all" || mode === "margin") + highlightConfig.marginColor = {r: 246, g: 178, b: 107, a: 0.66}; + + return highlightConfig; + } + + _createContentFlowFromPayload(flowPayload) + { + // FIXME: Collect the regions from the payload. + var flow = new WebInspector.ContentFlow(flowPayload.documentNodeId, flowPayload.name, flowPayload.overset, flowPayload.content.map(this.nodeForId.bind(this))); + + for (var contentNode of flow.contentNodes) { + console.assert(!this._contentNodesToFlowsMap.has(contentNode.id)); + this._contentNodesToFlowsMap.set(contentNode.id, flow); + } + + return flow; + } + + _updateContentFlowFromPayload(contentFlow, flowPayload) + { + console.assert(contentFlow.contentNodes.length === flowPayload.content.length); + console.assert(contentFlow.contentNodes.every((node, i) => node.id === flowPayload.content[i])); + + // FIXME: Collect the regions from the payload. + contentFlow.overset = flowPayload.overset; + } + + getNamedFlowCollection(documentNodeIdentifier) + { + function onNamedFlowCollectionAvailable(error, flows) + { + if (error) + return; + this._contentNodesToFlowsMap.clear(); + var contentFlows = []; + for (var i = 0; i < flows.length; ++i) { + var flowPayload = flows[i]; + var flowKey = WebInspector.DOMTreeManager._flowPayloadHashKey(flowPayload); + var contentFlow = this._flows.get(flowKey); + if (contentFlow) + this._updateContentFlowFromPayload(contentFlow, flowPayload); + else { + contentFlow = this._createContentFlowFromPayload(flowPayload); + this._flows.set(flowKey, contentFlow); + } + contentFlows.push(contentFlow); + } + this.dispatchEventToListeners(WebInspector.DOMTreeManager.Event.ContentFlowListWasUpdated, {documentNodeIdentifier, flows: contentFlows}); + } + + if (window.CSSAgent) + CSSAgent.getNamedFlowCollection(documentNodeIdentifier, onNamedFlowCollectionAvailable.bind(this)); + } + + namedFlowCreated(flowPayload) + { + var flowKey = WebInspector.DOMTreeManager._flowPayloadHashKey(flowPayload); + console.assert(!this._flows.has(flowKey)); + var contentFlow = this._createContentFlowFromPayload(flowPayload); + this._flows.set(flowKey, contentFlow); + this.dispatchEventToListeners(WebInspector.DOMTreeManager.Event.ContentFlowWasAdded, {flow: contentFlow}); + } + + namedFlowRemoved(documentNodeIdentifier, flowName) + { + var flowKey = WebInspector.DOMTreeManager._flowPayloadHashKey({documentNodeId: documentNodeIdentifier, name: flowName}); + var contentFlow = this._flows.get(flowKey); + console.assert(contentFlow); + this._flows.delete(flowKey); + + // Remove any back links to this flow from the content nodes. + for (var contentNode of contentFlow.contentNodes) + this._contentNodesToFlowsMap.delete(contentNode.id); + + this.dispatchEventToListeners(WebInspector.DOMTreeManager.Event.ContentFlowWasRemoved, {flow: contentFlow}); + } + + _sendNamedFlowUpdateEvents(flowPayload) + { + var flowKey = WebInspector.DOMTreeManager._flowPayloadHashKey(flowPayload); + console.assert(this._flows.has(flowKey)); + this._updateContentFlowFromPayload(this._flows.get(flowKey), flowPayload); + } + + regionOversetChanged(flowPayload) + { + this._sendNamedFlowUpdateEvents(flowPayload); + } + + registeredNamedFlowContentElement(documentNodeIdentifier, flowName, contentNodeId, nextContentElementNodeId) + { + var flowKey = WebInspector.DOMTreeManager._flowPayloadHashKey({documentNodeId: documentNodeIdentifier, name: flowName}); + console.assert(this._flows.has(flowKey)); + console.assert(!this._contentNodesToFlowsMap.has(contentNodeId)); + + var flow = this._flows.get(flowKey); + var contentNode = this.nodeForId(contentNodeId); + + this._contentNodesToFlowsMap.set(contentNode.id, flow); + + if (nextContentElementNodeId) + flow.insertContentNodeBefore(contentNode, this.nodeForId(nextContentElementNodeId)); + else + flow.appendContentNode(contentNode); + } + + _removeContentNodeFromFlowIfNeeded(node) + { + if (!this._contentNodesToFlowsMap.has(node.id)) + return; + var flow = this._contentNodesToFlowsMap.get(node.id); + this._contentNodesToFlowsMap.delete(node.id); + flow.removeContentNode(node); + } + + unregisteredNamedFlowContentElement(documentNodeIdentifier, flowName, contentNodeId) + { + console.assert(this._contentNodesToFlowsMap.has(contentNodeId)); + + var flow = this._contentNodesToFlowsMap.get(contentNodeId); + console.assert(flow.id === WebInspector.DOMTreeManager._flowPayloadHashKey({documentNodeId: documentNodeIdentifier, name: flowName})); + + this._contentNodesToFlowsMap.delete(contentNodeId); + flow.removeContentNode(this.nodeForId(contentNodeId)); + } + + _coerceRemoteArrayOfDOMNodes(remoteObject, callback) + { + console.assert(remoteObject.type === "object"); + console.assert(remoteObject.subtype === "array"); + + let length = remoteObject.size; + if (!length) { + callback(null, []); + return; + } + + let nodes; + let received = 0; + let lastError = null; + let domTreeManager = this; + + function nodeRequested(index, error, nodeId) + { + if (error) + lastError = error; + else + nodes[index] = domTreeManager._idToDOMNode[nodeId]; + if (++received === length) + callback(lastError, nodes); + } + + WebInspector.runtimeManager.getPropertiesForRemoteObject(remoteObject.objectId, function(error, properties) { + if (error) { + callback(error); + return; + } + + nodes = new Array(length); + for (let i = 0; i < length; ++i) { + let nodeProperty = properties.get(String(i)); + console.assert(nodeProperty.value.type === "object"); + console.assert(nodeProperty.value.subtype === "node"); + DOMAgent.requestNode(nodeProperty.value.objectId, nodeRequested.bind(null, i)); + } + }); + } + + getNodeContentFlowInfo(domNode, resultReadyCallback) + { + DOMAgent.resolveNode(domNode.id, domNodeResolved.bind(this)); + + function domNodeResolved(error, remoteObject) + { + if (error) { + resultReadyCallback(error); + return; + } + + var evalParameters = { + objectId: remoteObject.objectId, + functionDeclaration: appendWebInspectorSourceURL(inspectedPage_node_getFlowInfo.toString()), + doNotPauseOnExceptionsAndMuteConsole: true, + returnByValue: false, + generatePreview: false + }; + RuntimeAgent.callFunctionOn.invoke(evalParameters, regionNodesAvailable.bind(this)); + } + + function regionNodesAvailable(error, remoteObject, wasThrown) + { + if (error) { + resultReadyCallback(error); + return; + } + + if (wasThrown) { + // We should never get here, but having the error is useful for debugging. + console.error("Error while executing backend function:", JSON.stringify(remoteObject)); + resultReadyCallback(null); + return; + } + + // The backend function can never return null. + console.assert(remoteObject.type === "object"); + console.assert(remoteObject.objectId); + WebInspector.runtimeManager.getPropertiesForRemoteObject(remoteObject.objectId, remoteObjectPropertiesAvailable.bind(this)); + } + + function remoteObjectPropertiesAvailable(error, properties) { + if (error) { + resultReadyCallback(error); + return; + } + + var result = { + regionFlow: null, + contentFlow: null, + regions: null + }; + + var regionFlowNameProperty = properties.get("regionFlowName"); + if (regionFlowNameProperty && regionFlowNameProperty.value && regionFlowNameProperty.value.value) { + console.assert(regionFlowNameProperty.value.type === "string"); + var regionFlowKey = WebInspector.DOMTreeManager._flowPayloadHashKey({documentNodeId: domNode.ownerDocument.id, name: regionFlowNameProperty.value.value}); + result.regionFlow = this._flows.get(regionFlowKey); + } + + var contentFlowNameProperty = properties.get("contentFlowName"); + if (contentFlowNameProperty && contentFlowNameProperty.value && contentFlowNameProperty.value.value) { + console.assert(contentFlowNameProperty.value.type === "string"); + var contentFlowKey = WebInspector.DOMTreeManager._flowPayloadHashKey({documentNodeId: domNode.ownerDocument.id, name: contentFlowNameProperty.value.value}); + result.contentFlow = this._flows.get(contentFlowKey); + } + + var regionsProperty = properties.get("regions"); + if (!regionsProperty || !regionsProperty.value.objectId) { + // The list of regions is null. + resultReadyCallback(null, result); + return; + } + + this._coerceRemoteArrayOfDOMNodes(regionsProperty.value, function(error, nodes) { + result.regions = nodes; + resultReadyCallback(error, result); + }); + } + + function inspectedPage_node_getFlowInfo() + { + function getComputedProperty(node, propertyName) + { + if (!node.ownerDocument || !node.ownerDocument.defaultView) + return null; + var computedStyle = node.ownerDocument.defaultView.getComputedStyle(node); + return computedStyle ? computedStyle[propertyName] : null; + } + + function getContentFlowName(node) + { + for (; node; node = node.parentNode) { + var flowName = getComputedProperty(node, "webkitFlowInto"); + if (flowName && flowName !== "none") + return flowName; + } + return null; + } + + var node = this; + + // Even detached nodes have an ownerDocument. + console.assert(node.ownerDocument); + + var result = { + regionFlowName: getComputedProperty(node, "webkitFlowFrom"), + contentFlowName: getContentFlowName(node), + regions: null + }; + + if (result.contentFlowName) { + var flowThread = node.ownerDocument.webkitGetNamedFlows().namedItem(result.contentFlowName); + if (flowThread) + result.regions = Array.from(flowThread.getRegionsByContent(node)); + } + + return result; + } + } + + // Private + + _mainResourceDidChange(event) + { + if (event.target.isMainFrame()) + this._restoreSelectedNodeIsAllowed = true; + } +}; + +WebInspector.DOMTreeManager.Event = { + AttributeModified: "dom-tree-manager-attribute-modified", + AttributeRemoved: "dom-tree-manager-attribute-removed", + CharacterDataModified: "dom-tree-manager-character-data-modified", + NodeInserted: "dom-tree-manager-node-inserted", + NodeRemoved: "dom-tree-manager-node-removed", + CustomElementStateChanged: "dom-tree-manager-custom-element-state-changed", + DocumentUpdated: "dom-tree-manager-document-updated", + ChildNodeCountUpdated: "dom-tree-manager-child-node-count-updated", + DOMNodeWasInspected: "dom-tree-manager-dom-node-was-inspected", + InspectModeStateChanged: "dom-tree-manager-inspect-mode-state-changed", + ContentFlowListWasUpdated: "dom-tree-manager-content-flow-list-was-updated", + ContentFlowWasAdded: "dom-tree-manager-content-flow-was-added", + ContentFlowWasRemoved: "dom-tree-manager-content-flow-was-removed", + RegionOversetChanged: "dom-tree-manager-region-overset-changed" +}; diff --git a/Source/WebInspectorUI/UserInterface/Controllers/DashboardManager.js b/Source/WebInspectorUI/UserInterface/Controllers/DashboardManager.js new file mode 100644 index 000000000..48c4a8fd5 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/DashboardManager.js @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2013, 2014 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.DashboardManager = class DashboardManager extends WebInspector.Object +{ + constructor() + { + super(); + + this._dashboards = {}; + this._dashboards.default = new WebInspector.DefaultDashboard; + this._dashboards.debugger = new WebInspector.DebuggerDashboard; + this._dashboards.replay = new WebInspector.ReplayDashboard; + } + + get dashboards() + { + return this._dashboards; + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Controllers/DebuggerManager.js b/Source/WebInspectorUI/UserInterface/Controllers/DebuggerManager.js new file mode 100644 index 000000000..827263add --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/DebuggerManager.js @@ -0,0 +1,1217 @@ +/* + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.DebuggerManager = class DebuggerManager extends WebInspector.Object +{ + constructor() + { + super(); + + DebuggerAgent.enable(); + + WebInspector.notifications.addEventListener(WebInspector.Notification.DebugUIEnabledDidChange, this._debugUIEnabledDidChange, this); + + WebInspector.Breakpoint.addEventListener(WebInspector.Breakpoint.Event.DisplayLocationDidChange, this._breakpointDisplayLocationDidChange, this); + WebInspector.Breakpoint.addEventListener(WebInspector.Breakpoint.Event.DisabledStateDidChange, this._breakpointDisabledStateDidChange, this); + WebInspector.Breakpoint.addEventListener(WebInspector.Breakpoint.Event.ConditionDidChange, this._breakpointEditablePropertyDidChange, this); + WebInspector.Breakpoint.addEventListener(WebInspector.Breakpoint.Event.IgnoreCountDidChange, this._breakpointEditablePropertyDidChange, this); + WebInspector.Breakpoint.addEventListener(WebInspector.Breakpoint.Event.AutoContinueDidChange, this._breakpointEditablePropertyDidChange, this); + WebInspector.Breakpoint.addEventListener(WebInspector.Breakpoint.Event.ActionsDidChange, this._breakpointEditablePropertyDidChange, this); + + WebInspector.timelineManager.addEventListener(WebInspector.TimelineManager.Event.CapturingWillStart, this._timelineCapturingWillStart, this); + WebInspector.timelineManager.addEventListener(WebInspector.TimelineManager.Event.CapturingStopped, this._timelineCapturingStopped, this); + + WebInspector.targetManager.addEventListener(WebInspector.TargetManager.Event.TargetRemoved, this._targetRemoved, this); + + WebInspector.Frame.addEventListener(WebInspector.Frame.Event.MainResourceDidChange, this._mainResourceDidChange, this); + + this._breakpointsSetting = new WebInspector.Setting("breakpoints", []); + this._breakpointsEnabledSetting = new WebInspector.Setting("breakpoints-enabled", true); + this._allExceptionsBreakpointEnabledSetting = new WebInspector.Setting("break-on-all-exceptions", false); + this._allUncaughtExceptionsBreakpointEnabledSetting = new WebInspector.Setting("break-on-all-uncaught-exceptions", false); + this._assertionsBreakpointEnabledSetting = new WebInspector.Setting("break-on-assertions", false); + this._asyncStackTraceDepthSetting = new WebInspector.Setting("async-stack-trace-depth", 200); + + let specialBreakpointLocation = new WebInspector.SourceCodeLocation(null, Infinity, Infinity); + + this._allExceptionsBreakpoint = new WebInspector.Breakpoint(specialBreakpointLocation, !this._allExceptionsBreakpointEnabledSetting.value); + this._allExceptionsBreakpoint.resolved = true; + + this._allUncaughtExceptionsBreakpoint = new WebInspector.Breakpoint(specialBreakpointLocation, !this._allUncaughtExceptionsBreakpointEnabledSetting.value); + + this._assertionsBreakpoint = new WebInspector.Breakpoint(specialBreakpointLocation, !this._assertionsBreakpointEnabledSetting.value); + this._assertionsBreakpoint.resolved = true; + + this._breakpoints = []; + this._breakpointContentIdentifierMap = new Map; + this._breakpointScriptIdentifierMap = new Map; + this._breakpointIdMap = new Map; + + this._breakOnExceptionsState = "none"; + this._updateBreakOnExceptionsState(); + + this._nextBreakpointActionIdentifier = 1; + + this._activeCallFrame = null; + + this._internalWebKitScripts = []; + this._targetDebuggerDataMap = new Map; + this._targetDebuggerDataMap.set(WebInspector.mainTarget, new WebInspector.DebuggerData(WebInspector.mainTarget)); + + // Restore the correct breakpoints enabled setting if Web Inspector had + // previously been left in a state where breakpoints were temporarily disabled. + this._temporarilyDisabledBreakpointsRestoreSetting = new WebInspector.Setting("temporarily-disabled-breakpoints-restore", null); + if (this._temporarilyDisabledBreakpointsRestoreSetting.value !== null) { + this._breakpointsEnabledSetting.value = this._temporarilyDisabledBreakpointsRestoreSetting.value; + this._temporarilyDisabledBreakpointsRestoreSetting.value = null; + } + + DebuggerAgent.setBreakpointsActive(this._breakpointsEnabledSetting.value); + DebuggerAgent.setPauseOnExceptions(this._breakOnExceptionsState); + + // COMPATIBILITY (iOS 10): DebuggerAgent.setPauseOnAssertions did not exist yet. + if (DebuggerAgent.setPauseOnAssertions) + DebuggerAgent.setPauseOnAssertions(this._assertionsBreakpointEnabledSetting.value); + + // COMPATIBILITY (iOS 10): Debugger.setAsyncStackTraceDepth did not exist yet. + if (DebuggerAgent.setAsyncStackTraceDepth) + DebuggerAgent.setAsyncStackTraceDepth(this._asyncStackTraceDepthSetting.value); + + this._ignoreBreakpointDisplayLocationDidChangeEvent = false; + + function restoreBreakpointsSoon() { + this._restoringBreakpoints = true; + for (let cookie of this._breakpointsSetting.value) + this.addBreakpoint(new WebInspector.Breakpoint(cookie)); + this._restoringBreakpoints = false; + } + + // Ensure that all managers learn about restored breakpoints, + // regardless of their initialization order. + setTimeout(restoreBreakpointsSoon.bind(this), 0); + } + + // Public + + get paused() + { + for (let [target, targetData] of this._targetDebuggerDataMap) { + if (targetData.paused) + return true; + } + + return false; + } + + get activeCallFrame() + { + return this._activeCallFrame; + } + + set activeCallFrame(callFrame) + { + if (callFrame === this._activeCallFrame) + return; + + this._activeCallFrame = callFrame || null; + + this.dispatchEventToListeners(WebInspector.DebuggerManager.Event.ActiveCallFrameDidChange); + } + + dataForTarget(target) + { + let targetData = this._targetDebuggerDataMap.get(target); + if (targetData) + return targetData; + + targetData = new WebInspector.DebuggerData(target); + this._targetDebuggerDataMap.set(target, targetData); + return targetData; + } + + get allExceptionsBreakpoint() + { + return this._allExceptionsBreakpoint; + } + + get allUncaughtExceptionsBreakpoint() + { + return this._allUncaughtExceptionsBreakpoint; + } + + get assertionsBreakpoint() + { + return this._assertionsBreakpoint; + } + + get breakpoints() + { + return this._breakpoints; + } + + breakpointForIdentifier(id) + { + return this._breakpointIdMap.get(id) || null; + } + + breakpointsForSourceCode(sourceCode) + { + console.assert(sourceCode instanceof WebInspector.Resource || sourceCode instanceof WebInspector.Script); + + if (sourceCode instanceof WebInspector.SourceMapResource) { + let originalSourceCodeBreakpoints = this.breakpointsForSourceCode(sourceCode.sourceMap.originalSourceCode); + return originalSourceCodeBreakpoints.filter(function(breakpoint) { + return breakpoint.sourceCodeLocation.displaySourceCode === sourceCode; + }); + } + + let contentIdentifierBreakpoints = this._breakpointContentIdentifierMap.get(sourceCode.contentIdentifier); + if (contentIdentifierBreakpoints) { + this._associateBreakpointsWithSourceCode(contentIdentifierBreakpoints, sourceCode); + return contentIdentifierBreakpoints; + } + + if (sourceCode instanceof WebInspector.Script) { + let scriptIdentifierBreakpoints = this._breakpointScriptIdentifierMap.get(sourceCode.id); + if (scriptIdentifierBreakpoints) { + this._associateBreakpointsWithSourceCode(scriptIdentifierBreakpoints, sourceCode); + return scriptIdentifierBreakpoints; + } + } + + return []; + } + + isBreakpointRemovable(breakpoint) + { + return breakpoint !== this._allExceptionsBreakpoint + && breakpoint !== this._allUncaughtExceptionsBreakpoint + && breakpoint !== this._assertionsBreakpoint; + } + + isBreakpointEditable(breakpoint) + { + return this.isBreakpointRemovable(breakpoint); + } + + get breakpointsEnabled() + { + return this._breakpointsEnabledSetting.value; + } + + set breakpointsEnabled(enabled) + { + if (this._breakpointsEnabledSetting.value === enabled) + return; + + console.assert(!(enabled && this.breakpointsDisabledTemporarily), "Should not enable breakpoints when we are temporarily disabling breakpoints."); + if (enabled && this.breakpointsDisabledTemporarily) + return; + + this._breakpointsEnabledSetting.value = enabled; + + this._updateBreakOnExceptionsState(); + + for (let target of WebInspector.targets) { + target.DebuggerAgent.setBreakpointsActive(enabled); + target.DebuggerAgent.setPauseOnExceptions(this._breakOnExceptionsState); + } + + this.dispatchEventToListeners(WebInspector.DebuggerManager.Event.BreakpointsEnabledDidChange); + } + + get breakpointsDisabledTemporarily() + { + return this._temporarilyDisabledBreakpointsRestoreSetting.value !== null; + } + + scriptForIdentifier(id, target) + { + console.assert(target instanceof WebInspector.Target); + return this.dataForTarget(target).scriptForIdentifier(id); + } + + scriptsForURL(url, target) + { + // FIXME: This may not be safe. A Resource's URL may differ from a Script's URL. + console.assert(target instanceof WebInspector.Target); + return this.dataForTarget(target).scriptsForURL(url); + } + + get searchableScripts() + { + return this.knownNonResourceScripts.filter((script) => !!script.contentIdentifier); + } + + get knownNonResourceScripts() + { + let knownScripts = []; + + for (let [target, targetData] of this._targetDebuggerDataMap) { + for (let script of targetData.scripts) { + if (script.resource) + continue; + if (!WebInspector.isDebugUIEnabled() && isWebKitInternalScript(script.sourceURL)) + continue; + knownScripts.push(script); + } + } + + return knownScripts; + } + + get asyncStackTraceDepth() + { + return this._asyncStackTraceDepthSetting.value; + } + + set asyncStackTraceDepth(x) + { + if (this._asyncStackTraceDepthSetting.value === x) + return; + + this._asyncStackTraceDepthSetting.value = x; + + for (let target of WebInspector.targets) + target.DebuggerAgent.setAsyncStackTraceDepth(this._asyncStackTraceDepthSetting.value); + } + + pause() + { + if (this.paused) + return Promise.resolve(); + + this.dispatchEventToListeners(WebInspector.DebuggerManager.Event.WaitingToPause); + + let listener = new WebInspector.EventListener(this, true); + + let managerResult = new Promise(function(resolve, reject) { + listener.connect(WebInspector.debuggerManager, WebInspector.DebuggerManager.Event.Paused, resolve); + }); + + let promises = []; + for (let [target, targetData] of this._targetDebuggerDataMap) + promises.push(targetData.pauseIfNeeded()); + + return Promise.all([managerResult, ...promises]); + } + + resume() + { + if (!this.paused) + return Promise.resolve(); + + let listener = new WebInspector.EventListener(this, true); + + let managerResult = new Promise(function(resolve, reject) { + listener.connect(WebInspector.debuggerManager, WebInspector.DebuggerManager.Event.Resumed, resolve); + }); + + let promises = []; + for (let [target, targetData] of this._targetDebuggerDataMap) + promises.push(targetData.resumeIfNeeded()); + + return Promise.all([managerResult, ...promises]); + } + + stepOver() + { + if (!this.paused) + return Promise.reject(new Error("Cannot step over because debugger is not paused.")); + + let listener = new WebInspector.EventListener(this, true); + + let managerResult = new Promise(function(resolve, reject) { + listener.connect(WebInspector.debuggerManager, WebInspector.DebuggerManager.Event.ActiveCallFrameDidChange, resolve); + }); + + let protocolResult = this._activeCallFrame.target.DebuggerAgent.stepOver() + .catch(function(error) { + listener.disconnect(); + console.error("DebuggerManager.stepOver failed: ", error); + throw error; + }); + + return Promise.all([managerResult, protocolResult]); + } + + stepInto() + { + if (!this.paused) + return Promise.reject(new Error("Cannot step into because debugger is not paused.")); + + let listener = new WebInspector.EventListener(this, true); + + let managerResult = new Promise(function(resolve, reject) { + listener.connect(WebInspector.debuggerManager, WebInspector.DebuggerManager.Event.ActiveCallFrameDidChange, resolve); + }); + + let protocolResult = this._activeCallFrame.target.DebuggerAgent.stepInto() + .catch(function(error) { + listener.disconnect(); + console.error("DebuggerManager.stepInto failed: ", error); + throw error; + }); + + return Promise.all([managerResult, protocolResult]); + } + + stepOut() + { + if (!this.paused) + return Promise.reject(new Error("Cannot step out because debugger is not paused.")); + + let listener = new WebInspector.EventListener(this, true); + + let managerResult = new Promise(function(resolve, reject) { + listener.connect(WebInspector.debuggerManager, WebInspector.DebuggerManager.Event.ActiveCallFrameDidChange, resolve); + }); + + let protocolResult = this._activeCallFrame.target.DebuggerAgent.stepOut() + .catch(function(error) { + listener.disconnect(); + console.error("DebuggerManager.stepOut failed: ", error); + throw error; + }); + + return Promise.all([managerResult, protocolResult]); + } + + continueUntilNextRunLoop(target) + { + return this.dataForTarget(target).continueUntilNextRunLoop(); + } + + continueToLocation(script, lineNumber, columnNumber) + { + return script.target.DebuggerAgent.continueToLocation({scriptId: script.id, lineNumber, columnNumber}); + } + + addBreakpoint(breakpoint, shouldSpeculativelyResolve) + { + console.assert(breakpoint instanceof WebInspector.Breakpoint); + if (!breakpoint) + return; + + if (breakpoint.contentIdentifier) { + let contentIdentifierBreakpoints = this._breakpointContentIdentifierMap.get(breakpoint.contentIdentifier); + if (!contentIdentifierBreakpoints) { + contentIdentifierBreakpoints = []; + this._breakpointContentIdentifierMap.set(breakpoint.contentIdentifier, contentIdentifierBreakpoints); + } + contentIdentifierBreakpoints.push(breakpoint); + } + + if (breakpoint.scriptIdentifier) { + let scriptIdentifierBreakpoints = this._breakpointScriptIdentifierMap.get(breakpoint.scriptIdentifier); + if (!scriptIdentifierBreakpoints) { + scriptIdentifierBreakpoints = []; + this._breakpointScriptIdentifierMap.set(breakpoint.scriptIdentifier, scriptIdentifierBreakpoints); + } + scriptIdentifierBreakpoints.push(breakpoint); + } + + this._breakpoints.push(breakpoint); + + if (!breakpoint.disabled) { + const specificTarget = undefined; + this._setBreakpoint(breakpoint, specificTarget, () => { + if (shouldSpeculativelyResolve) + breakpoint.resolved = true; + }); + } + + this._saveBreakpoints(); + + this.dispatchEventToListeners(WebInspector.DebuggerManager.Event.BreakpointAdded, {breakpoint}); + } + + removeBreakpoint(breakpoint) + { + console.assert(breakpoint instanceof WebInspector.Breakpoint); + if (!breakpoint) + return; + + console.assert(this.isBreakpointRemovable(breakpoint)); + if (!this.isBreakpointRemovable(breakpoint)) + return; + + this._breakpoints.remove(breakpoint); + + if (breakpoint.identifier) + this._removeBreakpoint(breakpoint); + + if (breakpoint.contentIdentifier) { + let contentIdentifierBreakpoints = this._breakpointContentIdentifierMap.get(breakpoint.contentIdentifier); + if (contentIdentifierBreakpoints) { + contentIdentifierBreakpoints.remove(breakpoint); + if (!contentIdentifierBreakpoints.length) + this._breakpointContentIdentifierMap.delete(breakpoint.contentIdentifier); + } + } + + if (breakpoint.scriptIdentifier) { + let scriptIdentifierBreakpoints = this._breakpointScriptIdentifierMap.get(breakpoint.scriptIdentifier); + if (scriptIdentifierBreakpoints) { + scriptIdentifierBreakpoints.remove(breakpoint); + if (!scriptIdentifierBreakpoints.length) + this._breakpointScriptIdentifierMap.delete(breakpoint.scriptIdentifier); + } + } + + // Disable the breakpoint first, so removing actions doesn't re-add the breakpoint. + breakpoint.disabled = true; + breakpoint.clearActions(); + + this._saveBreakpoints(); + + this.dispatchEventToListeners(WebInspector.DebuggerManager.Event.BreakpointRemoved, {breakpoint}); + } + + nextBreakpointActionIdentifier() + { + return this._nextBreakpointActionIdentifier++; + } + + initializeTarget(target) + { + let DebuggerAgent = target.DebuggerAgent; + let targetData = this.dataForTarget(target); + + // Initialize global state. + DebuggerAgent.enable(); + DebuggerAgent.setBreakpointsActive(this._breakpointsEnabledSetting.value); + DebuggerAgent.setPauseOnAssertions(this._assertionsBreakpointEnabledSetting.value); + DebuggerAgent.setPauseOnExceptions(this._breakOnExceptionsState); + DebuggerAgent.setAsyncStackTraceDepth(this._asyncStackTraceDepthSetting.value); + + if (this.paused) + targetData.pauseIfNeeded(); + + // Initialize breakpoints. + this._restoringBreakpoints = true; + for (let breakpoint of this._breakpoints) { + if (breakpoint.disabled) + continue; + if (!breakpoint.contentIdentifier) + continue; + this._setBreakpoint(breakpoint, target); + } + this._restoringBreakpoints = false; + } + + // Protected (Called from WebInspector.DebuggerObserver) + + breakpointResolved(target, breakpointIdentifier, location) + { + // Called from WebInspector.DebuggerObserver. + + let breakpoint = this._breakpointIdMap.get(breakpointIdentifier); + console.assert(breakpoint); + if (!breakpoint) + return; + + console.assert(breakpoint.identifier === breakpointIdentifier); + + if (!breakpoint.sourceCodeLocation.sourceCode) { + let sourceCodeLocation = this._sourceCodeLocationFromPayload(target, location); + breakpoint.sourceCodeLocation.sourceCode = sourceCodeLocation.sourceCode; + } + + breakpoint.resolved = true; + } + + reset() + { + // Called from WebInspector.DebuggerObserver. + + let wasPaused = this.paused; + + WebInspector.Script.resetUniqueDisplayNameNumbers(); + + this._internalWebKitScripts = []; + this._targetDebuggerDataMap.clear(); + + this._ignoreBreakpointDisplayLocationDidChangeEvent = true; + + // Mark all the breakpoints as unresolved. They will be reported as resolved when + // breakpointResolved is called as the page loads. + for (let breakpoint of this._breakpoints) { + breakpoint.resolved = false; + if (breakpoint.sourceCodeLocation.sourceCode) + breakpoint.sourceCodeLocation.sourceCode = null; + } + + this._ignoreBreakpointDisplayLocationDidChangeEvent = false; + + this.dispatchEventToListeners(WebInspector.DebuggerManager.Event.ScriptsCleared); + + if (wasPaused) + this.dispatchEventToListeners(WebInspector.DebuggerManager.Event.Resumed); + } + + debuggerDidPause(target, callFramesPayload, reason, data, asyncStackTracePayload) + { + // Called from WebInspector.DebuggerObserver. + + if (this._delayedResumeTimeout) { + clearTimeout(this._delayedResumeTimeout); + this._delayedResumeTimeout = undefined; + } + + let wasPaused = this.paused; + let targetData = this._targetDebuggerDataMap.get(target); + + let callFrames = []; + let pauseReason = this._pauseReasonFromPayload(reason); + let pauseData = data || null; + + for (var i = 0; i < callFramesPayload.length; ++i) { + var callFramePayload = callFramesPayload[i]; + var sourceCodeLocation = this._sourceCodeLocationFromPayload(target, callFramePayload.location); + // FIXME: There may be useful call frames without a source code location (native callframes), should we include them? + if (!sourceCodeLocation) + continue; + if (!sourceCodeLocation.sourceCode) + continue; + + // Exclude the case where the call frame is in the inspector code. + if (!WebInspector.isDebugUIEnabled() && isWebKitInternalScript(sourceCodeLocation.sourceCode.sourceURL)) + continue; + + let scopeChain = this._scopeChainFromPayload(target, callFramePayload.scopeChain); + let callFrame = WebInspector.CallFrame.fromDebuggerPayload(target, callFramePayload, scopeChain, sourceCodeLocation); + callFrames.push(callFrame); + } + + let activeCallFrame = callFrames[0]; + + if (!activeCallFrame) { + // FIXME: This may not be safe for multiple threads/targets. + // This indicates we were pausing in internal scripts only (Injected Scripts). + // Just resume and skip past this pause. We should be fixing the backend to + // not send such pauses. + if (wasPaused) + target.DebuggerAgent.continueUntilNextRunLoop(); + else + target.DebuggerAgent.resume(); + this._didResumeInternal(target); + return; + } + + let asyncStackTrace = WebInspector.StackTrace.fromPayload(target, asyncStackTracePayload); + targetData.updateForPause(callFrames, pauseReason, pauseData, asyncStackTrace); + + // Pause other targets because at least one target has paused. + // FIXME: Should this be done on the backend? + for (let [otherTarget, otherTargetData] of this._targetDebuggerDataMap) + otherTargetData.pauseIfNeeded(); + + let activeCallFrameDidChange = this._activeCallFrame && this._activeCallFrame.target === target; + if (activeCallFrameDidChange) + this._activeCallFrame = activeCallFrame; + else if (!wasPaused) { + this._activeCallFrame = activeCallFrame; + activeCallFrameDidChange = true; + } + + if (!wasPaused) + this.dispatchEventToListeners(WebInspector.DebuggerManager.Event.Paused); + + this.dispatchEventToListeners(WebInspector.DebuggerManager.Event.CallFramesDidChange, {target}); + + if (activeCallFrameDidChange) + this.dispatchEventToListeners(WebInspector.DebuggerManager.Event.ActiveCallFrameDidChange); + } + + debuggerDidResume(target) + { + // Called from WebInspector.DebuggerObserver. + + // COMPATIBILITY (iOS 10): Debugger.resumed event was ambiguous. When stepping + // we would receive a Debugger.resumed and we would not know if it really meant + // the backend resumed or would pause again due to a step. Legacy backends wait + // 50ms, and treat it as a real resume if we haven't paused in that time frame. + // This delay ensures the user interface does not flash between brief steps + // or successive breakpoints. + if (!DebuggerAgent.setPauseOnAssertions) { + this._delayedResumeTimeout = setTimeout(this._didResumeInternal.bind(this, target), 50); + return; + } + + this._didResumeInternal(target); + } + + playBreakpointActionSound(breakpointActionIdentifier) + { + // Called from WebInspector.DebuggerObserver. + + InspectorFrontendHost.beep(); + } + + scriptDidParse(target, scriptIdentifier, url, startLine, startColumn, endLine, endColumn, isModule, isContentScript, sourceURL, sourceMapURL) + { + // Called from WebInspector.DebuggerObserver. + + // Don't add the script again if it is already known. + let targetData = this.dataForTarget(target); + let existingScript = targetData.scriptForIdentifier(scriptIdentifier); + if (existingScript) { + console.assert(existingScript.url === (url || null)); + console.assert(existingScript.range.startLine === startLine); + console.assert(existingScript.range.startColumn === startColumn); + console.assert(existingScript.range.endLine === endLine); + console.assert(existingScript.range.endColumn === endColumn); + return; + } + + if (!WebInspector.isDebugUIEnabled() && isWebKitInternalScript(sourceURL)) + return; + + let range = new WebInspector.TextRange(startLine, startColumn, endLine, endColumn); + let sourceType = isModule ? WebInspector.Script.SourceType.Module : WebInspector.Script.SourceType.Program; + let script = new WebInspector.Script(target, scriptIdentifier, range, url, sourceType, isContentScript, sourceURL, sourceMapURL); + + targetData.addScript(script); + + if (target !== WebInspector.mainTarget && !target.mainResource) { + // FIXME: Web Inspector: WorkerTarget's mainResource should be a Resource not a Script + // We make the main resource of a WorkerTarget the Script instead of the Resource + // because the frontend may not be informed of the Resource. We should guarantee + // the frontend is informed of the Resource. + if (script.url === target.name) { + target.mainResource = script; + if (script.resource) + target.resourceCollection.remove(script.resource); + } + } + + if (isWebKitInternalScript(script.sourceURL)) { + this._internalWebKitScripts.push(script); + if (!WebInspector.isDebugUIEnabled()) + return; + } + + // Console expressions are not added to the UI by default. + if (isWebInspectorConsoleEvaluationScript(script.sourceURL)) + return; + + this.dispatchEventToListeners(WebInspector.DebuggerManager.Event.ScriptAdded, {script}); + + if (target !== WebInspector.mainTarget && !script.isMainResource() && !script.resource) + target.addScript(script); + } + + // Private + + _sourceCodeLocationFromPayload(target, payload) + { + let targetData = this.dataForTarget(target); + let script = targetData.scriptForIdentifier(payload.scriptId); + if (!script) + return null; + + return script.createSourceCodeLocation(payload.lineNumber, payload.columnNumber); + } + + _scopeChainFromPayload(target, payload) + { + let scopeChain = []; + for (let i = 0; i < payload.length; ++i) + scopeChain.push(this._scopeChainNodeFromPayload(target, payload[i])); + return scopeChain; + } + + _scopeChainNodeFromPayload(target, payload) + { + var type = null; + switch (payload.type) { + case DebuggerAgent.ScopeType.Global: + type = WebInspector.ScopeChainNode.Type.Global; + break; + case DebuggerAgent.ScopeType.With: + type = WebInspector.ScopeChainNode.Type.With; + break; + case DebuggerAgent.ScopeType.Closure: + type = WebInspector.ScopeChainNode.Type.Closure; + break; + case DebuggerAgent.ScopeType.Catch: + type = WebInspector.ScopeChainNode.Type.Catch; + break; + case DebuggerAgent.ScopeType.FunctionName: + type = WebInspector.ScopeChainNode.Type.FunctionName; + break; + case DebuggerAgent.ScopeType.NestedLexical: + type = WebInspector.ScopeChainNode.Type.Block; + break; + case DebuggerAgent.ScopeType.GlobalLexicalEnvironment: + type = WebInspector.ScopeChainNode.Type.GlobalLexicalEnvironment; + break; + + // COMPATIBILITY (iOS 9): Debugger.ScopeType.Local used to be provided by the backend. + // Newer backends no longer send this enum value, it should be computed by the frontend. + // Map this to "Closure" type. The frontend can recalculate this when needed. + case DebuggerAgent.ScopeType.Local: + type = WebInspector.ScopeChainNode.Type.Closure; + break; + + default: + console.error("Unknown type: " + payload.type); + } + + let object = WebInspector.RemoteObject.fromPayload(payload.object, target); + return new WebInspector.ScopeChainNode(type, [object], payload.name, payload.location, payload.empty); + } + + _pauseReasonFromPayload(payload) + { + // FIXME: Handle other backend pause reasons. + switch (payload) { + case DebuggerAgent.PausedReason.Assert: + return WebInspector.DebuggerManager.PauseReason.Assertion; + case DebuggerAgent.PausedReason.Breakpoint: + return WebInspector.DebuggerManager.PauseReason.Breakpoint; + case DebuggerAgent.PausedReason.CSPViolation: + return WebInspector.DebuggerManager.PauseReason.CSPViolation; + case DebuggerAgent.PausedReason.DebuggerStatement: + return WebInspector.DebuggerManager.PauseReason.DebuggerStatement; + case DebuggerAgent.PausedReason.Exception: + return WebInspector.DebuggerManager.PauseReason.Exception; + case DebuggerAgent.PausedReason.PauseOnNextStatement: + return WebInspector.DebuggerManager.PauseReason.PauseOnNextStatement; + default: + return WebInspector.DebuggerManager.PauseReason.Other; + } + } + + _debuggerBreakpointActionType(type) + { + switch (type) { + case WebInspector.BreakpointAction.Type.Log: + return DebuggerAgent.BreakpointActionType.Log; + case WebInspector.BreakpointAction.Type.Evaluate: + return DebuggerAgent.BreakpointActionType.Evaluate; + case WebInspector.BreakpointAction.Type.Sound: + return DebuggerAgent.BreakpointActionType.Sound; + case WebInspector.BreakpointAction.Type.Probe: + return DebuggerAgent.BreakpointActionType.Probe; + default: + console.assert(false); + return DebuggerAgent.BreakpointActionType.Log; + } + } + + _debuggerBreakpointOptions(breakpoint) + { + const templatePlaceholderRegex = /\$\{.*?\}/; + + let options = breakpoint.options; + let invalidActions = []; + + for (let action of options.actions) { + if (action.type !== WebInspector.BreakpointAction.Type.Log) + continue; + + if (!templatePlaceholderRegex.test(action.data)) + continue; + + let lexer = new WebInspector.BreakpointLogMessageLexer; + let tokens = lexer.tokenize(action.data); + if (!tokens) { + invalidActions.push(action); + continue; + } + + let templateLiteral = tokens.reduce((text, token) => { + if (token.type === WebInspector.BreakpointLogMessageLexer.TokenType.PlainText) + return text + token.data.escapeCharacters("`\\"); + if (token.type === WebInspector.BreakpointLogMessageLexer.TokenType.Expression) + return text + "${" + token.data + "}"; + return text; + }, ""); + + action.data = "console.log(`" + templateLiteral + "`)"; + action.type = WebInspector.BreakpointAction.Type.Evaluate; + } + + const onlyFirst = true; + for (let invalidAction of invalidActions) + options.actions.remove(invalidAction, onlyFirst); + + return options; + } + + _setBreakpoint(breakpoint, specificTarget, callback) + { + console.assert(!breakpoint.disabled); + + if (breakpoint.disabled) + return; + + if (!this._restoringBreakpoints && !this.breakpointsDisabledTemporarily) { + // Enable breakpoints since a breakpoint is being set. This eliminates + // a multi-step process for the user that can be confusing. + this.breakpointsEnabled = true; + } + + function didSetBreakpoint(target, error, breakpointIdentifier, locations) + { + if (error) + return; + + this._breakpointIdMap.set(breakpointIdentifier, breakpoint); + + breakpoint.identifier = breakpointIdentifier; + + // Debugger.setBreakpoint returns a single location. + if (!(locations instanceof Array)) + locations = [locations]; + + for (let location of locations) + this.breakpointResolved(target, breakpointIdentifier, location); + + if (typeof callback === "function") + callback(); + } + + // The breakpoint will be resolved again by calling DebuggerAgent, so mark it as unresolved. + // If something goes wrong it will stay unresolved and show up as such in the user interface. + // When setting for a new target, don't change the resolved target. + if (!specificTarget) + breakpoint.resolved = false; + + // Convert BreakpointAction types to DebuggerAgent protocol types. + // NOTE: Breakpoint.options returns new objects each time, so it is safe to modify. + // COMPATIBILITY (iOS 7): Debugger.BreakpointActionType did not exist yet. + let options; + if (DebuggerAgent.BreakpointActionType) { + options = this._debuggerBreakpointOptions(breakpoint); + if (options.actions.length) { + for (let action of options.actions) + action.type = this._debuggerBreakpointActionType(action.type); + } + } + + // COMPATIBILITY (iOS 7): iOS 7 and earlier, DebuggerAgent.setBreakpoint* took a "condition" string argument. + // This has been replaced with an "options" BreakpointOptions object. + if (breakpoint.contentIdentifier) { + let targets = specificTarget ? [specificTarget] : WebInspector.targets; + for (let target of targets) { + target.DebuggerAgent.setBreakpointByUrl.invoke({ + lineNumber: breakpoint.sourceCodeLocation.lineNumber, + url: breakpoint.contentIdentifier, + urlRegex: undefined, + columnNumber: breakpoint.sourceCodeLocation.columnNumber, + condition: breakpoint.condition, + options + }, didSetBreakpoint.bind(this, target), target.DebuggerAgent); + } + } else if (breakpoint.scriptIdentifier) { + let target = breakpoint.target; + target.DebuggerAgent.setBreakpoint.invoke({ + location: {scriptId: breakpoint.scriptIdentifier, lineNumber: breakpoint.sourceCodeLocation.lineNumber, columnNumber: breakpoint.sourceCodeLocation.columnNumber}, + condition: breakpoint.condition, + options + }, didSetBreakpoint.bind(this, target), target.DebuggerAgent); + } + } + + _removeBreakpoint(breakpoint, callback) + { + if (!breakpoint.identifier) + return; + + function didRemoveBreakpoint(error) + { + if (error) + console.error(error); + + this._breakpointIdMap.delete(breakpoint.identifier); + + breakpoint.identifier = null; + + // Don't reset resolved here since we want to keep disabled breakpoints looking like they + // are resolved in the user interface. They will get marked as unresolved in reset. + + if (typeof callback === "function") + callback(); + } + + if (breakpoint.contentIdentifier) { + for (let target of WebInspector.targets) + target.DebuggerAgent.removeBreakpoint(breakpoint.identifier, didRemoveBreakpoint.bind(this)); + } else if (breakpoint.scriptIdentifier) { + let target = breakpoint.target; + target.DebuggerAgent.removeBreakpoint(breakpoint.identifier, didRemoveBreakpoint.bind(this)); + } + } + + _breakpointDisplayLocationDidChange(event) + { + if (this._ignoreBreakpointDisplayLocationDidChangeEvent) + return; + + let breakpoint = event.target; + if (!breakpoint.identifier || breakpoint.disabled) + return; + + // Remove the breakpoint with its old id. + this._removeBreakpoint(breakpoint, breakpointRemoved.bind(this)); + + function breakpointRemoved() + { + // Add the breakpoint at its new lineNumber and get a new id. + this._setBreakpoint(breakpoint); + + this.dispatchEventToListeners(WebInspector.DebuggerManager.Event.BreakpointMoved, {breakpoint}); + } + } + + _breakpointDisabledStateDidChange(event) + { + this._saveBreakpoints(); + + let breakpoint = event.target; + if (breakpoint === this._allExceptionsBreakpoint) { + if (!breakpoint.disabled && !this.breakpointsDisabledTemporarily) + this.breakpointsEnabled = true; + this._allExceptionsBreakpointEnabledSetting.value = !breakpoint.disabled; + this._updateBreakOnExceptionsState(); + for (let target of WebInspector.targets) + target.DebuggerAgent.setPauseOnExceptions(this._breakOnExceptionsState); + return; + } + + if (breakpoint === this._allUncaughtExceptionsBreakpoint) { + if (!breakpoint.disabled && !this.breakpointsDisabledTemporarily) + this.breakpointsEnabled = true; + this._allUncaughtExceptionsBreakpointEnabledSetting.value = !breakpoint.disabled; + this._updateBreakOnExceptionsState(); + for (let target of WebInspector.targets) + target.DebuggerAgent.setPauseOnExceptions(this._breakOnExceptionsState); + return; + } + + if (breakpoint === this._assertionsBreakpoint) { + if (!breakpoint.disabled && !this.breakpointsDisabledTemporarily) + this.breakpointsEnabled = true; + this._assertionsBreakpointEnabledSetting.value = !breakpoint.disabled; + for (let target of WebInspector.targets) + target.DebuggerAgent.setPauseOnAssertions(this._assertionsBreakpointEnabledSetting.value); + return; + } + + if (breakpoint.disabled) + this._removeBreakpoint(breakpoint); + else + this._setBreakpoint(breakpoint); + } + + _breakpointEditablePropertyDidChange(event) + { + this._saveBreakpoints(); + + let breakpoint = event.target; + if (breakpoint.disabled) + return; + + console.assert(this.isBreakpointEditable(breakpoint)); + if (!this.isBreakpointEditable(breakpoint)) + return; + + // Remove the breakpoint with its old id. + this._removeBreakpoint(breakpoint, breakpointRemoved.bind(this)); + + function breakpointRemoved() + { + // Add the breakpoint with its new properties and get a new id. + this._setBreakpoint(breakpoint); + } + } + + _startDisablingBreakpointsTemporarily() + { + console.assert(!this.breakpointsDisabledTemporarily, "Already temporarily disabling breakpoints."); + if (this.breakpointsDisabledTemporarily) + return; + + this._temporarilyDisabledBreakpointsRestoreSetting.value = this._breakpointsEnabledSetting.value; + + this.breakpointsEnabled = false; + } + + _stopDisablingBreakpointsTemporarily() + { + console.assert(this.breakpointsDisabledTemporarily, "Was not temporarily disabling breakpoints."); + if (!this.breakpointsDisabledTemporarily) + return; + + let restoreState = this._temporarilyDisabledBreakpointsRestoreSetting.value; + this._temporarilyDisabledBreakpointsRestoreSetting.value = null; + + this.breakpointsEnabled = restoreState; + } + + _timelineCapturingWillStart(event) + { + this._startDisablingBreakpointsTemporarily(); + + if (this.paused) + this.resume(); + } + + _timelineCapturingStopped(event) + { + this._stopDisablingBreakpointsTemporarily(); + } + + _targetRemoved(event) + { + let wasPaused = this.paused; + + this._targetDebuggerDataMap.delete(event.data.target); + + if (!this.paused && wasPaused) + this.dispatchEventToListeners(WebInspector.DebuggerManager.Event.Resumed); + } + + _mainResourceDidChange(event) + { + if (!event.target.isMainFrame()) + return; + + this._didResumeInternal(WebInspector.mainTarget); + } + + _didResumeInternal(target) + { + if (!this.paused) + return; + + if (this._delayedResumeTimeout) { + clearTimeout(this._delayedResumeTimeout); + this._delayedResumeTimeout = undefined; + } + + let activeCallFrameDidChange = false; + if (this._activeCallFrame && this._activeCallFrame.target === target) { + this._activeCallFrame = null; + activeCallFrameDidChange = true; + } + + this.dataForTarget(target).updateForResume(); + + if (!this.paused) + this.dispatchEventToListeners(WebInspector.DebuggerManager.Event.Resumed); + + this.dispatchEventToListeners(WebInspector.DebuggerManager.Event.CallFramesDidChange, {target}); + + if (activeCallFrameDidChange) + this.dispatchEventToListeners(WebInspector.DebuggerManager.Event.ActiveCallFrameDidChange); + } + + _updateBreakOnExceptionsState() + { + let state = "none"; + + if (this._breakpointsEnabledSetting.value) { + if (!this._allExceptionsBreakpoint.disabled) + state = "all"; + else if (!this._allUncaughtExceptionsBreakpoint.disabled) + state = "uncaught"; + } + + this._breakOnExceptionsState = state; + + switch (state) { + case "all": + // Mark the uncaught breakpoint as unresolved since "all" includes "uncaught". + // That way it is clear in the user interface that the breakpoint is ignored. + this._allUncaughtExceptionsBreakpoint.resolved = false; + break; + case "uncaught": + case "none": + // Mark the uncaught breakpoint as resolved again. + this._allUncaughtExceptionsBreakpoint.resolved = true; + break; + } + } + + _saveBreakpoints() + { + if (this._restoringBreakpoints) + return; + + let breakpointsToSave = this._breakpoints.filter((breakpoint) => !!breakpoint.contentIdentifier); + let serializedBreakpoints = breakpointsToSave.map((breakpoint) => breakpoint.info); + this._breakpointsSetting.value = serializedBreakpoints; + } + + _associateBreakpointsWithSourceCode(breakpoints, sourceCode) + { + this._ignoreBreakpointDisplayLocationDidChangeEvent = true; + + for (let breakpoint of breakpoints) { + if (!breakpoint.sourceCodeLocation.sourceCode) + breakpoint.sourceCodeLocation.sourceCode = sourceCode; + // SourceCodes can be unequal if the SourceCodeLocation is associated with a Script and we are looking at the Resource. + console.assert(breakpoint.sourceCodeLocation.sourceCode === sourceCode || breakpoint.sourceCodeLocation.sourceCode.contentIdentifier === sourceCode.contentIdentifier); + } + + this._ignoreBreakpointDisplayLocationDidChangeEvent = false; + } + + _debugUIEnabledDidChange() + { + let eventType = WebInspector.isDebugUIEnabled() ? WebInspector.DebuggerManager.Event.ScriptAdded : WebInspector.DebuggerManager.Event.ScriptRemoved; + for (let script of this._internalWebKitScripts) + this.dispatchEventToListeners(eventType, {script}); + } +}; + +WebInspector.DebuggerManager.Event = { + BreakpointAdded: "debugger-manager-breakpoint-added", + BreakpointRemoved: "debugger-manager-breakpoint-removed", + BreakpointMoved: "debugger-manager-breakpoint-moved", + WaitingToPause: "debugger-manager-waiting-to-pause", + Paused: "debugger-manager-paused", + Resumed: "debugger-manager-resumed", + CallFramesDidChange: "debugger-manager-call-frames-did-change", + ActiveCallFrameDidChange: "debugger-manager-active-call-frame-did-change", + ScriptAdded: "debugger-manager-script-added", + ScriptRemoved: "debugger-manager-script-removed", + ScriptsCleared: "debugger-manager-scripts-cleared", + BreakpointsEnabledDidChange: "debugger-manager-breakpoints-enabled-did-change" +}; + +WebInspector.DebuggerManager.PauseReason = { + Assertion: "assertion", + Breakpoint: "breakpoint", + CSPViolation: "CSP-violation", + DebuggerStatement: "debugger-statement", + Exception: "exception", + PauseOnNextStatement: "pause-on-next-statement", + Other: "other", +}; diff --git a/Source/WebInspectorUI/UserInterface/Controllers/DragToAdjustController.js b/Source/WebInspectorUI/UserInterface/Controllers/DragToAdjustController.js new file mode 100644 index 000000000..4ad3a2ab3 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/DragToAdjustController.js @@ -0,0 +1,238 @@ +/* + * Copyright (C) 2014 Antoine Quint + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.DragToAdjustController = class DragToAdjustController +{ + constructor(delegate) + { + this._delegate = delegate; + + this._element = null; + this._active = false; + this._enabled = false; + this._dragging = false; + this._tracksMouseClickAndDrag = false; + } + + // Public + + get element() + { + return this._element; + } + + set element(element) + { + this._element = element; + } + + get enabled() + { + return this._enabled; + } + + set enabled(enabled) + { + if (this._enabled === enabled) + return; + + if (enabled) { + this._element.addEventListener("mouseenter", this); + this._element.addEventListener("mouseleave", this); + } else { + this._element.removeEventListener("mouseenter", this); + this._element.removeEventListener("mouseleave", this); + } + } + + get active() + { + return this._active; + } + + set active(active) + { + if (!this._element) + return; + + if (this._active === active) + return; + + if (active) { + WebInspector.notifications.addEventListener(WebInspector.Notification.GlobalModifierKeysDidChange, this._modifiersDidChange, this); + this._element.addEventListener("mousemove", this); + } else { + WebInspector.notifications.removeEventListener(WebInspector.Notification.GlobalModifierKeysDidChange, this._modifiersDidChange, this); + this._element.removeEventListener("mousemove", this); + this._setTracksMouseClickAndDrag(false); + } + + this._active = active; + + if (this._delegate && typeof this._delegate.dragToAdjustControllerActiveStateChanged === "function") + this._delegate.dragToAdjustControllerActiveStateChanged(this); + } + + reset() + { + this._setTracksMouseClickAndDrag(false); + this._element.classList.remove(WebInspector.DragToAdjustController.StyleClassName); + + if (this._delegate && typeof this._delegate.dragToAdjustControllerDidReset === "function") + this._delegate.dragToAdjustControllerDidReset(this); + } + + // Protected + + handleEvent(event) + { + switch (event.type) { + case "mouseenter": + if (!this._dragging) { + if (this._delegate && typeof this._delegate.dragToAdjustControllerCanBeActivated === "function") + this.active = this._delegate.dragToAdjustControllerCanBeActivated(this); + else + this.active = true; + } + break; + case "mouseleave": + if (!this._dragging) + this.active = false; + break; + case "mousemove": + if (this._dragging) + this._mouseWasDragged(event); + else + this._mouseMoved(event); + break; + case "mousedown": + this._mouseWasPressed(event); + break; + case "mouseup": + this._mouseWasReleased(event); + break; + case "contextmenu": + event.preventDefault(); + break; + } + } + + // Private + + _setDragging(dragging) + { + if (this._dragging === dragging) + return; + + console.assert(window.event); + if (dragging) + WebInspector.elementDragStart(this._element, this, this, window.event, "col-resize", window); + else + WebInspector.elementDragEnd(window.event); + + this._dragging = dragging; + } + + _setTracksMouseClickAndDrag(tracksMouseClickAndDrag) + { + if (this._tracksMouseClickAndDrag === tracksMouseClickAndDrag) + return; + + if (tracksMouseClickAndDrag) { + this._element.classList.add(WebInspector.DragToAdjustController.StyleClassName); + window.addEventListener("mousedown", this, true); + window.addEventListener("contextmenu", this, true); + } else { + this._element.classList.remove(WebInspector.DragToAdjustController.StyleClassName); + window.removeEventListener("mousedown", this, true); + window.removeEventListener("contextmenu", this, true); + this._setDragging(false); + } + + this._tracksMouseClickAndDrag = tracksMouseClickAndDrag; + } + + _modifiersDidChange(event) + { + var canBeAdjusted = WebInspector.modifierKeys.altKey; + if (canBeAdjusted && this._delegate && typeof this._delegate.dragToAdjustControllerCanBeAdjusted === "function") + canBeAdjusted = this._delegate.dragToAdjustControllerCanBeAdjusted(this); + + this._setTracksMouseClickAndDrag(canBeAdjusted); + } + + _mouseMoved(event) + { + var canBeAdjusted = event.altKey; + if (canBeAdjusted && this._delegate && typeof this._delegate.dragToAdjustControllerCanAdjustObjectAtPoint === "function") + canBeAdjusted = this._delegate.dragToAdjustControllerCanAdjustObjectAtPoint(this, WebInspector.Point.fromEvent(event)); + + this._setTracksMouseClickAndDrag(canBeAdjusted); + } + + _mouseWasPressed(event) + { + this._lastX = event.screenX; + + this._setDragging(true); + + event.preventDefault(); + event.stopPropagation(); + } + + _mouseWasDragged(event) + { + var x = event.screenX; + var amount = x - this._lastX; + + if (Math.abs(amount) < 1) + return; + + this._lastX = x; + + if (event.ctrlKey) + amount /= 10; + else if (event.shiftKey) + amount *= 10; + + if (this._delegate && typeof this._delegate.dragToAdjustControllerWasAdjustedByAmount === "function") + this._delegate.dragToAdjustControllerWasAdjustedByAmount(this, amount); + + event.preventDefault(); + event.stopPropagation(); + } + + _mouseWasReleased(event) + { + this._setDragging(false); + + event.preventDefault(); + event.stopPropagation(); + + this.reset(); + } +}; + +WebInspector.DragToAdjustController.StyleClassName = "drag-to-adjust"; diff --git a/Source/WebInspectorUI/UserInterface/Controllers/Formatter.js b/Source/WebInspectorUI/UserInterface/Controllers/Formatter.js new file mode 100644 index 000000000..2a1652733 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/Formatter.js @@ -0,0 +1,167 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.Formatter = class Formatter +{ + constructor(codeMirror, builder) + { + console.assert(codeMirror); + console.assert(builder); + + this._codeMirror = codeMirror; + this._builder = builder; + + this._lastToken = null; + this._lastContent = ""; + } + + // Public + + format(from, to) + { + console.assert(this._builder.originalContent === null); + if (this._builder.originalContent !== null) + return; + + var outerMode = this._codeMirror.getMode(); + var content = this._codeMirror.getRange(from, to); + var state = CodeMirror.copyState(outerMode, this._codeMirror.getTokenAt(from).state); + this._builder.setOriginalContent(content); + + var lineOffset = 0; + var lines = content.split("\n"); + for (var i = 0; i < lines.length; ++i) { + var line = lines[i]; + var startOfNewLine = true; + var firstTokenOnLine = true; + var stream = new CodeMirror.StringStream(line); + while (!stream.eol()) { + var innerMode = CodeMirror.innerMode(outerMode, state); + var token = outerMode.token(stream, state); + var isWhiteSpace = token === null && /^\s*$/.test(stream.current()); + this._handleToken(innerMode.mode, token, state, stream, lineOffset + stream.start, isWhiteSpace, startOfNewLine, firstTokenOnLine); + stream.start = stream.pos; + startOfNewLine = false; + if (firstTokenOnLine && !isWhiteSpace) + firstTokenOnLine = false; + } + + if (firstTokenOnLine) + this._handleEmptyLine(); + + lineOffset += line.length + 1; // +1 for the "\n" removed in split. + this._handleLineEnding(lineOffset - 1); // -1 for the index of the "\n". + } + + this._builder.finish(); + } + + // Private + + _handleToken(mode, token, state, stream, originalPosition, isWhiteSpace, startOfNewLine, firstTokenOnLine) + { + // String content of the token. + var content = stream.current(); + + // Start of a new line. Insert a newline to be safe if code was not-ASI safe. These are collapsed. + if (startOfNewLine) + this._builder.appendNewline(); + + // Whitespace. Remove all spaces or collapse to a single space. + if (isWhiteSpace) { + this._builder.appendSpace(); + return; + } + + // Avoid some hooks for content in comments. + var isComment = token && /\bcomment\b/.test(token); + + if (mode.modifyStateForTokenPre) + mode.modifyStateForTokenPre(this._lastToken, this._lastContent, token, state, content, isComment); + + // Should we remove the last whitespace? + if (this._builder.lastTokenWasWhitespace && mode.removeLastWhitespace(this._lastToken, this._lastContent, token, state, content, isComment)) + this._builder.removeLastWhitespace(); + + // Should we remove the last newline? + if (this._builder.lastTokenWasNewline && mode.removeLastNewline(this._lastToken, this._lastContent, token, state, content, isComment, firstTokenOnLine)) + this._builder.removeLastNewline(); + + // Add whitespace after the last token? + if (!this._builder.lastTokenWasWhitespace && mode.shouldHaveSpaceAfterLastToken(this._lastToken, this._lastContent, token, state, content, isComment)) + this._builder.appendSpace(); + + // Add whitespace before this token? + if (!this._builder.lastTokenWasWhitespace && mode.shouldHaveSpaceBeforeToken(this._lastToken, this._lastContent, token, state, content, isComment)) + this._builder.appendSpace(); + + // Should we dedent before this token? + var dedents = mode.dedentsBeforeToken(this._lastToken, this._lastContent, token, state, content, isComment); + while (dedents-- > 0) + this._builder.dedent(); + + // Should we add a newline before this token? + if (mode.newlineBeforeToken(this._lastToken, this._lastContent, token, state, content, isComment)) + this._builder.appendNewline(); + + // Should we indent before this token? + if (mode.indentBeforeToken(this._lastToken, this._lastContent, token, state, content, isComment)) + this._builder.indent(); + + // Append token. + this._builder.appendToken(content, originalPosition); + + // Let the pretty printer update any state it keeps track of. + if (mode.modifyStateForTokenPost) + mode.modifyStateForTokenPost(this._lastToken, this._lastContent, token, state, content, isComment); + + // Should we indent or dedent after this token? + if (!isComment && mode.indentAfterToken(this._lastToken, this._lastContent, token, state, content, isComment)) + this._builder.indent(); + + // Should we add newlines after this token? + var newlines = mode.newlinesAfterToken(this._lastToken, this._lastContent, token, state, content, isComment); + if (newlines) + this._builder.appendMultipleNewlines(newlines); + + // Record this token as the last token. + this._lastToken = token; + this._lastContent = content; + } + + _handleEmptyLine() + { + // Preserve original whitespace only lines by adding a newline. + // However, don't do this if the builder just added multiple newlines. + if (!(this._builder.lastTokenWasNewline && this._builder.lastNewlineAppendWasMultiple)) + this._builder.appendNewline(true); + } + + _handleLineEnding(originalNewLinePosition) + { + // Record the original line ending. + this._builder.addOriginalLineEnding(originalNewLinePosition); + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Controllers/FormatterSourceMap.js b/Source/WebInspectorUI/UserInterface/Controllers/FormatterSourceMap.js new file mode 100644 index 000000000..e320ba1ce --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/FormatterSourceMap.js @@ -0,0 +1,97 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.FormatterSourceMap = class FormatterSourceMap extends WebInspector.Object +{ + constructor(originalLineEndings, formattedLineEndings, mapping) + { + super(); + + this._originalLineEndings = originalLineEndings; + this._formattedLineEndings = formattedLineEndings; + this._mapping = mapping; + } + + // Static + + static fromSourceMapData({originalLineEndings, formattedLineEndings, mapping}) + { + return new WebInspector.FormatterSourceMap(originalLineEndings, formattedLineEndings, mapping); + } + + // Public + + originalToFormatted(lineNumber, columnNumber) + { + var originalPosition = this._locationToPosition(this._originalLineEndings, lineNumber || 0, columnNumber || 0); + return this.originalPositionToFormatted(originalPosition); + } + + originalPositionToFormatted(originalPosition) + { + var formattedPosition = this._convertPosition(this._mapping.original, this._mapping.formatted, originalPosition); + return this._positionToLocation(this._formattedLineEndings, formattedPosition); + } + + formattedToOriginal(lineNumber, columnNumber) + { + var originalPosition = this.formattedToOriginalOffset(lineNumber, columnNumber); + return this._positionToLocation(this._originalLineEndings, originalPosition); + } + + formattedToOriginalOffset(lineNumber, columnNumber) + { + var formattedPosition = this._locationToPosition(this._formattedLineEndings, lineNumber || 0, columnNumber || 0); + var originalPosition = this._convertPosition(this._mapping.formatted, this._mapping.original, formattedPosition); + return originalPosition; + } + + // Private + + _locationToPosition(lineEndings, lineNumber, columnNumber) + { + var lineOffset = lineNumber ? lineEndings[lineNumber - 1] + 1 : 0; + return lineOffset + columnNumber; + } + + _positionToLocation(lineEndings, position) + { + var lineNumber = lineEndings.upperBound(position - 1); + if (!lineNumber) + var columnNumber = position; + else + var columnNumber = position - lineEndings[lineNumber - 1] - 1; + return {lineNumber, columnNumber}; + } + + _convertPosition(positions1, positions2, positionInPosition1) + { + var index = positions1.upperBound(positionInPosition1) - 1; + var convertedPosition = positions2[index] + positionInPosition1 - positions1[index]; + if (index < positions2.length - 1 && convertedPosition > positions2[index + 1]) + convertedPosition = positions2[index + 1]; + return convertedPosition; + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Controllers/FrameResourceManager.js b/Source/WebInspectorUI/UserInterface/Controllers/FrameResourceManager.js new file mode 100644 index 000000000..2fa0c936f --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/FrameResourceManager.js @@ -0,0 +1,640 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.FrameResourceManager = class FrameResourceManager extends WebInspector.Object +{ + constructor() + { + super(); + + if (window.PageAgent) + PageAgent.enable(); + if (window.NetworkAgent) + NetworkAgent.enable(); + + WebInspector.notifications.addEventListener(WebInspector.Notification.ExtraDomainsActivated, this._extraDomainsActivated, this); + + this.initialize(); + } + + // Public + + initialize() + { + var oldMainFrame = this._mainFrame; + + this._frameIdentifierMap = new Map; + this._mainFrame = null; + this._resourceRequestIdentifierMap = new Map; + this._orphanedResources = new Map; + + if (this._mainFrame !== oldMainFrame) + this._mainFrameDidChange(oldMainFrame); + + this._waitingForMainFrameResourceTreePayload = true; + if (window.PageAgent) + PageAgent.getResourceTree(this._processMainFrameResourceTreePayload.bind(this)); + } + + get mainFrame() + { + return this._mainFrame; + } + + get frames() + { + return [...this._frameIdentifierMap.values()]; + } + + frameForIdentifier(frameId) + { + return this._frameIdentifierMap.get(frameId) || null; + } + + frameDidNavigate(framePayload) + { + // Called from WebInspector.PageObserver. + + // Ignore this while waiting for the whole frame/resource tree. + if (this._waitingForMainFrameResourceTreePayload) + return; + + var frameWasLoadedInstantly = false; + + var frame = this.frameForIdentifier(framePayload.id); + if (!frame) { + // If the frame wasn't known before now, then the main resource was loaded instantly (about:blank, etc.) + // Make a new resource (which will make the frame). Mark will mark it as loaded at the end too since we + // don't expect any more events about the load finishing for these frames. + var frameResource = this._addNewResourceToFrameOrTarget(null, framePayload.id, framePayload.loaderId, framePayload.url, null, null, null, null, null, framePayload.name, framePayload.securityOrigin); + frame = frameResource.parentFrame; + frameWasLoadedInstantly = true; + + console.assert(frame); + if (!frame) + return; + } + + if (framePayload.loaderId === frame.provisionalLoaderIdentifier) { + // There was a provisional load in progress, commit it. + frame.commitProvisionalLoad(framePayload.securityOrigin); + } else { + if (frame.mainResource.url !== framePayload.url || frame.loaderIdentifier !== framePayload.loaderId) { + // Navigations like back/forward do not have provisional loads, so create a new main resource here. + var mainResource = new WebInspector.Resource(framePayload.url, framePayload.mimeType, null, framePayload.loaderId); + } else { + // The main resource is already correct, so reuse it. + var mainResource = frame.mainResource; + } + + frame.initialize(framePayload.name, framePayload.securityOrigin, framePayload.loaderId, mainResource); + } + + var oldMainFrame = this._mainFrame; + + if (framePayload.parentId) { + var parentFrame = this.frameForIdentifier(framePayload.parentId); + console.assert(parentFrame); + + if (frame === this._mainFrame) + this._mainFrame = null; + + if (frame.parentFrame !== parentFrame) + parentFrame.addChildFrame(frame); + } else { + if (frame.parentFrame) + frame.parentFrame.removeChildFrame(frame); + this._mainFrame = frame; + } + + if (this._mainFrame !== oldMainFrame) + this._mainFrameDidChange(oldMainFrame); + + if (frameWasLoadedInstantly) + frame.mainResource.markAsFinished(); + } + + frameDidDetach(frameId) + { + // Called from WebInspector.PageObserver. + + // Ignore this while waiting for the whole frame/resource tree. + if (this._waitingForMainFrameResourceTreePayload) + return; + + var frame = this.frameForIdentifier(frameId); + if (!frame) + return; + + if (frame.parentFrame) + frame.parentFrame.removeChildFrame(frame); + + this._frameIdentifierMap.delete(frame.id); + + var oldMainFrame = this._mainFrame; + + if (frame === this._mainFrame) + this._mainFrame = null; + + frame.clearExecutionContexts(); + + this.dispatchEventToListeners(WebInspector.FrameResourceManager.Event.FrameWasRemoved, {frame}); + + if (this._mainFrame !== oldMainFrame) + this._mainFrameDidChange(oldMainFrame); + } + + resourceRequestWillBeSent(requestIdentifier, frameIdentifier, loaderIdentifier, request, type, redirectResponse, timestamp, initiator, targetId) + { + // Called from WebInspector.NetworkObserver. + + // Ignore this while waiting for the whole frame/resource tree. + if (this._waitingForMainFrameResourceTreePayload) + return; + + // COMPATIBILITY (iOS 8): Timeline timestamps for legacy backends are computed + // dynamically from the first backend timestamp received. For navigations we + // need to reset that base timestamp, and an appropriate timestamp to use is + // the new main resource's will be sent timestamp. So save this value on the + // resource in case it becomes a main resource. + var originalRequestWillBeSentTimestamp = timestamp; + + var elapsedTime = WebInspector.timelineManager.computeElapsedTime(timestamp); + let resource = this._resourceRequestIdentifierMap.get(requestIdentifier); + if (resource) { + // This is an existing request which is being redirected, update the resource. + console.assert(redirectResponse); + console.assert(!targetId); + resource.updateForRedirectResponse(request.url, request.headers, elapsedTime); + return; + } + + var initiatorSourceCodeLocation = this._initiatorSourceCodeLocationFromPayload(initiator); + + // This is a new request, make a new resource and add it to the right frame. + resource = this._addNewResourceToFrameOrTarget(requestIdentifier, frameIdentifier, loaderIdentifier, request.url, type, request.method, request.headers, request.postData, elapsedTime, null, null, initiatorSourceCodeLocation, originalRequestWillBeSentTimestamp, targetId); + + // Associate the resource with the requestIdentifier so it can be found in future loading events. + this._resourceRequestIdentifierMap.set(requestIdentifier, resource); + } + + markResourceRequestAsServedFromMemoryCache(requestIdentifier) + { + // Called from WebInspector.NetworkObserver. + + // Ignore this while waiting for the whole frame/resource tree. + if (this._waitingForMainFrameResourceTreePayload) + return; + + let resource = this._resourceRequestIdentifierMap.get(requestIdentifier); + + // We might not have a resource if the inspector was opened during the page load (after resourceRequestWillBeSent is called). + // We don't want to assert in this case since we do likely have the resource, via PageAgent.getResourceTree. The Resource + // just doesn't have a requestIdentifier for us to look it up. + if (!resource) + return; + + resource.markAsCached(); + } + + resourceRequestWasServedFromMemoryCache(requestIdentifier, frameIdentifier, loaderIdentifier, cachedResourcePayload, timestamp, initiator) + { + // Called from WebInspector.NetworkObserver. + + // Ignore this while waiting for the whole frame/resource tree. + if (this._waitingForMainFrameResourceTreePayload) + return; + + console.assert(!this._resourceRequestIdentifierMap.has(requestIdentifier)); + + var elapsedTime = WebInspector.timelineManager.computeElapsedTime(timestamp); + var initiatorSourceCodeLocation = this._initiatorSourceCodeLocationFromPayload(initiator); + var response = cachedResourcePayload.response; + var resource = this._addNewResourceToFrameOrTarget(requestIdentifier, frameIdentifier, loaderIdentifier, cachedResourcePayload.url, cachedResourcePayload.type, "GET", null, null, elapsedTime, null, null, initiatorSourceCodeLocation); + resource.markAsCached(); + resource.updateForResponse(cachedResourcePayload.url, response.mimeType, cachedResourcePayload.type, response.headers, response.status, response.statusText, elapsedTime, response.timing); + resource.increaseSize(cachedResourcePayload.bodySize, elapsedTime); + resource.increaseTransferSize(cachedResourcePayload.bodySize); + resource.markAsFinished(elapsedTime); + + if (cachedResourcePayload.sourceMapURL) + WebInspector.sourceMapManager.downloadSourceMap(cachedResourcePayload.sourceMapURL, resource.url, resource); + + // No need to associate the resource with the requestIdentifier, since this is the only event + // sent for memory cache resource loads. + } + + resourceRequestDidReceiveResponse(requestIdentifier, frameIdentifier, loaderIdentifier, type, response, timestamp) + { + // Called from WebInspector.NetworkObserver. + + // Ignore this while waiting for the whole frame/resource tree. + if (this._waitingForMainFrameResourceTreePayload) + return; + + var elapsedTime = WebInspector.timelineManager.computeElapsedTime(timestamp); + let resource = this._resourceRequestIdentifierMap.get(requestIdentifier); + + // We might not have a resource if the inspector was opened during the page load (after resourceRequestWillBeSent is called). + // We don't want to assert in this case since we do likely have the resource, via PageAgent.getResourceTree. The Resource + // just doesn't have a requestIdentifier for us to look it up, but we can try to look it up by its URL. + if (!resource) { + var frame = this.frameForIdentifier(frameIdentifier); + if (frame) + resource = frame.resourceForURL(response.url); + + // If we find the resource this way we had marked it earlier as finished via PageAgent.getResourceTree. + // Associate the resource with the requestIdentifier so it can be found in future loading events. + // and roll it back to an unfinished state, we know now it is still loading. + if (resource) { + this._resourceRequestIdentifierMap.set(requestIdentifier, resource); + resource.revertMarkAsFinished(); + } + } + + // If we haven't found an existing Resource by now, then it is a resource that was loading when the inspector + // opened and we just missed the resourceRequestWillBeSent for it. So make a new resource and add it. + if (!resource) { + resource = this._addNewResourceToFrameOrTarget(requestIdentifier, frameIdentifier, loaderIdentifier, response.url, type, null, response.requestHeaders, null, elapsedTime, null, null, null); + + // Associate the resource with the requestIdentifier so it can be found in future loading events. + this._resourceRequestIdentifierMap.set(requestIdentifier, resource); + } + + if (response.fromDiskCache) + resource.markAsCached(); + + resource.updateForResponse(response.url, response.mimeType, type, response.headers, response.status, response.statusText, elapsedTime, response.timing); + } + + resourceRequestDidReceiveData(requestIdentifier, dataLength, encodedDataLength, timestamp) + { + // Called from WebInspector.NetworkObserver. + + // Ignore this while waiting for the whole frame/resource tree. + if (this._waitingForMainFrameResourceTreePayload) + return; + + let resource = this._resourceRequestIdentifierMap.get(requestIdentifier); + var elapsedTime = WebInspector.timelineManager.computeElapsedTime(timestamp); + + // We might not have a resource if the inspector was opened during the page load (after resourceRequestWillBeSent is called). + // We don't want to assert in this case since we do likely have the resource, via PageAgent.getResourceTree. The Resource + // just doesn't have a requestIdentifier for us to look it up. + if (!resource) + return; + + resource.increaseSize(dataLength, elapsedTime); + + if (encodedDataLength !== -1) + resource.increaseTransferSize(encodedDataLength); + } + + resourceRequestDidFinishLoading(requestIdentifier, timestamp, sourceMapURL) + { + // Called from WebInspector.NetworkObserver. + + // Ignore this while waiting for the whole frame/resource tree. + if (this._waitingForMainFrameResourceTreePayload) + return; + + // By now we should always have the Resource. Either it was fetched when the inspector first opened with + // PageAgent.getResourceTree, or it was a currently loading resource that we learned about in resourceRequestDidReceiveResponse. + let resource = this._resourceRequestIdentifierMap.get(requestIdentifier); + console.assert(resource); + if (!resource) + return; + + var elapsedTime = WebInspector.timelineManager.computeElapsedTime(timestamp); + resource.markAsFinished(elapsedTime); + + if (sourceMapURL) + WebInspector.sourceMapManager.downloadSourceMap(sourceMapURL, resource.url, resource); + + this._resourceRequestIdentifierMap.delete(requestIdentifier); + } + + resourceRequestDidFailLoading(requestIdentifier, canceled, timestamp) + { + // Called from WebInspector.NetworkObserver. + + // Ignore this while waiting for the whole frame/resource tree. + if (this._waitingForMainFrameResourceTreePayload) + return; + + // By now we should always have the Resource. Either it was fetched when the inspector first opened with + // PageAgent.getResourceTree, or it was a currently loading resource that we learned about in resourceRequestDidReceiveResponse. + let resource = this._resourceRequestIdentifierMap.get(requestIdentifier); + console.assert(resource); + if (!resource) + return; + + var elapsedTime = WebInspector.timelineManager.computeElapsedTime(timestamp); + resource.markAsFailed(canceled, elapsedTime); + + if (resource === resource.parentFrame.provisionalMainResource) + resource.parentFrame.clearProvisionalLoad(); + + this._resourceRequestIdentifierMap.delete(requestIdentifier); + } + + executionContextCreated(contextPayload) + { + // Called from WebInspector.RuntimeObserver. + + var frame = this.frameForIdentifier(contextPayload.frameId); + console.assert(frame); + if (!frame) + return; + + var displayName = contextPayload.name || frame.mainResource.displayName; + var executionContext = new WebInspector.ExecutionContext(WebInspector.mainTarget, contextPayload.id, displayName, contextPayload.isPageContext, frame); + frame.addExecutionContext(executionContext); + } + + resourceForURL(url) + { + if (!this._mainFrame) + return null; + + if (this._mainFrame.mainResource.url === url) + return this._mainFrame.mainResource; + + return this._mainFrame.resourceForURL(url, true); + } + + adoptOrphanedResourcesForTarget(target) + { + let resources = this._orphanedResources.take(target.identifier); + if (!resources) + return; + + for (let resource of resources) + target.adoptResource(resource); + } + + // Private + + _addNewResourceToFrameOrTarget(requestIdentifier, frameIdentifier, loaderIdentifier, url, type, requestMethod, requestHeaders, requestData, elapsedTime, frameName, frameSecurityOrigin, initiatorSourceCodeLocation, originalRequestWillBeSentTimestamp, targetId) + { + console.assert(!this._waitingForMainFrameResourceTreePayload); + + let resource = null; + + let frame = this.frameForIdentifier(frameIdentifier); + if (frame) { + // This is a new request for an existing frame, which might be the main resource or a new resource. + if (frame.mainResource.url === url && frame.loaderIdentifier === loaderIdentifier) + resource = frame.mainResource; + else if (frame.provisionalMainResource && frame.provisionalMainResource.url === url && frame.provisionalLoaderIdentifier === loaderIdentifier) + resource = frame.provisionalMainResource; + else { + resource = new WebInspector.Resource(url, null, type, loaderIdentifier, targetId, requestIdentifier, requestMethod, requestHeaders, requestData, elapsedTime, initiatorSourceCodeLocation, originalRequestWillBeSentTimestamp); + if (resource.target === WebInspector.mainTarget) + this._addResourceToFrame(frame, resource); + else if (resource.target) + resource.target.addResource(resource); + else + this._addOrphanedResource(resource, targetId); + } + } else { + // This is a new request for a new frame, which is always the main resource. + console.assert(!targetId); + resource = new WebInspector.Resource(url, null, type, loaderIdentifier, targetId, requestIdentifier, requestMethod, requestHeaders, requestData, elapsedTime, initiatorSourceCodeLocation, originalRequestWillBeSentTimestamp); + frame = new WebInspector.Frame(frameIdentifier, frameName, frameSecurityOrigin, loaderIdentifier, resource); + this._frameIdentifierMap.set(frame.id, frame); + + // If we don't have a main frame, assume this is it. This can change later in + // frameDidNavigate when the parent frame is known. + if (!this._mainFrame) { + this._mainFrame = frame; + this._mainFrameDidChange(null); + } + + this._dispatchFrameWasAddedEvent(frame); + } + + console.assert(resource); + + return resource; + } + + _addResourceToFrame(frame, resource) + { + console.assert(!this._waitingForMainFrameResourceTreePayload); + if (this._waitingForMainFrameResourceTreePayload) + return; + + console.assert(frame); + console.assert(resource); + + if (resource.loaderIdentifier !== frame.loaderIdentifier && !frame.provisionalLoaderIdentifier) { + // This is the start of a provisional load which happens before frameDidNavigate is called. + // This resource will be the new mainResource if frameDidNavigate is called. + frame.startProvisionalLoad(resource); + return; + } + + // This is just another resource, either for the main loader or the provisional loader. + console.assert(resource.loaderIdentifier === frame.loaderIdentifier || resource.loaderIdentifier === frame.provisionalLoaderIdentifier); + frame.addResource(resource); + } + + _addResourceToTarget(target, resource) + { + console.assert(target !== WebInspector.mainTarget); + console.assert(resource); + + target.addResource(resource); + } + + _initiatorSourceCodeLocationFromPayload(initiatorPayload) + { + if (!initiatorPayload) + return null; + + var url = null; + var lineNumber = NaN; + var columnNumber = 0; + + if (initiatorPayload.stackTrace && initiatorPayload.stackTrace.length) { + var stackTracePayload = initiatorPayload.stackTrace; + for (var i = 0; i < stackTracePayload.length; ++i) { + var callFramePayload = stackTracePayload[i]; + if (!callFramePayload.url || callFramePayload.url === "[native code]") + continue; + + url = callFramePayload.url; + + // The lineNumber is 1-based, but we expect 0-based. + lineNumber = callFramePayload.lineNumber - 1; + + columnNumber = callFramePayload.columnNumber; + + break; + } + } else if (initiatorPayload.url) { + url = initiatorPayload.url; + + // The lineNumber is 1-based, but we expect 0-based. + lineNumber = initiatorPayload.lineNumber - 1; + } + + if (!url || isNaN(lineNumber) || lineNumber < 0) + return null; + + var sourceCode = WebInspector.frameResourceManager.resourceForURL(url); + if (!sourceCode) + sourceCode = WebInspector.debuggerManager.scriptsForURL(url, WebInspector.mainTarget)[0]; + + if (!sourceCode) + return null; + + return sourceCode.createSourceCodeLocation(lineNumber, columnNumber); + } + + _processMainFrameResourceTreePayload(error, mainFramePayload) + { + console.assert(this._waitingForMainFrameResourceTreePayload); + delete this._waitingForMainFrameResourceTreePayload; + + if (error) { + console.error(JSON.stringify(error)); + return; + } + + console.assert(mainFramePayload); + console.assert(mainFramePayload.frame); + + this._resourceRequestIdentifierMap = new Map; + this._frameIdentifierMap = new Map; + + var oldMainFrame = this._mainFrame; + + this._mainFrame = this._addFrameTreeFromFrameResourceTreePayload(mainFramePayload, true); + + if (this._mainFrame !== oldMainFrame) + this._mainFrameDidChange(oldMainFrame); + } + + _createFrame(payload) + { + // If payload.url is missing or empty then this page is likely the special empty page. In that case + // we will just say it is "about:blank" so we have a URL, which is required for resources. + var mainResource = new WebInspector.Resource(payload.url || "about:blank", payload.mimeType, null, payload.loaderId); + var frame = new WebInspector.Frame(payload.id, payload.name, payload.securityOrigin, payload.loaderId, mainResource); + + this._frameIdentifierMap.set(frame.id, frame); + + mainResource.markAsFinished(); + + return frame; + } + + _createResource(payload, framePayload) + { + var resource = new WebInspector.Resource(payload.url, payload.mimeType, payload.type, framePayload.loaderId, payload.targetId); + + if (payload.sourceMapURL) + WebInspector.sourceMapManager.downloadSourceMap(payload.sourceMapURL, resource.url, resource); + + return resource; + } + + _addFrameTreeFromFrameResourceTreePayload(payload, isMainFrame) + { + var frame = this._createFrame(payload.frame); + if (isMainFrame) + frame.markAsMainFrame(); + + for (var i = 0; payload.childFrames && i < payload.childFrames.length; ++i) + frame.addChildFrame(this._addFrameTreeFromFrameResourceTreePayload(payload.childFrames[i], false)); + + for (var i = 0; payload.resources && i < payload.resources.length; ++i) { + var resourcePayload = payload.resources[i]; + + // The main resource is included as a resource. We can skip it since we already created + // a main resource when we created the Frame. The resource payload does not include anything + // didn't already get from the frame payload. + if (resourcePayload.type === "Document" && resourcePayload.url === payload.frame.url) + continue; + + var resource = this._createResource(resourcePayload, payload); + if (resource.target === WebInspector.mainTarget) + frame.addResource(resource); + else if (resource.target) + resource.target.addResource(resource); + else + this._addOrphanedResource(resource, resourcePayload.targetId); + + if (resourcePayload.failed || resourcePayload.canceled) + resource.markAsFailed(resourcePayload.canceled); + else + resource.markAsFinished(); + } + + this._dispatchFrameWasAddedEvent(frame); + + return frame; + } + + _addOrphanedResource(resource, targetId) + { + let resources = this._orphanedResources.get(targetId); + if (!resources) { + resources = []; + this._orphanedResources.set(targetId, resources); + } + + resources.push(resource); + } + + _dispatchFrameWasAddedEvent(frame) + { + this.dispatchEventToListeners(WebInspector.FrameResourceManager.Event.FrameWasAdded, {frame}); + } + + _mainFrameDidChange(oldMainFrame) + { + if (oldMainFrame) + oldMainFrame.unmarkAsMainFrame(); + if (this._mainFrame) + this._mainFrame.markAsMainFrame(); + + this.dispatchEventToListeners(WebInspector.FrameResourceManager.Event.MainFrameDidChange, {oldMainFrame}); + } + + _extraDomainsActivated(event) + { + if (event.data.domains.includes("Page") && window.PageAgent) + PageAgent.getResourceTree(this._processMainFrameResourceTreePayload.bind(this)); + } +}; + +WebInspector.FrameResourceManager.Event = { + FrameWasAdded: "frame-resource-manager-frame-was-added", + FrameWasRemoved: "frame-resource-manager-frame-was-removed", + MainFrameDidChange: "frame-resource-manager-main-frame-did-change", +}; diff --git a/Source/WebInspectorUI/UserInterface/Controllers/HeapManager.js b/Source/WebInspectorUI/UserInterface/Controllers/HeapManager.js new file mode 100644 index 000000000..cc8449cf3 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/HeapManager.js @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.HeapManager = class HeapManager extends WebInspector.Object +{ + constructor() + { + super(); + + if (window.HeapAgent) + HeapAgent.enable(); + } + + // Public + + garbageCollected(target, payload) + { + // Called from WebInspector.HeapObserver. + + // FIXME: Web Inspector: Enable Memory profiling in Workers + if (target !== WebInspector.mainTarget) + return; + + let collection = WebInspector.GarbageCollection.fromPayload(payload); + this.dispatchEventToListeners(WebInspector.HeapManager.Event.GarbageCollected, {collection}); + } +}; + +WebInspector.HeapManager.Event = { + GarbageCollected: "heap-manager-garbage-collected" +}; diff --git a/Source/WebInspectorUI/UserInterface/Controllers/IssueManager.js b/Source/WebInspectorUI/UserInterface/Controllers/IssueManager.js new file mode 100644 index 000000000..a589adb38 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/IssueManager.js @@ -0,0 +1,101 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.IssueManager = class IssueManager extends WebInspector.Object +{ + constructor() + { + super(); + + WebInspector.Frame.addEventListener(WebInspector.Frame.Event.MainResourceDidChange, this._mainResourceDidChange, this); + WebInspector.logManager.addEventListener(WebInspector.LogManager.Event.Cleared, this._logCleared, this); + + this.initialize(); + } + + static issueMatchSourceCode(issue, sourceCode) + { + if (sourceCode instanceof WebInspector.SourceMapResource) + return issue.sourceCodeLocation && issue.sourceCodeLocation.displaySourceCode === sourceCode; + if (sourceCode instanceof WebInspector.Resource) + return issue.url === sourceCode.url && (!issue.sourceCodeLocation || issue.sourceCodeLocation.sourceCode === sourceCode); + if (sourceCode instanceof WebInspector.Script) + return issue.sourceCodeLocation && issue.sourceCodeLocation.sourceCode === sourceCode; + return false; + } + + // Public + + initialize() + { + this._issues = []; + + this.dispatchEventToListeners(WebInspector.IssueManager.Event.Cleared); + } + + issueWasAdded(consoleMessage) + { + let issue = new WebInspector.IssueMessage(consoleMessage); + + this._issues.push(issue); + + this.dispatchEventToListeners(WebInspector.IssueManager.Event.IssueWasAdded, {issue}); + } + + issuesForSourceCode(sourceCode) + { + var issues = []; + + for (var i = 0; i < this._issues.length; ++i) { + var issue = this._issues[i]; + if (WebInspector.IssueManager.issueMatchSourceCode(issue, sourceCode)) + issues.push(issue); + } + + return issues; + } + + // Private + + _logCleared(event) + { + this.initialize(); + } + + _mainResourceDidChange(event) + { + console.assert(event.target instanceof WebInspector.Frame); + + if (!event.target.isMainFrame()) + return; + + this.initialize(); + } +}; + +WebInspector.IssueManager.Event = { + IssueWasAdded: "issue-manager-issue-was-added", + Cleared: "issue-manager-cleared" +}; diff --git a/Source/WebInspectorUI/UserInterface/Controllers/JavaScriptLogViewController.js b/Source/WebInspectorUI/UserInterface/Controllers/JavaScriptLogViewController.js new file mode 100644 index 000000000..72621324c --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/JavaScriptLogViewController.js @@ -0,0 +1,350 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.JavaScriptLogViewController = class JavaScriptLogViewController extends WebInspector.Object +{ + constructor(element, scrollElement, textPrompt, delegate, historySettingIdentifier) + { + super(); + + console.assert(textPrompt instanceof WebInspector.ConsolePrompt); + console.assert(historySettingIdentifier); + + this._element = element; + this._scrollElement = scrollElement; + + this._promptHistorySetting = new WebInspector.Setting(historySettingIdentifier, null); + + this._prompt = textPrompt; + this._prompt.delegate = this; + this._prompt.history = this._promptHistorySetting.value; + + this.delegate = delegate; + + this._cleared = true; + this._previousMessageView = null; + this._lastCommitted = ""; + this._repeatCountWasInterrupted = false; + + this._sessions = []; + + this.messagesAlternateClearKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.Control, "L", this.requestClearMessages.bind(this), this._element); + + this._messagesFindNextKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, "G", this._handleFindNextShortcut.bind(this), this._element); + this._messagesFindPreviousKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl | WebInspector.KeyboardShortcut.Modifier.Shift, "G", this._handleFindPreviousShortcut.bind(this), this._element); + + this._promptAlternateClearKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.Control, "L", this.requestClearMessages.bind(this), this._prompt.element); + this._promptFindNextKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, "G", this._handleFindNextShortcut.bind(this), this._prompt.element); + this._promptFindPreviousKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl | WebInspector.KeyboardShortcut.Modifier.Shift, "G", this._handleFindPreviousShortcut.bind(this), this._prompt.element); + + this._pendingMessages = []; + this._scheduledRenderIdentifier = 0; + + this.startNewSession(); + } + + // Public + + get prompt() + { + return this._prompt; + } + + get currentConsoleGroup() + { + return this._currentConsoleGroup; + } + + clear() + { + this._cleared = true; + + const clearPreviousSessions = true; + this.startNewSession(clearPreviousSessions, {newSessionReason: WebInspector.ConsoleSession.NewSessionReason.ConsoleCleared}); + } + + startNewSession(clearPreviousSessions = false, data = {}) + { + if (this._sessions.length && clearPreviousSessions) { + for (var i = 0; i < this._sessions.length; ++i) + this._element.removeChild(this._sessions[i].element); + + this._sessions = []; + this._currentConsoleGroup = null; + } + + // First session shows the time when the console was opened. + if (!this._sessions.length) + data.timestamp = Date.now(); + + let lastSession = this._sessions.lastValue; + + // Remove empty session. + if (lastSession && !lastSession.hasMessages()) { + this._sessions.pop(); + lastSession.element.remove(); + } + + let consoleSession = new WebInspector.ConsoleSession(data); + + this._previousMessageView = null; + this._lastCommitted = ""; + this._repeatCountWasInterrupted = false; + + this._sessions.push(consoleSession); + this._currentConsoleGroup = consoleSession; + + this._element.appendChild(consoleSession.element); + + // Make sure the new session is visible. + consoleSession.element.scrollIntoView(); + } + + appendImmediateExecutionWithResult(text, result, addSpecialUserLogClass, shouldRevealConsole) + { + console.assert(result instanceof WebInspector.RemoteObject); + + var commandMessageView = new WebInspector.ConsoleCommandView(text, addSpecialUserLogClass ? "special-user-log" : null); + this._appendConsoleMessageView(commandMessageView, true); + + function saveResultCallback(savedResultIndex) + { + let commandResultMessage = new WebInspector.ConsoleCommandResultMessage(result.target, result, false, savedResultIndex, shouldRevealConsole); + let commandResultMessageView = new WebInspector.ConsoleMessageView(commandResultMessage); + this._appendConsoleMessageView(commandResultMessageView, true); + } + + WebInspector.runtimeManager.saveResult(result, saveResultCallback.bind(this)); + } + + appendConsoleMessage(consoleMessage) + { + var consoleMessageView = new WebInspector.ConsoleMessageView(consoleMessage); + this._appendConsoleMessageView(consoleMessageView); + return consoleMessageView; + } + + updatePreviousMessageRepeatCount(count) + { + console.assert(this._previousMessageView); + if (!this._previousMessageView) + return false; + + var previousIgnoredCount = this._previousMessageView[WebInspector.JavaScriptLogViewController.IgnoredRepeatCount] || 0; + var previousVisibleCount = this._previousMessageView.repeatCount; + + if (!this._repeatCountWasInterrupted) { + this._previousMessageView.repeatCount = count - previousIgnoredCount; + return true; + } + + var consoleMessage = this._previousMessageView.message; + var duplicatedConsoleMessageView = new WebInspector.ConsoleMessageView(consoleMessage); + duplicatedConsoleMessageView[WebInspector.JavaScriptLogViewController.IgnoredRepeatCount] = previousIgnoredCount + previousVisibleCount; + duplicatedConsoleMessageView.repeatCount = 1; + this._appendConsoleMessageView(duplicatedConsoleMessageView); + + return true; + } + + isScrolledToBottom() + { + // Lie about being scrolled to the bottom if we have a pending request to scroll to the bottom soon. + return this._scrollToBottomTimeout || this._scrollElement.isScrolledToBottom(); + } + + scrollToBottom() + { + if (this._scrollToBottomTimeout) + return; + + function delayedWork() + { + this._scrollToBottomTimeout = null; + this._scrollElement.scrollTop = this._scrollElement.scrollHeight; + } + + // Don't scroll immediately so we are not causing excessive layouts when there + // are many messages being added at once. + this._scrollToBottomTimeout = setTimeout(delayedWork.bind(this), 0); + } + + requestClearMessages() + { + WebInspector.logManager.requestClearMessages(); + } + + // Protected + + consolePromptHistoryDidChange(prompt) + { + this._promptHistorySetting.value = this.prompt.history; + } + + consolePromptShouldCommitText(prompt, text, cursorIsAtLastPosition, handler) + { + // Always commit the text if we are not at the last position. + if (!cursorIsAtLastPosition) { + handler(true); + return; + } + + function parseFinished(error, result, message, range) + { + handler(result !== RuntimeAgent.SyntaxErrorType.Recoverable); + } + + WebInspector.runtimeManager.activeExecutionContext.target.RuntimeAgent.parse(text, parseFinished.bind(this)); + } + + consolePromptTextCommitted(prompt, text) + { + console.assert(text); + + if (this._lastCommitted !== text) { + let commandMessageView = new WebInspector.ConsoleCommandView(text); + this._appendConsoleMessageView(commandMessageView, true); + this._lastCommitted = text; + } + + function printResult(result, wasThrown, savedResultIndex) + { + if (!result || this._cleared) + return; + + let shouldRevealConsole = true; + let commandResultMessage = new WebInspector.ConsoleCommandResultMessage(result.target, result, wasThrown, savedResultIndex, shouldRevealConsole); + let commandResultMessageView = new WebInspector.ConsoleMessageView(commandResultMessage); + this._appendConsoleMessageView(commandResultMessageView, true); + } + + let options = { + objectGroup: WebInspector.RuntimeManager.ConsoleObjectGroup, + includeCommandLineAPI: true, + doNotPauseOnExceptionsAndMuteConsole: false, + returnByValue: false, + generatePreview: true, + saveResult: true, + sourceURLAppender: appendWebInspectorConsoleEvaluationSourceURL, + }; + + WebInspector.runtimeManager.evaluateInInspectedWindow(text, options, printResult.bind(this)); + } + + // Private + + _handleFindNextShortcut() + { + this.delegate.highlightNextSearchMatch(); + } + + _handleFindPreviousShortcut() + { + this.delegate.highlightPreviousSearchMatch(); + } + + _appendConsoleMessageView(messageView, repeatCountWasInterrupted) + { + this._pendingMessages.push(messageView); + + this._cleared = false; + this._repeatCountWasInterrupted = repeatCountWasInterrupted || false; + + if (!repeatCountWasInterrupted) + this._previousMessageView = messageView; + + if (messageView.message && messageView.message.source !== WebInspector.ConsoleMessage.MessageSource.JS) + this._lastCommitted = ""; + + if (WebInspector.consoleContentView.visible) + this.renderPendingMessagesSoon(); + + if (!WebInspector.isShowingConsoleTab() && messageView.message && messageView.message.shouldRevealConsole) + WebInspector.showSplitConsole(); + } + + renderPendingMessages() + { + if (this._scheduledRenderIdentifier) { + cancelAnimationFrame(this._scheduledRenderIdentifier); + this._scheduledRenderIdentifier = 0; + } + + if (this._pendingMessages.length === 0) + return; + + const maxMessagesPerFrame = 100; + let messages = this._pendingMessages.splice(0, maxMessagesPerFrame); + + let lastMessageView = messages.lastValue; + let isCommandView = lastMessageView instanceof WebInspector.ConsoleCommandView; + let shouldScrollToBottom = isCommandView || lastMessageView.message.type === WebInspector.ConsoleMessage.MessageType.Result || this.isScrolledToBottom(); + + for (let messageView of messages) { + messageView.render(); + this._didRenderConsoleMessageView(messageView); + } + + if (shouldScrollToBottom) + this.scrollToBottom(); + + WebInspector.quickConsole.needsLayout(); + + if (this._pendingMessages.length > 0) + this.renderPendingMessagesSoon(); + } + + renderPendingMessagesSoon() + { + if (this._scheduledRenderIdentifier) + return; + + this._scheduledRenderIdentifier = requestAnimationFrame(() => this.renderPendingMessages()); + } + + _didRenderConsoleMessageView(messageView) + { + var type = messageView instanceof WebInspector.ConsoleCommandView ? null : messageView.message.type; + if (type === WebInspector.ConsoleMessage.MessageType.EndGroup) { + var parentGroup = this._currentConsoleGroup.parentGroup; + if (parentGroup) + this._currentConsoleGroup = parentGroup; + } else { + if (type === WebInspector.ConsoleMessage.MessageType.StartGroup || type === WebInspector.ConsoleMessage.MessageType.StartGroupCollapsed) { + var group = new WebInspector.ConsoleGroup(this._currentConsoleGroup); + var groupElement = group.render(messageView); + this._currentConsoleGroup.append(groupElement); + this._currentConsoleGroup = group; + } else + this._currentConsoleGroup.addMessageView(messageView); + } + + if (this.delegate && typeof this.delegate.didAppendConsoleMessageView === "function") + this.delegate.didAppendConsoleMessageView(messageView); + } +}; + +WebInspector.JavaScriptLogViewController.CachedPropertiesDuration = 30000; +WebInspector.JavaScriptLogViewController.IgnoredRepeatCount = Symbol("ignored-repeat-count"); diff --git a/Source/WebInspectorUI/UserInterface/Controllers/JavaScriptRuntimeCompletionProvider.js b/Source/WebInspectorUI/UserInterface/Controllers/JavaScriptRuntimeCompletionProvider.js new file mode 100644 index 000000000..134b2f032 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/JavaScriptRuntimeCompletionProvider.js @@ -0,0 +1,307 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +Object.defineProperty(WebInspector, "javaScriptRuntimeCompletionProvider", +{ + get: function() + { + if (!WebInspector.JavaScriptRuntimeCompletionProvider._instance) + WebInspector.JavaScriptRuntimeCompletionProvider._instance = new WebInspector.JavaScriptRuntimeCompletionProvider; + return WebInspector.JavaScriptRuntimeCompletionProvider._instance; + } +}); + +WebInspector.JavaScriptRuntimeCompletionProvider = class JavaScriptRuntimeCompletionProvider extends WebInspector.Object +{ + constructor() + { + super(); + + console.assert(!WebInspector.JavaScriptRuntimeCompletionProvider._instance); + + WebInspector.debuggerManager.addEventListener(WebInspector.DebuggerManager.Event.ActiveCallFrameDidChange, this._clearLastProperties, this); + } + + // Protected + + completionControllerCompletionsNeeded(completionController, defaultCompletions, base, prefix, suffix, forced) + { + // Don't allow non-forced empty prefix completions unless the base is that start of property access. + if (!forced && !prefix && !/[.[]$/.test(base)) { + completionController.updateCompletions(null); + return; + } + + // If the base ends with an open parentheses or open curly bracket then treat it like there is + // no base so we get global object completions. + if (/[({]$/.test(base)) + base = ""; + + var lastBaseIndex = base.length - 1; + var dotNotation = base[lastBaseIndex] === "."; + var bracketNotation = base[lastBaseIndex] === "["; + + if (dotNotation || bracketNotation) { + base = base.substring(0, lastBaseIndex); + + // Don't suggest anything for an empty base that is using dot notation. + // Bracket notation with an empty base will be treated as an array. + if (!base && dotNotation) { + completionController.updateCompletions(defaultCompletions); + return; + } + + // Don't allow non-forced empty prefix completions if the user is entering a number, since it might be a float. + // But allow number completions if the base already has a decimal, so "10.0." will suggest Number properties. + if (!forced && !prefix && dotNotation && base.indexOf(".") === -1 && parseInt(base, 10) == base) { + completionController.updateCompletions(null); + return; + } + + // An empty base with bracket notation is not property access, it is an array. + // Clear the bracketNotation flag so completions are not quoted. + if (!base && bracketNotation) + bracketNotation = false; + } + + // If the base is the same as the last time, we can reuse the property names we have already gathered. + // Doing this eliminates delay caused by the async nature of the code below and it only calls getters + // and functions once instead of repetitively. Sure, there can be difference each time the base is evaluated, + // but this optimization gives us more of a win. We clear the cache after 30 seconds or when stepping in the + // debugger to make sure we don't use stale properties in most cases. + if (this._lastBase === base && this._lastPropertyNames) { + receivedPropertyNames.call(this, this._lastPropertyNames); + return; + } + + this._lastBase = base; + this._lastPropertyNames = null; + + var activeCallFrame = WebInspector.debuggerManager.activeCallFrame; + if (!base && activeCallFrame && !this._alwaysEvaluateInWindowContext) + activeCallFrame.collectScopeChainVariableNames(receivedPropertyNames.bind(this)); + else { + let options = {objectGroup: "completion", includeCommandLineAPI: true, doNotPauseOnExceptionsAndMuteConsole: true, returnByValue: false, generatePreview: false, saveResult: false}; + WebInspector.runtimeManager.evaluateInInspectedWindow(base, options, evaluated.bind(this)); + } + + function updateLastPropertyNames(propertyNames) + { + if (this._clearLastPropertiesTimeout) + clearTimeout(this._clearLastPropertiesTimeout); + this._clearLastPropertiesTimeout = setTimeout(this._clearLastProperties.bind(this), WebInspector.JavaScriptLogViewController.CachedPropertiesDuration); + + this._lastPropertyNames = propertyNames || {}; + } + + function evaluated(result, wasThrown) + { + if (wasThrown || !result || result.type === "undefined" || (result.type === "object" && result.subtype === "null")) { + WebInspector.runtimeManager.activeExecutionContext.target.RuntimeAgent.releaseObjectGroup("completion"); + + updateLastPropertyNames.call(this, {}); + completionController.updateCompletions(defaultCompletions); + + return; + } + + function inspectedPage_evalResult_getArrayCompletions(primitiveType) + { + var array = this; + var arrayLength; + + var resultSet = {}; + for (var o = array; o; o = o.__proto__) { + try { + if (o === array && o.length) { + // If the array type has a length, don't include a list of all the indexes. + // Include it at the end and the frontend can build the list. + arrayLength = o.length; + } else { + var names = Object.getOwnPropertyNames(o); + for (var i = 0; i < names.length; ++i) + resultSet[names[i]] = true; + } + } catch (e) { + // Ignore + } + } + + if (arrayLength) + resultSet["length"] = arrayLength; + + return resultSet; + } + + function inspectedPage_evalResult_getCompletions(primitiveType) + { + var object; + if (primitiveType === "string") + object = new String(""); + else if (primitiveType === "number") + object = new Number(0); + else if (primitiveType === "boolean") + object = new Boolean(false); + else if (primitiveType === "symbol") + object = Symbol(); + else + object = this; + + var resultSet = {}; + for (var o = object; o; o = o.__proto__) { + try { + var names = Object.getOwnPropertyNames(o); + for (var i = 0; i < names.length; ++i) + resultSet[names[i]] = true; + } catch (e) { + // Ignore + } + } + + return resultSet; + } + + if (result.subtype === "array") + result.callFunctionJSON(inspectedPage_evalResult_getArrayCompletions, undefined, receivedArrayPropertyNames.bind(this)); + else if (result.type === "object" || result.type === "function") + result.callFunctionJSON(inspectedPage_evalResult_getCompletions, undefined, receivedPropertyNames.bind(this)); + else if (result.type === "string" || result.type === "number" || result.type === "boolean" || result.type === "symbol") { + let options = {objectGroup: "completion", includeCommandLineAPI: false, doNotPauseOnExceptionsAndMuteConsole: true, returnByValue: false, generatePreview: false, saveResult: false}; + WebInspector.runtimeManager.evaluateInInspectedWindow("(" + inspectedPage_evalResult_getCompletions + ")(\"" + result.type + "\")", options, receivedPropertyNamesFromEvaluate.bind(this)); + } else + console.error("Unknown result type: " + result.type); + } + + function receivedPropertyNamesFromEvaluate(object, wasThrown, result) + { + receivedPropertyNames.call(this, result && !wasThrown ? result.value : null); + } + + function receivedArrayPropertyNames(propertyNames) + { + // FIXME: Web Inspector: Better handling for large collections in Object Trees + // If there was an array like object, we generate autocompletion up to 1000 indexes, but this should + // handle a list with arbitrary length. + if (propertyNames && typeof propertyNames.length === "number") { + var max = Math.min(propertyNames.length, 1000); + for (var i = 0; i < max; ++i) + propertyNames[i] = true; + } + + receivedPropertyNames.call(this, propertyNames); + } + + function receivedPropertyNames(propertyNames) + { + propertyNames = propertyNames || {}; + + updateLastPropertyNames.call(this, propertyNames); + + WebInspector.runtimeManager.activeExecutionContext.target.RuntimeAgent.releaseObjectGroup("completion"); + + if (!base) { + var commandLineAPI = ["$", "$$", "$x", "dir", "dirxml", "keys", "values", "profile", "profileEnd", "monitorEvents", "unmonitorEvents", "inspect", "copy", "clear", "getEventListeners", "$0", "$_"]; + if (WebInspector.debuggerManager.paused) { + let targetData = WebInspector.debuggerManager.dataForTarget(WebInspector.runtimeManager.activeExecutionContext.target); + if (targetData.pauseReason === WebInspector.DebuggerManager.PauseReason.Exception) + commandLineAPI.push("$exception"); + } + for (var i = 0; i < commandLineAPI.length; ++i) + propertyNames[commandLineAPI[i]] = true; + + // FIXME: Due to caching, sometimes old $n values show up as completion results even though they are not available. We should clear that proactively. + for (var i = 1; i <= WebInspector.ConsoleCommandResultMessage.maximumSavedResultIndex; ++i) + propertyNames["$" + i] = true; + } + + propertyNames = Object.keys(propertyNames); + + var implicitSuffix = ""; + if (bracketNotation) { + var quoteUsed = prefix[0] === "'" ? "'" : "\""; + if (suffix !== "]" && suffix !== quoteUsed) + implicitSuffix = "]"; + } + + var completions = defaultCompletions; + var knownCompletions = completions.keySet(); + + for (var i = 0; i < propertyNames.length; ++i) { + var property = propertyNames[i]; + + if (dotNotation && !/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(property)) + continue; + + if (bracketNotation) { + if (parseInt(property) != property) + property = quoteUsed + property.escapeCharacters(quoteUsed + "\\") + (suffix !== quoteUsed ? quoteUsed : ""); + } + + if (!property.startsWith(prefix) || property in knownCompletions) + continue; + + completions.push(property); + knownCompletions[property] = true; + } + + function compare(a, b) + { + // Try to sort in numerical order first. + let numericCompareResult = a - b; + if (!isNaN(numericCompareResult)) + return numericCompareResult; + + // Sort __defineGetter__, __lookupGetter__, and friends last. + let aRareProperty = a.startsWith("__") && a.endsWith("__"); + let bRareProperty = b.startsWith("__") && b.endsWith("__"); + if (aRareProperty && !bRareProperty) + return 1; + if (!aRareProperty && bRareProperty) + return -1; + + // Not numbers, sort as strings. + return a.localeCompare(b); + } + + completions.sort(compare); + + completionController.updateCompletions(completions, implicitSuffix); + } + } + + // Private + + _clearLastProperties() + { + if (this._clearLastPropertiesTimeout) { + clearTimeout(this._clearLastPropertiesTimeout); + delete this._clearLastPropertiesTimeout; + } + + // Clear the cache of property names so any changes while stepping or sitting idle get picked up if the same + // expression is evaluated again. + this._lastPropertyNames = null; + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Controllers/LayerTreeManager.js b/Source/WebInspectorUI/UserInterface/Controllers/LayerTreeManager.js new file mode 100644 index 000000000..48ec5f1d4 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/LayerTreeManager.js @@ -0,0 +1,154 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.LayerTreeManager = class LayerTreeManager extends WebInspector.Object +{ + constructor() + { + super(); + + this._supported = !!window.LayerTreeAgent; + + if (this._supported) + LayerTreeAgent.enable(); + } + + // Public + + get supported() + { + return this._supported; + } + + layerTreeMutations(previousLayers, newLayers) + { + console.assert(this.supported); + + if (isEmptyObject(previousLayers)) { + return { + preserved: [], + additions: newLayers, + removals: [] + }; + } + + function nodeIdForLayer(layer) + { + return layer.isGeneratedContent ? layer.pseudoElementId : layer.nodeId; + } + + var layerIdsInPreviousLayers = []; + var nodeIdsInPreviousLayers = []; + var nodeIdsForReflectionsInPreviousLayers = []; + + previousLayers.forEach(function(layer) { + layerIdsInPreviousLayers.push(layer.layerId); + + var nodeId = nodeIdForLayer(layer); + if (!nodeId) + return; + + if (layer.isReflection) + nodeIdsForReflectionsInPreviousLayers.push(nodeId); + else + nodeIdsInPreviousLayers.push(nodeId); + }); + + var preserved = []; + var additions = []; + + var layerIdsInNewLayers = []; + var nodeIdsInNewLayers = []; + var nodeIdsForReflectionsInNewLayers = []; + + newLayers.forEach(function(layer) { + layerIdsInNewLayers.push(layer.layerId); + + var existed = layerIdsInPreviousLayers.includes(layer.layerId); + + var nodeId = nodeIdForLayer(layer); + if (!nodeId) + return; + + if (layer.isReflection) { + nodeIdsForReflectionsInNewLayers.push(nodeId); + existed = existed || nodeIdsForReflectionsInPreviousLayers.includes(nodeId); + } else { + nodeIdsInNewLayers.push(nodeId); + existed = existed || nodeIdsInPreviousLayers.includes(nodeId); + } + + if (existed) + preserved.push(layer); + else + additions.push(layer); + }); + + var removals = previousLayers.filter(function(layer) { + var nodeId = nodeIdForLayer(layer); + + if (layer.isReflection) + return !nodeIdsForReflectionsInNewLayers.includes(nodeId); + else + return !nodeIdsInNewLayers.includes(nodeId) && !layerIdsInNewLayers.includes(layer.layerId); + }); + + return {preserved, additions, removals}; + } + + layersForNode(node, callback) + { + console.assert(this.supported); + + LayerTreeAgent.layersForNode(node.id, function(error, layers) { + if (error || isEmptyObject(layers)) { + callback(null, []); + return; + } + + var firstLayer = layers[0]; + var layerForNode = firstLayer.nodeId === node.id && !firstLayer.isGeneratedContent ? layers.shift() : null; + callback(layerForNode, layers); + }); + } + + reasonsForCompositingLayer(layer, callback) + { + console.assert(this.supported); + + LayerTreeAgent.reasonsForCompositingLayer(layer.layerId, function(error, reasons) { + callback(error ? 0 : reasons); + }); + } + + layerTreeDidChange() + { + this.dispatchEventToListeners(WebInspector.LayerTreeManager.Event.LayerTreeDidChange); + } +}; + +WebInspector.LayerTreeManager.Event = { + LayerTreeDidChange: "layer-tree-did-change" +}; diff --git a/Source/WebInspectorUI/UserInterface/Controllers/LogManager.js b/Source/WebInspectorUI/UserInterface/Controllers/LogManager.js new file mode 100644 index 000000000..3b917bbbd --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/LogManager.js @@ -0,0 +1,129 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * Copyright (C) 2015 Tobias Reiss + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.LogManager = class LogManager extends WebInspector.Object +{ + constructor() + { + super(); + + this._clearMessagesRequested = false; + this._isNewPageOrReload = false; + + WebInspector.Frame.addEventListener(WebInspector.Frame.Event.MainResourceDidChange, this._mainResourceDidChange, this); + } + + // Public + + messageWasAdded(target, source, level, text, type, url, line, column, repeatCount, parameters, stackTrace, requestId) + { + // Called from WebInspector.ConsoleObserver. + + // FIXME: Get a request from request ID. + + if (parameters) + parameters = parameters.map((x) => WebInspector.RemoteObject.fromPayload(x, target)); + + let message = new WebInspector.ConsoleMessage(target, source, level, text, type, url, line, column, repeatCount, parameters, stackTrace, null); + + this.dispatchEventToListeners(WebInspector.LogManager.Event.MessageAdded, {message}); + + if (message.level === "warning" || message.level === "error") + WebInspector.issueManager.issueWasAdded(message); + } + + messagesCleared() + { + // Called from WebInspector.ConsoleObserver. + + WebInspector.ConsoleCommandResultMessage.clearMaximumSavedResultIndex(); + + if (this._clearMessagesRequested) { + // Frontend requested "clear console" and Backend successfully completed the request. + this._clearMessagesRequested = false; + this.dispatchEventToListeners(WebInspector.LogManager.Event.Cleared); + } else { + // Received an unrequested clear console event. + // This could be for a navigation or other reasons (like console.clear()). + // If this was a reload, we may not want to dispatch WebInspector.LogManager.Event.Cleared. + // To detect if this is a reload we wait a turn and check if there was a main resource change reload. + setTimeout(this._delayedMessagesCleared.bind(this), 0); + } + } + + _delayedMessagesCleared() + { + if (this._isNewPageOrReload) { + this._isNewPageOrReload = false; + + if (!WebInspector.settings.clearLogOnNavigate.value) + return; + } + + // A console.clear() or command line clear() happened. + this.dispatchEventToListeners(WebInspector.LogManager.Event.Cleared); + } + + messageRepeatCountUpdated(count) + { + // Called from WebInspector.ConsoleObserver. + + this.dispatchEventToListeners(WebInspector.LogManager.Event.PreviousMessageRepeatCountUpdated, {count}); + } + + requestClearMessages() + { + this._clearMessagesRequested = true; + + for (let target of WebInspector.targets) + target.ConsoleAgent.clearMessages(); + } + + // Private + + _mainResourceDidChange(event) + { + console.assert(event.target instanceof WebInspector.Frame); + + if (!event.target.isMainFrame()) + return; + + this._isNewPageOrReload = true; + + let timestamp = Date.now(); + let wasReloaded = event.data.oldMainResource && event.data.oldMainResource.url === event.target.mainResource.url; + this.dispatchEventToListeners(WebInspector.LogManager.Event.SessionStarted, {timestamp, wasReloaded}); + + WebInspector.ConsoleCommandResultMessage.clearMaximumSavedResultIndex(); + } +}; + +WebInspector.LogManager.Event = { + SessionStarted: "log-manager-session-was-started", + Cleared: "log-manager-cleared", + MessageAdded: "log-manager-message-added", + PreviousMessageRepeatCountUpdated: "log-manager-previous-message-repeat-count-updated" +}; diff --git a/Source/WebInspectorUI/UserInterface/Controllers/MemoryManager.js b/Source/WebInspectorUI/UserInterface/Controllers/MemoryManager.js new file mode 100644 index 000000000..ecb07eacb --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/MemoryManager.js @@ -0,0 +1,49 @@ +/* + * Copyright (C) 2016 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.MemoryManager = class MemoryManager extends WebInspector.Object +{ + constructor() + { + super(); + + if (window.MemoryAgent) + MemoryAgent.enable(); + } + + // Public + + memoryPressure(timestamp, protocolSeverity) + { + // Called from WebInspector.MemoryObserver. + + let memoryPressureEvent = WebInspector.MemoryPressureEvent.fromPayload(timestamp, protocolSeverity); + this.dispatchEventToListeners(WebInspector.MemoryManager.Event.MemoryPressure, {memoryPressureEvent}); + } +}; + +WebInspector.MemoryManager.Event = { + MemoryPressure: "memory-manager-memory-pressure", +}; diff --git a/Source/WebInspectorUI/UserInterface/Controllers/ProbeManager.js b/Source/WebInspectorUI/UserInterface/Controllers/ProbeManager.js new file mode 100644 index 000000000..b7f100fba --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/ProbeManager.js @@ -0,0 +1,177 @@ +/* + * Copyright (C) 2013 University of Washington. All rights reserved. + * Copyright (C) 2014 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.ProbeManager = class ProbeManager extends WebInspector.Object +{ + constructor() + { + super(); + + // Used to detect deleted probe actions. + this._knownProbeIdentifiersForBreakpoint = new Map; + + // Main lookup tables for probes and probe sets. + this._probesByIdentifier = new Map; + this._probeSetsByBreakpoint = new Map; + + WebInspector.debuggerManager.addEventListener(WebInspector.DebuggerManager.Event.BreakpointAdded, this._breakpointAdded, this); + WebInspector.debuggerManager.addEventListener(WebInspector.DebuggerManager.Event.BreakpointRemoved, this._breakpointRemoved, this); + WebInspector.Breakpoint.addEventListener(WebInspector.Breakpoint.Event.ActionsDidChange, this._breakpointActionsChanged, this); + + // Saved breakpoints should not be restored on the first event loop turn, because it + // makes manager initialization order very fragile. No breakpoints should be available. + console.assert(!WebInspector.debuggerManager.breakpoints.length, "No breakpoints should exist before all the managers are constructed."); + } + + // Public + + get probeSets() + { + return [...this._probeSetsByBreakpoint.values()]; + } + + probeForIdentifier(identifier) + { + return this._probesByIdentifier.get(identifier); + } + + // Protected (called by WebInspector.DebuggerObserver) + + didSampleProbe(target, sample) + { + console.assert(this._probesByIdentifier.has(sample.probeId), "Unknown probe identifier specified for sample: ", sample); + let probe = this._probesByIdentifier.get(sample.probeId); + let elapsedTime = WebInspector.timelineManager.computeElapsedTime(sample.timestamp); + let object = WebInspector.RemoteObject.fromPayload(sample.payload, target); + probe.addSample(new WebInspector.ProbeSample(sample.sampleId, sample.batchId, elapsedTime, object)); + } + + // Private + + _breakpointAdded(breakpointOrEvent) + { + var breakpoint; + if (breakpointOrEvent instanceof WebInspector.Breakpoint) + breakpoint = breakpointOrEvent; + else + breakpoint = breakpointOrEvent.data.breakpoint; + + console.assert(breakpoint instanceof WebInspector.Breakpoint, "Unknown object passed as breakpoint: ", breakpoint); + + if (this._knownProbeIdentifiersForBreakpoint.has(breakpoint)) + return; + + this._knownProbeIdentifiersForBreakpoint.set(breakpoint, new Set); + + this._breakpointActionsChanged(breakpoint); + } + + _breakpointRemoved(event) + { + var breakpoint = event.data.breakpoint; + console.assert(this._knownProbeIdentifiersForBreakpoint.has(breakpoint)); + + this._breakpointActionsChanged(breakpoint); + this._knownProbeIdentifiersForBreakpoint.delete(breakpoint); + } + + _breakpointActionsChanged(breakpointOrEvent) + { + var breakpoint; + if (breakpointOrEvent instanceof WebInspector.Breakpoint) + breakpoint = breakpointOrEvent; + else + breakpoint = breakpointOrEvent.target; + + console.assert(breakpoint instanceof WebInspector.Breakpoint, "Unknown object passed as breakpoint: ", breakpoint); + + // Sometimes actions change before the added breakpoint is fully dispatched. + if (!this._knownProbeIdentifiersForBreakpoint.has(breakpoint)) { + this._breakpointAdded(breakpoint); + return; + } + + var knownProbeIdentifiers = this._knownProbeIdentifiersForBreakpoint.get(breakpoint); + var seenProbeIdentifiers = new Set; + + breakpoint.probeActions.forEach(function(probeAction) { + var probeIdentifier = probeAction.id; + console.assert(probeIdentifier, "Probe added without breakpoint action identifier: ", breakpoint); + + seenProbeIdentifiers.add(probeIdentifier); + if (!knownProbeIdentifiers.has(probeIdentifier)) { + // New probe; find or create relevant probe set. + knownProbeIdentifiers.add(probeIdentifier); + var probeSet = this._probeSetForBreakpoint(breakpoint); + var newProbe = new WebInspector.Probe(probeIdentifier, breakpoint, probeAction.data); + this._probesByIdentifier.set(probeIdentifier, newProbe); + probeSet.addProbe(newProbe); + return; + } + + var probe = this._probesByIdentifier.get(probeIdentifier); + console.assert(probe, "Probe known but couldn't be found by identifier: ", probeIdentifier); + // Update probe expression; if it differed, change events will fire. + probe.expression = probeAction.data; + }, this); + + // Look for missing probes based on what we saw last. + knownProbeIdentifiers.forEach(function(probeIdentifier) { + if (seenProbeIdentifiers.has(probeIdentifier)) + return; + + // The probe has gone missing, remove it. + var probeSet = this._probeSetForBreakpoint(breakpoint); + var probe = this._probesByIdentifier.get(probeIdentifier); + this._probesByIdentifier.delete(probeIdentifier); + knownProbeIdentifiers.delete(probeIdentifier); + probeSet.removeProbe(probe); + + // Remove the probe set if it has become empty. + if (!probeSet.probes.length) { + this._probeSetsByBreakpoint.delete(probeSet.breakpoint); + probeSet.willRemove(); + this.dispatchEventToListeners(WebInspector.ProbeManager.Event.ProbeSetRemoved, {probeSet}); + } + }, this); + } + + _probeSetForBreakpoint(breakpoint) + { + if (this._probeSetsByBreakpoint.has(breakpoint)) + return this._probeSetsByBreakpoint.get(breakpoint); + + var newProbeSet = new WebInspector.ProbeSet(breakpoint); + this._probeSetsByBreakpoint.set(breakpoint, newProbeSet); + this.dispatchEventToListeners(WebInspector.ProbeManager.Event.ProbeSetAdded, {probeSet: newProbeSet}); + return newProbeSet; + } +}; + +WebInspector.ProbeManager.Event = { + ProbeSetAdded: "probe-manager-probe-set-added", + ProbeSetRemoved: "probe-manager-probe-set-removed", +}; diff --git a/Source/WebInspectorUI/UserInterface/Controllers/ReplayManager.js b/Source/WebInspectorUI/UserInterface/Controllers/ReplayManager.js new file mode 100644 index 000000000..ab04ddf10 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/ReplayManager.js @@ -0,0 +1,678 @@ +/* + * Copyright (C) 2013 University of Washington. All rights reserved. + * Copyright (C) 2014 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.ReplayManager = class ReplayManager extends WebInspector.Object +{ + constructor() + { + super(); + + this._sessionState = WebInspector.ReplayManager.SessionState.Inactive; + this._segmentState = WebInspector.ReplayManager.SegmentState.Unloaded; + + this._activeSessionIdentifier = null; + this._activeSegmentIdentifier = null; + this._currentPosition = new WebInspector.ReplayPosition(0, 0); + this._initialized = false; + + // These hold actual instances of sessions and segments. + this._sessions = new Map; + this._segments = new Map; + // These hold promises that resolve when the instance data is recieved. + this._sessionPromises = new Map; + this._segmentPromises = new Map; + + // Playback speed is specified in replayToPosition commands, and persists + // for the duration of the playback command until another playback begins. + this._playbackSpeed = WebInspector.ReplayManager.PlaybackSpeed.RealTime; + + if (window.ReplayAgent) { + var instance = this; + this._initializationPromise = ReplayAgent.currentReplayState() + .then(function(payload) { + console.assert(payload.sessionState in WebInspector.ReplayManager.SessionState, "Unknown session state: " + payload.sessionState); + console.assert(payload.segmentState in WebInspector.ReplayManager.SegmentState, "Unknown segment state: " + payload.segmentState); + + instance._activeSessionIdentifier = payload.sessionIdentifier; + instance._activeSegmentIdentifier = payload.segmentIdentifier; + instance._sessionState = WebInspector.ReplayManager.SessionState[payload.sessionState]; + instance._segmentState = WebInspector.ReplayManager.SegmentState[payload.segmentState]; + instance._currentPosition = payload.replayPosition; + + instance._initialized = true; + }).then(function() { + return ReplayAgent.getAvailableSessions(); + }).then(function(payload) { + for (var sessionId of payload.ids) + instance.sessionCreated(sessionId); + }).catch(function(error) { + console.error("ReplayManager initialization failed: ", error); + throw error; + }); + } + } + + // Public + + // The following state is invalid unless called from a function that's chained + // to the (resolved) ReplayManager.waitUntilInitialized promise. + get sessionState() + { + console.assert(this._initialized); + return this._sessionState; + } + + get segmentState() + { + console.assert(this._initialized); + return this._segmentState; + } + + get activeSessionIdentifier() + { + console.assert(this._initialized); + return this._activeSessionIdentifier; + } + + get activeSegmentIdentifier() + { + console.assert(this._initialized); + return this._activeSegmentIdentifier; + } + + get playbackSpeed() + { + console.assert(this._initialized); + return this._playbackSpeed; + } + + set playbackSpeed(value) + { + console.assert(this._initialized); + this._playbackSpeed = value; + } + + get currentPosition() + { + console.assert(this._initialized); + return this._currentPosition; + } + + // These return promises even if the relevant instance is already created. + waitUntilInitialized() // --> () + { + return this._initializationPromise; + } + + // Return a promise that resolves to a session, if it exists. + getSession(sessionId) // --> (WebInspector.ReplaySession) + { + if (this._sessionPromises.has(sessionId)) + return this._sessionPromises.get(sessionId); + + var newPromise = ReplayAgent.getSessionData(sessionId) + .then(function(payload) { + return Promise.resolve(WebInspector.ReplaySession.fromPayload(sessionId, payload)); + }); + + this._sessionPromises.set(sessionId, newPromise); + return newPromise; + } + + // Return a promise that resolves to a session segment, if it exists. + getSegment(segmentId) // --> (WebInspector.ReplaySessionSegment) + { + if (this._segmentPromises.has(segmentId)) + return this._segmentPromises.get(segmentId); + + var newPromise = ReplayAgent.getSegmentData(segmentId) + .then(function(payload) { + return Promise.resolve(new WebInspector.ReplaySessionSegment(segmentId, payload)); + }); + + this._segmentPromises.set(segmentId, newPromise); + return newPromise; + } + + // Switch to the specified session. + // Returns a promise that resolves when the switch completes. + switchSession(sessionId) // --> () + { + var manager = this; + var result = this.waitUntilInitialized(); + + if (this.sessionState === WebInspector.ReplayManager.SessionState.Capturing) { + result = result.then(function() { + return WebInspector.replayManager.stopCapturing(); + }); + } + + if (this.sessionState === WebInspector.ReplayManager.SessionState.Replaying) { + result = result.then(function() { + return WebInspector.replayManager.cancelPlayback(); + }); + } + + result = result.then(function() { + console.assert(manager.sessionState === WebInspector.ReplayManager.SessionState.Inactive); + console.assert(manager.segmentState === WebInspector.ReplayManager.SegmentState.Unloaded); + + return manager.getSession(sessionId); + }).then(function ensureSessionDataIsLoaded(session) { + return ReplayAgent.switchSession(session.identifier); + }).catch(function(error) { + console.error("Failed to switch to session: ", error); + throw error; + }); + + return result; + } + + // Start capturing into the current session as soon as possible. + // Returns a promise that resolves when capturing begins. + startCapturing() // --> () + { + var manager = this; + var result = this.waitUntilInitialized(); + + if (this.sessionState === WebInspector.ReplayManager.SessionState.Capturing) + return result; // Already capturing. + + if (this.sessionState === WebInspector.ReplayManager.SessionState.Replaying) { + result = result.then(function() { + return WebInspector.replayManager.cancelPlayback(); + }); + } + + result = result.then(this._suppressBreakpointsAndResumeIfNeeded()); + + result = result.then(function() { + console.assert(manager.sessionState === WebInspector.ReplayManager.SessionState.Inactive); + console.assert(manager.segmentState === WebInspector.ReplayManager.SegmentState.Unloaded); + + return ReplayAgent.startCapturing(); + }).catch(function(error) { + console.error("Failed to start capturing: ", error); + throw error; + }); + + return result; + } + + // Stop capturing into the current session as soon as possible. + // Returns a promise that resolves when capturing ends. + stopCapturing() // --> () + { + console.assert(this.sessionState === WebInspector.ReplayManager.SessionState.Capturing, "Cannot stop capturing unless capture is active."); + console.assert(this.segmentState === WebInspector.ReplayManager.SegmentState.Appending); + + return ReplayAgent.stopCapturing() + .catch(function(error) { + console.error("Failed to stop capturing: ", error); + throw error; + }); + } + + // Pause playback as soon as possible. + // Returns a promise that resolves when playback is paused. + pausePlayback() // --> () + { + console.assert(this.sessionState !== WebInspector.ReplayManager.SessionState.Capturing, "Cannot pause playback while capturing."); + + var manager = this; + var result = this.waitUntilInitialized(); + + if (this.sessionState === WebInspector.ReplayManager.SessionState.Inactive) + return result; // Already stopped. + + if (this.segmentState !== WebInspector.ReplayManager.SegmentState.Dispatching) + return result; // Already stopped. + + result = result.then(function() { + console.assert(manager.sessionState === WebInspector.ReplayManager.SessionState.Replaying); + console.assert(manager.segmentState === WebInspector.ReplayManager.SegmentState.Dispatching); + + return ReplayAgent.pausePlayback(); + }).catch(function(error) { + console.error("Failed to pause playback: ", error); + throw error; + }); + + return result; + } + + // Pause playback and unload the current session segment as soon as possible. + // Returns a promise that resolves when the current segment is unloaded. + cancelPlayback() // --> () + { + console.assert(this.sessionState !== WebInspector.ReplayManager.SessionState.Capturing, "Cannot stop playback while capturing."); + + var manager = this; + var result = this.waitUntilInitialized(); + + if (this.sessionState === WebInspector.ReplayManager.SessionState.Inactive) + return result; // Already stopped. + + result = result.then(function() { + console.assert(manager.sessionState === WebInspector.ReplayManager.SessionState.Replaying); + console.assert(manager.segmentState !== WebInspector.ReplayManager.SegmentState.Appending); + + return ReplayAgent.cancelPlayback(); + }).catch(function(error) { + console.error("Failed to stop playback: ", error); + throw error; + }); + + return result; + } + + // Replay to the specified position as soon as possible using the current replay speed. + // Returns a promise that resolves when replay has begun (NOT when the position is reached). + replayToPosition(replayPosition) // --> () + { + console.assert(replayPosition instanceof WebInspector.ReplayPosition, "Cannot replay to a position while capturing."); + + var manager = this; + var result = this.waitUntilInitialized(); + + if (this.sessionState === WebInspector.ReplayManager.SessionState.Capturing) { + result = result.then(function() { + return WebInspector.replayManager.stopCapturing(); + }); + } + + result = result.then(this._suppressBreakpointsAndResumeIfNeeded()); + + result = result.then(function() { + console.assert(manager.sessionState !== WebInspector.ReplayManager.SessionState.Capturing); + console.assert(manager.segmentState !== WebInspector.ReplayManager.SegmentState.Appending); + + return ReplayAgent.replayToPosition(replayPosition, manager.playbackSpeed === WebInspector.ReplayManager.PlaybackSpeed.FastForward); + }).catch(function(error) { + console.error("Failed to start playback to position: ", replayPosition, error); + throw error; + }); + + return result; + } + + // Replay to the end of the session as soon as possible using the current replay speed. + // Returns a promise that resolves when replay has begun (NOT when the end is reached). + replayToCompletion() // --> () + { + var manager = this; + var result = this.waitUntilInitialized(); + + if (this.segmentState === WebInspector.ReplayManager.SegmentState.Dispatching) + return result; // Already running. + + if (this.sessionState === WebInspector.ReplayManager.SessionState.Capturing) { + result = result.then(function() { + return WebInspector.replayManager.stopCapturing(); + }); + } + + result = result.then(this._suppressBreakpointsAndResumeIfNeeded()); + + result = result.then(function() { + console.assert(manager.sessionState !== WebInspector.ReplayManager.SessionState.Capturing); + console.assert(manager.segmentState === WebInspector.ReplayManager.SegmentState.Loaded || manager.segmentState === WebInspector.ReplayManager.SegmentState.Unloaded); + + return ReplayAgent.replayToCompletion(manager.playbackSpeed === WebInspector.ReplayManager.PlaybackSpeed.FastForward); + }).catch(function(error) { + console.error("Failed to start playback to completion: ", error); + throw error; + }); + + return result; + } + + // Protected (called by ReplayObserver) + + // Since these methods update session and segment state, they depend on the manager + // being properly initialized. So, each function body is prepended with a retry guard. + // This makes call sites simpler and avoids an extra event loop turn in the common case. + + captureStarted() + { + if (!this._initialized) + return this.waitUntilInitialized().then(this.captureStarted.bind(this)); + + this._changeSessionState(WebInspector.ReplayManager.SessionState.Capturing); + + this.dispatchEventToListeners(WebInspector.ReplayManager.Event.CaptureStarted); + } + + captureStopped() + { + if (!this._initialized) + return this.waitUntilInitialized().then(this.captureStopped.bind(this)); + + this._changeSessionState(WebInspector.ReplayManager.SessionState.Inactive); + this._changeSegmentState(WebInspector.ReplayManager.SegmentState.Unloaded); + + if (this._breakpointsWereSuppressed) { + delete this._breakpointsWereSuppressed; + WebInspector.debuggerManager.breakpointsEnabled = true; + } + + this.dispatchEventToListeners(WebInspector.ReplayManager.Event.CaptureStopped); + } + + playbackStarted() + { + if (!this._initialized) + return this.waitUntilInitialized().then(this.playbackStarted.bind(this)); + + if (this.sessionState === WebInspector.ReplayManager.SessionState.Inactive) + this._changeSessionState(WebInspector.ReplayManager.SessionState.Replaying); + + this._changeSegmentState(WebInspector.ReplayManager.SegmentState.Dispatching); + + this.dispatchEventToListeners(WebInspector.ReplayManager.Event.PlaybackStarted); + } + + playbackHitPosition(replayPosition, timestamp) + { + if (!this._initialized) + return this.waitUntilInitialized().then(this.playbackHitPosition.bind(this, replayPosition, timestamp)); + + console.assert(this.sessionState === WebInspector.ReplayManager.SessionState.Replaying); + console.assert(this.segmentState === WebInspector.ReplayManager.SegmentState.Dispatching); + console.assert(replayPosition instanceof WebInspector.ReplayPosition); + + this._currentPosition = replayPosition; + this.dispatchEventToListeners(WebInspector.ReplayManager.Event.PlaybackPositionChanged); + } + + playbackPaused(position) + { + if (!this._initialized) + return this.waitUntilInitialized().then(this.playbackPaused.bind(this, position)); + + console.assert(this.sessionState === WebInspector.ReplayManager.SessionState.Replaying); + this._changeSegmentState(WebInspector.ReplayManager.SegmentState.Loaded); + + if (this._breakpointsWereSuppressed) { + delete this._breakpointsWereSuppressed; + WebInspector.debuggerManager.breakpointsEnabled = true; + } + + this.dispatchEventToListeners(WebInspector.ReplayManager.Event.PlaybackPaused); + } + + playbackFinished() + { + if (!this._initialized) + return this.waitUntilInitialized().then(this.playbackFinished.bind(this)); + + this._changeSessionState(WebInspector.ReplayManager.SessionState.Inactive); + console.assert(this.segmentState === WebInspector.ReplayManager.SegmentState.Unloaded); + + if (this._breakpointsWereSuppressed) { + delete this._breakpointsWereSuppressed; + WebInspector.debuggerManager.breakpointsEnabled = true; + } + + this.dispatchEventToListeners(WebInspector.ReplayManager.Event.PlaybackFinished); + } + + sessionCreated(sessionId) + { + if (!this._initialized) + return this.waitUntilInitialized().then(this.sessionCreated.bind(this, sessionId)); + + console.assert(!this._sessions.has(sessionId), "Tried to add duplicate session identifier:", sessionId); + var sessionMap = this._sessions; + this.getSession(sessionId) + .then(function(session) { + sessionMap.set(sessionId, session); + }).catch(function(error) { + console.error("Error obtaining session data: ", error); + throw error; + }); + + this.dispatchEventToListeners(WebInspector.ReplayManager.Event.SessionAdded, {sessionId}); + } + + sessionModified(sessionId) + { + if (!this._initialized) + return this.waitUntilInitialized().then(this.sessionModified.bind(this, sessionId)); + + this.getSession(sessionId).then(function(session) { + session.segmentsChanged(); + }); + } + + sessionRemoved(sessionId) + { + if (!this._initialized) + return this.waitUntilInitialized().then(this.sessionRemoved.bind(this, sessionId)); + + console.assert(this._sessions.has(sessionId), "Unknown session identifier:", sessionId); + + if (!this._sessionPromises.has(sessionId)) + return; + + var manager = this; + + this.getSession(sessionId) + .catch(function(error) { + // Wait for any outstanding promise to settle so it doesn't get re-added. + }).then(function() { + manager._sessionPromises.delete(sessionId); + var removedSession = manager._sessions.take(sessionId); + console.assert(removedSession); + manager.dispatchEventToListeners(WebInspector.ReplayManager.Event.SessionRemoved, {removedSession}); + }); + } + + segmentCreated(segmentId) + { + if (!this._initialized) + return this.waitUntilInitialized().then(this.segmentCreated.bind(this, segmentId)); + + console.assert(!this._segments.has(segmentId), "Tried to add duplicate segment identifier:", segmentId); + + this._changeSegmentState(WebInspector.ReplayManager.SegmentState.Appending); + + // Create a dummy segment, and don't try to load any data for it. It will + // be removed once the segment is complete, and then its data will be fetched. + var incompleteSegment = new WebInspector.IncompleteSessionSegment(segmentId); + this._segments.set(segmentId, incompleteSegment); + this._segmentPromises.set(segmentId, Promise.resolve(incompleteSegment)); + + this.dispatchEventToListeners(WebInspector.ReplayManager.Event.SessionSegmentAdded, {segmentIdentifier: segmentId}); + } + + segmentCompleted(segmentId) + { + if (!this._initialized) + return this.waitUntilInitialized().then(this.segmentCompleted.bind(this, segmentId)); + + var placeholderSegment = this._segments.take(segmentId); + console.assert(placeholderSegment instanceof WebInspector.IncompleteSessionSegment); + this._segmentPromises.delete(segmentId); + + var segmentMap = this._segments; + this.getSegment(segmentId) + .then(function(segment) { + segmentMap.set(segmentId, segment); + }).catch(function(error) { + console.error("Error obtaining segment data: ", error); + throw error; + }); + } + + segmentRemoved(segmentId) + { + if (!this._initialized) + return this.waitUntilInitialized().then(this.segmentRemoved.bind(this, segmentId)); + + console.assert(this._segments.has(segmentId), "Unknown segment identifier:", segmentId); + + if (!this._segmentPromises.has(segmentId)) + return; + + var manager = this; + + // Wait for any outstanding promise to settle so it doesn't get re-added. + this.getSegment(segmentId) + .catch(function(error) { + return Promise.resolve(); + }).then(function() { + manager._segmentPromises.delete(segmentId); + var removedSegment = manager._segments.take(segmentId); + console.assert(removedSegment); + manager.dispatchEventToListeners(WebInspector.ReplayManager.Event.SessionSegmentRemoved, {removedSegment}); + }); + } + + segmentLoaded(segmentId) + { + if (!this._initialized) + return this.waitUntilInitialized().then(this.segmentLoaded.bind(this, segmentId)); + + console.assert(this._segments.has(segmentId), "Unknown segment identifier:", segmentId); + + console.assert(this.sessionState !== WebInspector.ReplayManager.SessionState.Capturing); + this._changeSegmentState(WebInspector.ReplayManager.SegmentState.Loaded); + + var previousIdentifier = this._activeSegmentIdentifier; + this._activeSegmentIdentifier = segmentId; + this.dispatchEventToListeners(WebInspector.ReplayManager.Event.ActiveSegmentChanged, {previousSegmentIdentifier: previousIdentifier}); + } + + segmentUnloaded() + { + if (!this._initialized) + return this.waitUntilInitialized().then(this.segmentUnloaded.bind(this)); + + console.assert(this.sessionState === WebInspector.ReplayManager.SessionState.Replaying); + this._changeSegmentState(WebInspector.ReplayManager.SegmentState.Unloaded); + + var previousIdentifier = this._activeSegmentIdentifier; + this._activeSegmentIdentifier = null; + this.dispatchEventToListeners(WebInspector.ReplayManager.Event.ActiveSegmentChanged, {previousSegmentIdentifier: previousIdentifier}); + } + + // Private + + _changeSessionState(newState) + { + // Warn about no-op state changes. We shouldn't be seeing them. + var isAllowed = this._sessionState !== newState; + + switch (this._sessionState) { + case WebInspector.ReplayManager.SessionState.Capturing: + isAllowed &= newState === WebInspector.ReplayManager.SessionState.Inactive; + break; + + case WebInspector.ReplayManager.SessionState.Replaying: + isAllowed &= newState === WebInspector.ReplayManager.SessionState.Inactive; + break; + } + + console.assert(isAllowed, "Invalid session state change: ", this._sessionState, " to ", newState); + if (isAllowed) + this._sessionState = newState; + } + + _changeSegmentState(newState) + { + // Warn about no-op state changes. We shouldn't be seeing them. + var isAllowed = this._segmentState !== newState; + + switch (this._segmentState) { + case WebInspector.ReplayManager.SegmentState.Appending: + isAllowed &= newState === WebInspector.ReplayManager.SegmentState.Unloaded; + break; + case WebInspector.ReplayManager.SegmentState.Unloaded: + isAllowed &= newState === WebInspector.ReplayManager.SegmentState.Appending || newState === WebInspector.ReplayManager.SegmentState.Loaded; + break; + case WebInspector.ReplayManager.SegmentState.Loaded: + isAllowed &= newState === WebInspector.ReplayManager.SegmentState.Unloaded || newState === WebInspector.ReplayManager.SegmentState.Dispatching; + break; + case WebInspector.ReplayManager.SegmentState.Dispatching: + isAllowed &= newState === WebInspector.ReplayManager.SegmentState.Loaded; + break; + } + + console.assert(isAllowed, "Invalid segment state change: ", this._segmentState, " to ", newState); + if (isAllowed) + this._segmentState = newState; + } + + _suppressBreakpointsAndResumeIfNeeded() + { + var manager = this; + + return new Promise(function(resolve, reject) { + manager._breakpointsWereSuppressed = WebInspector.debuggerManager.breakpointsEnabled; + WebInspector.debuggerManager.breakpointsEnabled = false; + + return WebInspector.debuggerManager.resume(); + }); + } +}; + +WebInspector.ReplayManager.Event = { + CaptureStarted: "replay-manager-capture-started", + CaptureStopped: "replay-manager-capture-stopped", + + PlaybackStarted: "replay-manager-playback-started", + PlaybackPaused: "replay-manager-playback-paused", + PlaybackFinished: "replay-manager-playback-finished", + PlaybackPositionChanged: "replay-manager-play-back-position-changed", + + ActiveSessionChanged: "replay-manager-active-session-changed", + ActiveSegmentChanged: "replay-manager-active-segment-changed", + + SessionSegmentAdded: "replay-manager-session-segment-added", + SessionSegmentRemoved: "replay-manager-session-segment-removed", + + SessionAdded: "replay-manager-session-added", + SessionRemoved: "replay-manager-session-removed", +}; + +WebInspector.ReplayManager.SessionState = { + Capturing: "replay-manager-session-state-capturing", + Inactive: "replay-manager-session-state-inactive", + Replaying: "replay-manager-session-state-replaying", +}; + +WebInspector.ReplayManager.SegmentState = { + Appending: "replay-manager-segment-state-appending", + Unloaded: "replay-manager-segment-state-unloaded", + Loaded: "replay-manager-segment-state-loaded", + Dispatching: "replay-manager-segment-state-dispatching", +}; + +WebInspector.ReplayManager.PlaybackSpeed = { + RealTime: "replay-manager-playback-speed-real-time", + FastForward: "replay-manager-playback-speed-fast-forward", +}; diff --git a/Source/WebInspectorUI/UserInterface/Controllers/ResourceQueryController.js b/Source/WebInspectorUI/UserInterface/Controllers/ResourceQueryController.js new file mode 100644 index 000000000..171165f32 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/ResourceQueryController.js @@ -0,0 +1,203 @@ +/* + * Copyright (C) 2016 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.ResourceQueryController = class ResourceQueryController extends WebInspector.Object +{ + constructor() + { + super(); + + this._resourceDataMap = new Map; + } + + // Public + + addResource(resource) + { + this._resourceDataMap.set(resource, {}); + } + + removeResource(resource) + { + this._resourceDataMap.delete(resource); + } + + reset() + { + this._resourceDataMap.clear(); + } + + executeQuery(query) + { + if (!query || !this._resourceDataMap.size) + return []; + + query = query.removeWhitespace().toLowerCase(); + + let cookie = null; + if (query.includes(":")) { + let [newQuery, lineNumber, columnNumber] = query.split(":"); + query = newQuery; + lineNumber = lineNumber ? parseInt(lineNumber, 10) - 1 : 0; + columnNumber = columnNumber ? parseInt(columnNumber, 10) - 1 : 0; + cookie = {lineNumber, columnNumber}; + } + + let results = []; + for (let [resource, cachedData] of this._resourceDataMap) { + if (!cachedData.searchString) { + let displayName = resource.displayName; + cachedData.searchString = displayName.toLowerCase(); + cachedData.specialCharacterIndices = this._findSpecialCharacterIndices(displayName); + } + + let matches = this._findQueryMatches(query, cachedData.searchString, cachedData.specialCharacterIndices); + if (matches.length) + results.push(new WebInspector.ResourceQueryResult(resource, matches, cookie)); + } + + // Resources are sorted in descending order by rank. Resources of equal + // rank are sorted by display name. + return results.sort((a, b) => { + if (a.rank === b.rank) + return a.resource.displayName.localeCompare(b.resource.displayName); + return b.rank - a.rank; + }); + } + + // Private + + _findQueryMatches(query, searchString, specialCharacterIndices) + { + let matches = []; + let queryIndex = 0; + let searchIndex = 0; + let specialIndex = 0; + let deadBranches = new Array(query.length).fill(Infinity); + let type = WebInspector.ResourceQueryMatch.Type.Special; + + function pushMatch(index) + { + matches.push(new WebInspector.ResourceQueryMatch(type, index, queryIndex)); + searchIndex = index + 1; + queryIndex++; + } + + function matchNextSpecialCharacter() + { + if (specialIndex >= specialCharacterIndices.length) + return false; + + let originalSpecialIndex = specialIndex; + while (specialIndex < specialCharacterIndices.length) { + // Normal character matching can move past special characters, + // so advance the special character index if it's before the + // current search string position. + let index = specialCharacterIndices[specialIndex++]; + if (index < searchIndex) + continue; + + if (query[queryIndex] === searchString[index]) { + pushMatch(index); + return true; + } + } + + specialIndex = originalSpecialIndex; + return false; + } + + function backtrack() + { + while (matches.length) { + queryIndex--; + + let lastMatch = matches.pop(); + if (lastMatch.type !== WebInspector.ResourceQueryMatch.Type.Special) + continue; + + deadBranches[lastMatch.queryIndex] = lastMatch.index; + searchIndex = matches.lastValue ? matches.lastValue.index + 1 : 0; + return true; + } + + return false; + } + + while (queryIndex < query.length && searchIndex < searchString.length) { + if (type === WebInspector.ResourceQueryMatch.Type.Special && !matchNextSpecialCharacter()) + type = WebInspector.ResourceQueryMatch.Type.Normal; + + if (type === WebInspector.ResourceQueryMatch.Type.Normal) { + let index = searchString.indexOf(query[queryIndex], searchIndex); + if (index >= 0 && index < deadBranches[queryIndex]) { + pushMatch(index); + type = WebInspector.ResourceQueryMatch.Type.Special; + } else if (!backtrack()) + return []; + } + } + + if (queryIndex < query.length) + return []; + + return matches; + } + + _findSpecialCharacterIndices(string) + { + if (!string.length) + return []; + + const filenameSeparators = "_.-"; + + // Special characters include the following: + // 1. The first character. + // 2. Uppercase characters that follow a lowercase letter. + // 3. Filename separators and the first character following the separator. + let indices = [0]; + + for (let i = 1; i < string.length; ++i) { + let character = string[i]; + let isSpecial = false; + + if (filenameSeparators.includes(character)) + isSpecial = true; + else { + let previousCharacter = string[i - 1]; + let previousCharacterIsSeparator = filenameSeparators.includes(previousCharacter); + if (previousCharacterIsSeparator) + isSpecial = true; + else if (character.isUpperCase() && previousCharacter.isLowerCase()) + isSpecial = true; + } + + if (isSpecial) + indices.push(i); + } + + return indices; + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Controllers/RuntimeManager.js b/Source/WebInspectorUI/UserInterface/Controllers/RuntimeManager.js new file mode 100644 index 000000000..a10541422 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/RuntimeManager.js @@ -0,0 +1,262 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.RuntimeManager = class RuntimeManager extends WebInspector.Object +{ + constructor() + { + super(); + + // Enable the RuntimeAgent to receive notification of execution contexts. + RuntimeAgent.enable(); + + this._activeExecutionContext = WebInspector.mainTarget.executionContext; + + WebInspector.Frame.addEventListener(WebInspector.Frame.Event.ExecutionContextsCleared, this._frameExecutionContextsCleared, this); + } + + // Public + + get activeExecutionContext() + { + return this._activeExecutionContext; + } + + set activeExecutionContext(executionContext) + { + if (this._activeExecutionContext === executionContext) + return; + + this._activeExecutionContext = executionContext; + + this.dispatchEventToListeners(WebInspector.RuntimeManager.Event.ActiveExecutionContextChanged); + } + + evaluateInInspectedWindow(expression, options, callback) + { + let {objectGroup, includeCommandLineAPI, doNotPauseOnExceptionsAndMuteConsole, returnByValue, generatePreview, saveResult, sourceURLAppender} = options; + + includeCommandLineAPI = includeCommandLineAPI || false; + doNotPauseOnExceptionsAndMuteConsole = doNotPauseOnExceptionsAndMuteConsole || false; + returnByValue = returnByValue || false; + generatePreview = generatePreview || false; + saveResult = saveResult || false; + sourceURLAppender = sourceURLAppender || appendWebInspectorSourceURL; + + console.assert(objectGroup, "RuntimeManager.evaluateInInspectedWindow should always be called with an objectGroup"); + console.assert(typeof sourceURLAppender === "function"); + + if (!expression) { + // There is no expression, so the completion should happen against global properties. + expression = "this"; + } else if (/^\s*\{/.test(expression) && /\}\s*$/.test(expression)) { + // Transform {a:1} to ({a:1}) so it is treated like an object literal instead of a block with a label. + expression = "(" + expression + ")"; + } else if (/\bawait\b/.test(expression)) { + // Transform `await ` into an async function assignment. + expression = this._tryApplyAwaitConvenience(expression); + } + + expression = sourceURLAppender(expression); + + let target = this._activeExecutionContext.target; + let executionContextId = this._activeExecutionContext.id; + + if (WebInspector.debuggerManager.activeCallFrame) { + target = WebInspector.debuggerManager.activeCallFrame.target; + executionContextId = target.executionContext.id; + } + + function evalCallback(error, result, wasThrown, savedResultIndex) + { + this.dispatchEventToListeners(WebInspector.RuntimeManager.Event.DidEvaluate, {objectGroup}); + + if (error) { + console.error(error); + callback(null, false); + return; + } + + if (returnByValue) + callback(null, wasThrown, wasThrown ? null : result, savedResultIndex); + else + callback(WebInspector.RemoteObject.fromPayload(result, target), wasThrown, savedResultIndex); + } + + if (WebInspector.debuggerManager.activeCallFrame) { + // COMPATIBILITY (iOS 8): "saveResult" did not exist. + target.DebuggerAgent.evaluateOnCallFrame.invoke({callFrameId: WebInspector.debuggerManager.activeCallFrame.id, expression, objectGroup, includeCommandLineAPI, doNotPauseOnExceptionsAndMuteConsole, returnByValue, generatePreview, saveResult}, evalCallback.bind(this), target.DebuggerAgent); + return; + } + + // COMPATIBILITY (iOS 8): "saveResult" did not exist. + target.RuntimeAgent.evaluate.invoke({expression, objectGroup, includeCommandLineAPI, doNotPauseOnExceptionsAndMuteConsole, contextId: executionContextId, returnByValue, generatePreview, saveResult}, evalCallback.bind(this), target.RuntimeAgent); + } + + saveResult(remoteObject, callback) + { + console.assert(remoteObject instanceof WebInspector.RemoteObject); + + // COMPATIBILITY (iOS 8): Runtime.saveResult did not exist. + if (!RuntimeAgent.saveResult) { + callback(undefined); + return; + } + + function mycallback(error, savedResultIndex) + { + callback(savedResultIndex); + } + + let target = this._activeExecutionContext.target; + let executionContextId = this._activeExecutionContext.id; + + if (remoteObject.objectId) + target.RuntimeAgent.saveResult(remoteObject.asCallArgument(), mycallback); + else + target.RuntimeAgent.saveResult(remoteObject.asCallArgument(), executionContextId, mycallback); + } + + getPropertiesForRemoteObject(objectId, callback) + { + this._activeExecutionContext.target.RuntimeAgent.getProperties(objectId, function(error, result) { + if (error) { + callback(error); + return; + } + + let properties = new Map; + for (let property of result) + properties.set(property.name, property); + + callback(null, properties); + }); + } + + // Private + + _frameExecutionContextsCleared(event) + { + let contexts = event.data.contexts || []; + + let currentContextWasDestroyed = contexts.some((context) => context.id === this._activeExecutionContext.id); + if (currentContextWasDestroyed) + this.activeExecutionContext = WebInspector.mainTarget.executionContext; + } + + _tryApplyAwaitConvenience(originalExpression) + { + let esprimaSyntaxTree; + + // Do not transform if the original code parses just fine. + try { + esprima.parse(originalExpression); + return originalExpression; + } catch (error) { } + + // Do not transform if the async function version does not parse. + try { + esprimaSyntaxTree = esprima.parse("(async function(){" + originalExpression + "})"); + } catch (error) { + return originalExpression; + } + + // Assert expected AST produced by our wrapping code. + console.assert(esprimaSyntaxTree.type === "Program"); + console.assert(esprimaSyntaxTree.body.length === 1); + console.assert(esprimaSyntaxTree.body[0].type === "ExpressionStatement"); + console.assert(esprimaSyntaxTree.body[0].expression.type === "FunctionExpression"); + console.assert(esprimaSyntaxTree.body[0].expression.async); + console.assert(esprimaSyntaxTree.body[0].expression.body.type === "BlockStatement"); + + // Do not transform if there is more than one statement. + let asyncFunctionBlock = esprimaSyntaxTree.body[0].expression.body; + if (asyncFunctionBlock.body.length !== 1) + return originalExpression; + + // Extract the variable name for transformation. + let variableName; + let anonymous = false; + let declarationKind = "var"; + let awaitPortion; + let statement = asyncFunctionBlock.body[0]; + if (statement.type === "ExpressionStatement" + && statement.expression.type === "AwaitExpression") { + // await + anonymous = true; + } else if (statement.type === "ExpressionStatement" + && statement.expression.type === "AssignmentExpression" + && statement.expression.right.type === "AwaitExpression" + && statement.expression.left.type === "Identifier") { + // x = await + variableName = statement.expression.left.name; + awaitPortion = originalExpression.substring(originalExpression.indexOf("await")); + } else if (statement.type === "VariableDeclaration" + && statement.declarations.length === 1 + && statement.declarations[0].init.type === "AwaitExpression" + && statement.declarations[0].id.type === "Identifier") { + // var x = await + variableName = statement.declarations[0].id.name; + declarationKind = statement.kind; + awaitPortion = originalExpression.substring(originalExpression.indexOf("await")); + } else { + // Do not transform if this was not one of the simple supported syntaxes. + return originalExpression; + } + + if (anonymous) { + return ` +(async function() { + try { + let result = ${originalExpression}; + console.info("%o", result); + } catch (e) { + console.error(e); + } +})(); +undefined`; + } + + return `${declarationKind} ${variableName}; +(async function() { + try { + ${variableName} = ${awaitPortion}; + console.info("%o", ${variableName}); + } catch (e) { + console.error(e); + } +})(); +undefined;`; + } +}; + +WebInspector.RuntimeManager.ConsoleObjectGroup = "console"; +WebInspector.RuntimeManager.TopLevelExecutionContextIdentifier = undefined; + +WebInspector.RuntimeManager.Event = { + DidEvaluate: Symbol("runtime-manager-did-evaluate"), + DefaultExecutionContextChanged: Symbol("runtime-manager-default-execution-context-changed"), + ActiveExecutionContextChanged: Symbol("runtime-manager-active-execution-context-changed"), +}; diff --git a/Source/WebInspectorUI/UserInterface/Controllers/SourceMapManager.js b/Source/WebInspectorUI/UserInterface/Controllers/SourceMapManager.js new file mode 100644 index 000000000..6bb8cefba --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/SourceMapManager.js @@ -0,0 +1,186 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.SourceMapManager = class SourceMapManager extends WebInspector.Object +{ + constructor() + { + super(); + + this._sourceMapURLMap = {}; + this._downloadingSourceMaps = {}; + + WebInspector.Frame.addEventListener(WebInspector.Frame.Event.MainResourceDidChange, this._mainResourceDidChange, this); + } + + // Public + + sourceMapForURL(sourceMapURL) + { + return this._sourceMapURLMap[sourceMapURL]; + } + + downloadSourceMap(sourceMapURL, baseURL, originalSourceCode) + { + // The baseURL could have come from a "//# sourceURL". Attempt to get a + // reasonable absolute URL for the base by using the main resource's URL. + if (WebInspector.frameResourceManager.mainFrame) + baseURL = absoluteURL(baseURL, WebInspector.frameResourceManager.mainFrame.url); + + if (sourceMapURL.startsWith("data:")) { + this._loadAndParseSourceMap(sourceMapURL, baseURL, originalSourceCode); + return; + } + + sourceMapURL = absoluteURL(sourceMapURL, baseURL); + if (!sourceMapURL) + return; + + console.assert(originalSourceCode.url); + if (!originalSourceCode.url) + return; + + // FIXME: Source Maps: Better handle when multiple resources reference the same SourceMap + + if (sourceMapURL in this._sourceMapURLMap) + return; + + if (sourceMapURL in this._downloadingSourceMaps) + return; + + function loadAndParseSourceMap() + { + this._loadAndParseSourceMap(sourceMapURL, baseURL, originalSourceCode); + } + + if (!WebInspector.frameResourceManager.mainFrame) { + // If we don't have a main frame, then we are likely in the middle of building the resource tree. + // Delaying until the next runloop is enough in this case to then start loading the source map. + setTimeout(loadAndParseSourceMap.bind(this), 0); + return; + } + + loadAndParseSourceMap.call(this); + } + + // Private + + _loadAndParseSourceMap(sourceMapURL, baseURL, originalSourceCode) + { + this._downloadingSourceMaps[sourceMapURL] = true; + + function sourceMapLoaded(error, content, mimeType, statusCode) + { + if (error || statusCode >= 400) { + this._loadAndParseFailed(sourceMapURL); + return; + } + + if (content.slice(0, 3) === ")]}") { + var firstNewlineIndex = content.indexOf("\n"); + if (firstNewlineIndex === -1) { + this._loadAndParseFailed(sourceMapURL); + return; + } + + content = content.substring(firstNewlineIndex); + } + + try { + var payload = JSON.parse(content); + var baseURL = sourceMapURL.startsWith("data:") ? originalSourceCode.url : sourceMapURL; + var sourceMap = new WebInspector.SourceMap(baseURL, payload, originalSourceCode); + this._loadAndParseSucceeded(sourceMapURL, sourceMap); + } catch (e) { + this._loadAndParseFailed(sourceMapURL); + } + } + + if (sourceMapURL.startsWith("data:")) { + let {mimeType, base64, data} = parseDataURL(sourceMapURL); + let content = base64 ? atob(data) : data; + sourceMapLoaded.call(this, null, content, mimeType, 0); + return; + } + + // COMPATIBILITY (iOS 7): Network.loadResource did not exist. + // Also, JavaScript Debuggable may reach this. + if (!window.NetworkAgent || !NetworkAgent.loadResource) { + this._loadAndParseFailed(sourceMapURL); + return; + } + + var frameIdentifier = null; + if (originalSourceCode instanceof WebInspector.Resource && originalSourceCode.parentFrame) + frameIdentifier = originalSourceCode.parentFrame.id; + + if (!frameIdentifier) + frameIdentifier = WebInspector.frameResourceManager.mainFrame.id; + + NetworkAgent.loadResource(frameIdentifier, sourceMapURL, sourceMapLoaded.bind(this)); + } + + _loadAndParseFailed(sourceMapURL) + { + delete this._downloadingSourceMaps[sourceMapURL]; + } + + _loadAndParseSucceeded(sourceMapURL, sourceMap) + { + if (!(sourceMapURL in this._downloadingSourceMaps)) + return; + + delete this._downloadingSourceMaps[sourceMapURL]; + + this._sourceMapURLMap[sourceMapURL] = sourceMap; + + var sources = sourceMap.sources(); + for (var i = 0; i < sources.length; ++i) { + var sourceMapResource = new WebInspector.SourceMapResource(sources[i], sourceMap); + sourceMap.addResource(sourceMapResource); + } + + // Associate the SourceMap with the originalSourceCode. + sourceMap.originalSourceCode.addSourceMap(sourceMap); + + // If the originalSourceCode was not a Resource, be sure to also associate with the Resource if one exists. + // FIXME: We should try to use the right frame instead of a global lookup by URL. + if (!(sourceMap.originalSourceCode instanceof WebInspector.Resource)) { + console.assert(sourceMap.originalSourceCode instanceof WebInspector.Script); + var resource = sourceMap.originalSourceCode.resource; + if (resource) + resource.addSourceMap(sourceMap); + } + } + + _mainResourceDidChange(event) + { + if (!event.target.isMainFrame()) + return; + + this._sourceMapURLMap = {}; + this._downloadingSourceMaps = {}; + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Controllers/StorageManager.js b/Source/WebInspectorUI/UserInterface/Controllers/StorageManager.js new file mode 100644 index 000000000..a267dcb85 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/StorageManager.js @@ -0,0 +1,336 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * Copyright (C) 2013 Samsung Electronics. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.StorageManager = class StorageManager extends WebInspector.Object +{ + constructor() + { + super(); + + if (window.DOMStorageAgent) + DOMStorageAgent.enable(); + if (window.DatabaseAgent) + DatabaseAgent.enable(); + if (window.IndexedDBAgent) + IndexedDBAgent.enable(); + + WebInspector.Frame.addEventListener(WebInspector.Frame.Event.MainResourceDidChange, this._mainResourceDidChange, this); + WebInspector.Frame.addEventListener(WebInspector.Frame.Event.SecurityOriginDidChange, this._securityOriginDidChange, this); + + this.initialize(); + } + + // Public + + initialize() + { + this._domStorageObjects = []; + this._databaseObjects = []; + this._indexedDatabases = []; + this._cookieStorageObjects = {}; + } + + get domStorageObjects() + { + return this._domStorageObjects; + } + + get databases() + { + return this._databaseObjects; + } + + get indexedDatabases() + { + return this._indexedDatabases; + } + + get cookieStorageObjects() + { + var cookieStorageObjects = []; + for (var host in this._cookieStorageObjects) + cookieStorageObjects.push(this._cookieStorageObjects[host]); + return cookieStorageObjects; + } + + domStorageWasAdded(id, host, isLocalStorage) + { + var domStorage = new WebInspector.DOMStorageObject(id, host, isLocalStorage); + + this._domStorageObjects.push(domStorage); + this.dispatchEventToListeners(WebInspector.StorageManager.Event.DOMStorageObjectWasAdded, {domStorage}); + } + + databaseWasAdded(id, host, name, version) + { + var database = new WebInspector.DatabaseObject(id, host, name, version); + + this._databaseObjects.push(database); + this.dispatchEventToListeners(WebInspector.StorageManager.Event.DatabaseWasAdded, {database}); + } + + itemsCleared(storageId) + { + let domStorage = this._domStorageForIdentifier(storageId); + if (domStorage) + domStorage.itemsCleared(storageId); + } + + itemRemoved(storageId, key) + { + let domStorage = this._domStorageForIdentifier(storageId); + if (domStorage) + domStorage.itemRemoved(key); + } + + itemAdded(storageId, key, value) + { + let domStorage = this._domStorageForIdentifier(storageId); + if (domStorage) + domStorage.itemAdded(key, value); + } + + itemUpdated(storageId, key, oldValue, value) + { + let domStorage = this._domStorageForIdentifier(storageId); + if (domStorage) + domStorage.itemUpdated(key, oldValue, value); + } + + inspectDatabase(id) + { + var database = this._databaseForIdentifier(id); + console.assert(database); + if (!database) + return; + this.dispatchEventToListeners(WebInspector.StorageManager.Event.DatabaseWasInspected, {database}); + } + + inspectDOMStorage(id) + { + var domStorage = this._domStorageForIdentifier(id); + console.assert(domStorage); + if (!domStorage) + return; + this.dispatchEventToListeners(WebInspector.StorageManager.Event.DOMStorageObjectWasInspected, {domStorage}); + } + + requestIndexedDatabaseData(objectStore, objectStoreIndex, startEntryIndex, maximumEntryCount, callback) + { + console.assert(window.IndexedDBAgent); + console.assert(objectStore); + console.assert(callback); + + function processData(error, entryPayloads, moreAvailable) + { + if (error) { + callback(null, false); + return; + } + + var entries = []; + + for (var entryPayload of entryPayloads) { + var entry = {}; + entry.primaryKey = WebInspector.RemoteObject.fromPayload(entryPayload.primaryKey); + entry.key = WebInspector.RemoteObject.fromPayload(entryPayload.key); + entry.value = WebInspector.RemoteObject.fromPayload(entryPayload.value); + entries.push(entry); + } + + callback(entries, moreAvailable); + } + + var requestArguments = { + securityOrigin: objectStore.parentDatabase.securityOrigin, + databaseName: objectStore.parentDatabase.name, + objectStoreName: objectStore.name, + indexName: objectStoreIndex && objectStoreIndex.name || "", + skipCount: startEntryIndex || 0, + pageSize: maximumEntryCount || 100 + }; + + IndexedDBAgent.requestData.invoke(requestArguments, processData); + } + + clearObjectStore(objectStore) + { + let securityOrigin = objectStore.parentDatabase.securityOrigin; + let databaseName = objectStore.parentDatabase.name; + let objectStoreName = objectStore.name; + + IndexedDBAgent.clearObjectStore(securityOrigin, databaseName, objectStoreName); + } + + // Private + + _domStorageForIdentifier(id) + { + for (var storageObject of this._domStorageObjects) { + // The id is an object, so we need to compare the properties using Object.shallowEqual. + if (Object.shallowEqual(storageObject.id, id)) + return storageObject; + } + + return null; + } + + _mainResourceDidChange(event) + { + console.assert(event.target instanceof WebInspector.Frame); + + if (event.target.isMainFrame()) { + // If we are dealing with the main frame, we want to clear our list of objects, because we are navigating to a new page. + this.initialize(); + this.dispatchEventToListeners(WebInspector.StorageManager.Event.Cleared); + + this._addDOMStorageIfNeeded(event.target); + this._addIndexedDBDatabasesIfNeeded(event.target); + } + + // Add the host of the frame that changed the main resource to the list of hosts there could be cookies for. + var host = parseURL(event.target.url).host; + if (!host) + return; + + if (this._cookieStorageObjects[host]) + return; + + this._cookieStorageObjects[host] = new WebInspector.CookieStorageObject(host); + this.dispatchEventToListeners(WebInspector.StorageManager.Event.CookieStorageObjectWasAdded, {cookieStorage: this._cookieStorageObjects[host]}); + } + + _addDOMStorageIfNeeded(frame) + { + if (!window.DOMStorageAgent) + return; + + // Don't show storage if we don't have a security origin (about:blank). + if (!frame.securityOrigin || frame.securityOrigin === "://") + return; + + // FIXME: Consider passing the other parts of the origin along to domStorageWasAdded. + + var localStorageIdentifier = {securityOrigin: frame.securityOrigin, isLocalStorage: true}; + if (!this._domStorageForIdentifier(localStorageIdentifier)) + this.domStorageWasAdded(localStorageIdentifier, frame.mainResource.urlComponents.host, true); + + var sessionStorageIdentifier = {securityOrigin: frame.securityOrigin, isLocalStorage: false}; + if (!this._domStorageForIdentifier(sessionStorageIdentifier)) + this.domStorageWasAdded(sessionStorageIdentifier, frame.mainResource.urlComponents.host, false); + } + + _addIndexedDBDatabasesIfNeeded(frame) + { + if (!window.IndexedDBAgent) + return; + + var securityOrigin = frame.securityOrigin; + + // Don't show storage if we don't have a security origin (about:blank). + if (!securityOrigin || securityOrigin === "://") + return; + + function processDatabaseNames(error, names) + { + if (error || !names) + return; + + for (var name of names) + IndexedDBAgent.requestDatabase(securityOrigin, name, processDatabase.bind(this)); + } + + function processDatabase(error, databasePayload) + { + if (error || !databasePayload) + return; + + var objectStores = databasePayload.objectStores.map(processObjectStore); + var indexedDatabase = new WebInspector.IndexedDatabase(databasePayload.name, securityOrigin, databasePayload.version, objectStores); + + this._indexedDatabases.push(indexedDatabase); + this.dispatchEventToListeners(WebInspector.StorageManager.Event.IndexedDatabaseWasAdded, {indexedDatabase}); + } + + function processKeyPath(keyPathPayload) + { + switch (keyPathPayload.type) { + case IndexedDBAgent.KeyPathType.Null: + return null; + case IndexedDBAgent.KeyPathType.String: + return keyPathPayload.string; + case IndexedDBAgent.KeyPathType.Array: + return keyPathPayload.array; + default: + console.error("Unknown KeyPath type:", keyPathPayload.type); + return null; + } + } + + function processObjectStore(objectStorePayload) + { + var keyPath = processKeyPath(objectStorePayload.keyPath); + var indexes = objectStorePayload.indexes.map(processObjectStoreIndex); + return new WebInspector.IndexedDatabaseObjectStore(objectStorePayload.name, keyPath, objectStorePayload.autoIncrement, indexes); + } + + function processObjectStoreIndex(objectStoreIndexPayload) + { + var keyPath = processKeyPath(objectStoreIndexPayload.keyPath); + return new WebInspector.IndexedDatabaseObjectStoreIndex(objectStoreIndexPayload.name, keyPath, objectStoreIndexPayload.unique, objectStoreIndexPayload.multiEntry); + } + + IndexedDBAgent.requestDatabaseNames(securityOrigin, processDatabaseNames.bind(this)); + } + + _securityOriginDidChange(event) + { + console.assert(event.target instanceof WebInspector.Frame); + + this._addDOMStorageIfNeeded(event.target); + this._addIndexedDBDatabasesIfNeeded(event.target); + } + + _databaseForIdentifier(id) + { + for (var i = 0; i < this._databaseObjects.length; ++i) { + if (this._databaseObjects[i].id === id) + return this._databaseObjects[i]; + } + + return null; + } +}; + +WebInspector.StorageManager.Event = { + CookieStorageObjectWasAdded: "storage-manager-cookie-storage-object-was-added", + DOMStorageObjectWasAdded: "storage-manager-dom-storage-object-was-added", + DOMStorageObjectWasInspected: "storage-dom-object-was-inspected", + DatabaseWasAdded: "storage-manager-database-was-added", + DatabaseWasInspected: "storage-object-was-inspected", + IndexedDatabaseWasAdded: "storage-manager-indexed-database-was-added", + Cleared: "storage-manager-cleared" +}; diff --git a/Source/WebInspectorUI/UserInterface/Controllers/TargetManager.js b/Source/WebInspectorUI/UserInterface/Controllers/TargetManager.js new file mode 100644 index 000000000..7e987d4dd --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/TargetManager.js @@ -0,0 +1,75 @@ +/* + * Copyright (C) 2016 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.TargetManager = class TargetManager extends WebInspector.Object +{ + constructor() + { + super(); + + console.assert(WebInspector.mainTarget); + + this._targets = new Set([WebInspector.mainTarget]); + } + + // Public + + get targets() + { + return this._targets; + } + + targetForIdentifier(targetId) + { + if (!targetId) + return null; + + for (let target of this._targets) { + if (target.identifier === targetId) + return target; + } + + return null; + } + + addTarget(target) + { + this._targets.add(target); + + this.dispatchEventToListeners(WebInspector.TargetManager.Event.TargetAdded, {target}); + } + + removeTarget(target) + { + this._targets.delete(target); + + this.dispatchEventToListeners(WebInspector.TargetManager.Event.TargetRemoved, {target}); + } +}; + +WebInspector.TargetManager.Event = { + TargetAdded: Symbol("target-manager-target-added"), + TargetRemoved: Symbol("target-manager-target-removed"), +}; diff --git a/Source/WebInspectorUI/UserInterface/Controllers/TimelineManager.js b/Source/WebInspectorUI/UserInterface/Controllers/TimelineManager.js new file mode 100644 index 000000000..e03ba9ba2 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/TimelineManager.js @@ -0,0 +1,1091 @@ +/* + * Copyright (C) 2013, 2016 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.TimelineManager = class TimelineManager extends WebInspector.Object +{ + constructor() + { + super(); + + WebInspector.Frame.addEventListener(WebInspector.Frame.Event.ProvisionalLoadStarted, this._provisionalLoadStarted, this); + WebInspector.Frame.addEventListener(WebInspector.Frame.Event.MainResourceDidChange, this._mainResourceDidChange, this); + WebInspector.Frame.addEventListener(WebInspector.Frame.Event.ResourceWasAdded, this._resourceWasAdded, this); + WebInspector.Target.addEventListener(WebInspector.Target.Event.ResourceAdded, this._resourceWasAdded, this); + + WebInspector.heapManager.addEventListener(WebInspector.HeapManager.Event.GarbageCollected, this._garbageCollected, this); + WebInspector.memoryManager.addEventListener(WebInspector.MemoryManager.Event.MemoryPressure, this._memoryPressure, this); + + this._enabledTimelineTypesSetting = new WebInspector.Setting("enabled-instrument-types", WebInspector.TimelineManager.defaultTimelineTypes()); + this._updateAutoCaptureInstruments(); + + this._persistentNetworkTimeline = new WebInspector.NetworkTimeline; + + this._isCapturing = false; + this._initiatedByBackendStart = false; + this._initiatedByBackendStop = false; + this._waitingForCapturingStartedEvent = false; + this._isCapturingPageReload = false; + this._autoCaptureOnPageLoad = false; + this._mainResourceForAutoCapturing = null; + this._shouldSetAutoCapturingMainResource = false; + this._boundStopCapturing = this.stopCapturing.bind(this); + + this._webTimelineScriptRecordsExpectingScriptProfilerEvents = null; + this._scriptProfilerRecords = null; + + this._stopCapturingTimeout = undefined; + this._deadTimeTimeout = undefined; + this._lastDeadTimeTickle = 0; + + this.reset(); + } + + // Static + + static defaultTimelineTypes() + { + if (WebInspector.debuggableType === WebInspector.DebuggableType.JavaScript) { + let defaultTypes = [WebInspector.TimelineRecord.Type.Script]; + if (WebInspector.HeapAllocationsInstrument.supported()) + defaultTypes.push(WebInspector.TimelineRecord.Type.HeapAllocations); + return defaultTypes; + } + + let defaultTypes = [ + WebInspector.TimelineRecord.Type.Network, + WebInspector.TimelineRecord.Type.Layout, + WebInspector.TimelineRecord.Type.Script, + ]; + + if (WebInspector.FPSInstrument.supported()) + defaultTypes.push(WebInspector.TimelineRecord.Type.RenderingFrame); + + return defaultTypes; + } + + static availableTimelineTypes() + { + let types = WebInspector.TimelineManager.defaultTimelineTypes(); + if (WebInspector.debuggableType === WebInspector.DebuggableType.JavaScript) + return types; + + if (WebInspector.MemoryInstrument.supported()) + types.push(WebInspector.TimelineRecord.Type.Memory); + + if (WebInspector.HeapAllocationsInstrument.supported()) + types.push(WebInspector.TimelineRecord.Type.HeapAllocations); + + return types; + } + + // Public + + reset() + { + if (this._isCapturing) + this.stopCapturing(); + + this._recordings = []; + this._activeRecording = null; + this._nextRecordingIdentifier = 1; + + this._loadNewRecording(); + } + + // The current recording that new timeline records will be appended to, if any. + get activeRecording() + { + console.assert(this._activeRecording || !this._isCapturing); + return this._activeRecording; + } + + get persistentNetworkTimeline() + { + return this._persistentNetworkTimeline; + } + + get recordings() + { + return this._recordings.slice(); + } + + get autoCaptureOnPageLoad() + { + return this._autoCaptureOnPageLoad; + } + + set autoCaptureOnPageLoad(autoCapture) + { + autoCapture = !!autoCapture; + + if (this._autoCaptureOnPageLoad === autoCapture) + return; + + this._autoCaptureOnPageLoad = autoCapture; + + if (window.TimelineAgent && TimelineAgent.setAutoCaptureEnabled) + TimelineAgent.setAutoCaptureEnabled(this._autoCaptureOnPageLoad); + } + + get enabledTimelineTypes() + { + let availableTimelineTypes = WebInspector.TimelineManager.availableTimelineTypes(); + return this._enabledTimelineTypesSetting.value.filter((type) => availableTimelineTypes.includes(type)); + } + + set enabledTimelineTypes(x) + { + this._enabledTimelineTypesSetting.value = x || []; + + this._updateAutoCaptureInstruments(); + } + + isCapturing() + { + return this._isCapturing; + } + + isCapturingPageReload() + { + return this._isCapturingPageReload; + } + + startCapturing(shouldCreateRecording) + { + console.assert(!this._isCapturing, "TimelineManager is already capturing."); + + if (!this._activeRecording || shouldCreateRecording) + this._loadNewRecording(); + + this._waitingForCapturingStartedEvent = true; + + this.dispatchEventToListeners(WebInspector.TimelineManager.Event.CapturingWillStart); + + this._activeRecording.start(this._initiatedByBackendStart); + } + + stopCapturing() + { + console.assert(this._isCapturing, "TimelineManager is not capturing."); + + this._activeRecording.stop(this._initiatedByBackendStop); + + // NOTE: Always stop immediately instead of waiting for a Timeline.recordingStopped event. + // This way the UI feels as responsive to a stop as possible. + // FIXME: Web Inspector: Timeline UI should keep up with processing all incoming records + this.capturingStopped(); + } + + unloadRecording() + { + if (!this._activeRecording) + return; + + if (this._isCapturing) + this.stopCapturing(); + + this._activeRecording.unloaded(); + this._activeRecording = null; + } + + computeElapsedTime(timestamp) + { + if (!this._activeRecording) + return 0; + + return this._activeRecording.computeElapsedTime(timestamp); + } + + scriptProfilerIsTracking() + { + return this._scriptProfilerRecords !== null; + } + + // Protected + + capturingStarted(startTime) + { + // Called from WebInspector.TimelineObserver. + + if (this._isCapturing) + return; + + this._waitingForCapturingStartedEvent = false; + this._isCapturing = true; + + this._lastDeadTimeTickle = 0; + + if (startTime) + this.activeRecording.initializeTimeBoundsIfNecessary(startTime); + + this._webTimelineScriptRecordsExpectingScriptProfilerEvents = []; + + this.dispatchEventToListeners(WebInspector.TimelineManager.Event.CapturingStarted, {startTime}); + } + + capturingStopped(endTime) + { + // Called from WebInspector.TimelineObserver. + + if (!this._isCapturing) + return; + + if (this._stopCapturingTimeout) { + clearTimeout(this._stopCapturingTimeout); + this._stopCapturingTimeout = undefined; + } + + if (this._deadTimeTimeout) { + clearTimeout(this._deadTimeTimeout); + this._deadTimeTimeout = undefined; + } + + this._isCapturing = false; + this._isCapturingPageReload = false; + this._shouldSetAutoCapturingMainResource = false; + this._mainResourceForAutoCapturing = null; + this._initiatedByBackendStart = false; + this._initiatedByBackendStop = false; + + this.dispatchEventToListeners(WebInspector.TimelineManager.Event.CapturingStopped, {endTime}); + } + + autoCaptureStarted() + { + // Called from WebInspector.TimelineObserver. + + if (this._isCapturing) + this.stopCapturing(); + + this._initiatedByBackendStart = true; + + // We may already have an fresh TimelineRecording created if autoCaptureStarted is received + // between sending the Timeline.start command and receiving Timeline.capturingStarted event. + // In that case, there is no need to call startCapturing again. Reuse the fresh recording. + if (!this._waitingForCapturingStartedEvent) { + const createNewRecording = true; + this.startCapturing(createNewRecording); + } + + this._shouldSetAutoCapturingMainResource = true; + } + + programmaticCaptureStarted() + { + // Called from WebInspector.TimelineObserver. + + this._initiatedByBackendStart = true; + + this._activeRecording.addScriptInstrumentForProgrammaticCapture(); + + const createNewRecording = false; + this.startCapturing(createNewRecording); + } + + programmaticCaptureStopped() + { + // Called from WebInspector.TimelineObserver. + + this._initiatedByBackendStop = true; + + // FIXME: This is purely to avoid a noisy assert. Previously + // it was impossible to stop without stopping from the UI. + console.assert(!this._isCapturing); + this._isCapturing = true; + + this.stopCapturing(); + } + + eventRecorded(recordPayload) + { + // Called from WebInspector.TimelineObserver. + + if (!this._isCapturing) + return; + + var records = []; + + // Iterate over the records tree using a stack. Doing this recursively has + // been known to cause a call stack overflow. https://webkit.org/b/79106 + var stack = [{array: [recordPayload], parent: null, parentRecord: null, index: 0}]; + while (stack.length) { + var entry = stack.lastValue; + var recordPayloads = entry.array; + + if (entry.index < recordPayloads.length) { + var recordPayload = recordPayloads[entry.index]; + var record = this._processEvent(recordPayload, entry.parent); + if (record) { + record.parent = entry.parentRecord; + records.push(record); + if (entry.parentRecord) + entry.parentRecord.children.push(record); + } + + if (recordPayload.children && recordPayload.children.length) + stack.push({array: recordPayload.children, parent: recordPayload, parentRecord: record || entry.parentRecord, index: 0}); + ++entry.index; + } else + stack.pop(); + } + + for (var record of records) { + if (record.type === WebInspector.TimelineRecord.Type.RenderingFrame) { + if (!record.children.length) + continue; + record.setupFrameIndex(); + } + + this._addRecord(record); + } + } + + // Protected + + pageDOMContentLoadedEventFired(timestamp) + { + // Called from WebInspector.PageObserver. + + console.assert(this._activeRecording); + console.assert(isNaN(WebInspector.frameResourceManager.mainFrame.domContentReadyEventTimestamp)); + + let computedTimestamp = this.activeRecording.computeElapsedTime(timestamp); + + WebInspector.frameResourceManager.mainFrame.markDOMContentReadyEvent(computedTimestamp); + + let eventMarker = new WebInspector.TimelineMarker(computedTimestamp, WebInspector.TimelineMarker.Type.DOMContentEvent); + this._activeRecording.addEventMarker(eventMarker); + } + + pageLoadEventFired(timestamp) + { + // Called from WebInspector.PageObserver. + + console.assert(this._activeRecording); + console.assert(isNaN(WebInspector.frameResourceManager.mainFrame.loadEventTimestamp)); + + let computedTimestamp = this.activeRecording.computeElapsedTime(timestamp); + + WebInspector.frameResourceManager.mainFrame.markLoadEvent(computedTimestamp); + + let eventMarker = new WebInspector.TimelineMarker(computedTimestamp, WebInspector.TimelineMarker.Type.LoadEvent); + this._activeRecording.addEventMarker(eventMarker); + + this._stopAutoRecordingSoon(); + } + + memoryTrackingStart(timestamp) + { + // Called from WebInspector.MemoryObserver. + + this.capturingStarted(timestamp); + } + + memoryTrackingUpdate(event) + { + // Called from WebInspector.MemoryObserver. + + if (!this._isCapturing) + return; + + this._addRecord(new WebInspector.MemoryTimelineRecord(event.timestamp, event.categories)); + } + + memoryTrackingComplete() + { + // Called from WebInspector.MemoryObserver. + } + + heapTrackingStarted(timestamp, snapshot) + { + // Called from WebInspector.HeapObserver. + + this._addRecord(new WebInspector.HeapAllocationsTimelineRecord(timestamp, snapshot)); + + this.capturingStarted(timestamp); + } + + heapTrackingCompleted(timestamp, snapshot) + { + // Called from WebInspector.HeapObserver. + + this._addRecord(new WebInspector.HeapAllocationsTimelineRecord(timestamp, snapshot)); + } + + heapSnapshotAdded(timestamp, snapshot) + { + // Called from WebInspector.HeapAllocationsInstrument. + + this._addRecord(new WebInspector.HeapAllocationsTimelineRecord(timestamp, snapshot)); + } + + // Private + + _processRecord(recordPayload, parentRecordPayload) + { + var startTime = this.activeRecording.computeElapsedTime(recordPayload.startTime); + var endTime = this.activeRecording.computeElapsedTime(recordPayload.endTime); + var callFrames = this._callFramesFromPayload(recordPayload.stackTrace); + + var significantCallFrame = null; + if (callFrames) { + for (var i = 0; i < callFrames.length; ++i) { + if (callFrames[i].nativeCode) + continue; + significantCallFrame = callFrames[i]; + break; + } + } + + var sourceCodeLocation = significantCallFrame && significantCallFrame.sourceCodeLocation; + + switch (recordPayload.type) { + case TimelineAgent.EventType.ScheduleStyleRecalculation: + console.assert(isNaN(endTime)); + + // Pass the startTime as the endTime since this record type has no duration. + return new WebInspector.LayoutTimelineRecord(WebInspector.LayoutTimelineRecord.EventType.InvalidateStyles, startTime, startTime, callFrames, sourceCodeLocation); + + case TimelineAgent.EventType.RecalculateStyles: + return new WebInspector.LayoutTimelineRecord(WebInspector.LayoutTimelineRecord.EventType.RecalculateStyles, startTime, endTime, callFrames, sourceCodeLocation); + + case TimelineAgent.EventType.InvalidateLayout: + console.assert(isNaN(endTime)); + + // Pass the startTime as the endTime since this record type has no duration. + return new WebInspector.LayoutTimelineRecord(WebInspector.LayoutTimelineRecord.EventType.InvalidateLayout, startTime, startTime, callFrames, sourceCodeLocation); + + case TimelineAgent.EventType.Layout: + var layoutRecordType = sourceCodeLocation ? WebInspector.LayoutTimelineRecord.EventType.ForcedLayout : WebInspector.LayoutTimelineRecord.EventType.Layout; + var quad = new WebInspector.Quad(recordPayload.data.root); + return new WebInspector.LayoutTimelineRecord(layoutRecordType, startTime, endTime, callFrames, sourceCodeLocation, quad); + + case TimelineAgent.EventType.Paint: + var quad = new WebInspector.Quad(recordPayload.data.clip); + return new WebInspector.LayoutTimelineRecord(WebInspector.LayoutTimelineRecord.EventType.Paint, startTime, endTime, callFrames, sourceCodeLocation, quad); + + case TimelineAgent.EventType.Composite: + return new WebInspector.LayoutTimelineRecord(WebInspector.LayoutTimelineRecord.EventType.Composite, startTime, endTime, callFrames, sourceCodeLocation); + + case TimelineAgent.EventType.RenderingFrame: + if (!recordPayload.children || !recordPayload.children.length) + return null; + + return new WebInspector.RenderingFrameTimelineRecord(startTime, endTime); + + case TimelineAgent.EventType.EvaluateScript: + if (!sourceCodeLocation) { + var mainFrame = WebInspector.frameResourceManager.mainFrame; + var scriptResource = mainFrame.url === recordPayload.data.url ? mainFrame.mainResource : mainFrame.resourceForURL(recordPayload.data.url, true); + if (scriptResource) { + // The lineNumber is 1-based, but we expect 0-based. + var lineNumber = recordPayload.data.lineNumber - 1; + + // FIXME: No column number is provided. + sourceCodeLocation = scriptResource.createSourceCodeLocation(lineNumber, 0); + } + } + + var profileData = recordPayload.data.profile; + + var record; + switch (parentRecordPayload && parentRecordPayload.type) { + case TimelineAgent.EventType.TimerFire: + record = new WebInspector.ScriptTimelineRecord(WebInspector.ScriptTimelineRecord.EventType.TimerFired, startTime, endTime, callFrames, sourceCodeLocation, parentRecordPayload.data.timerId, profileData); + break; + default: + record = new WebInspector.ScriptTimelineRecord(WebInspector.ScriptTimelineRecord.EventType.ScriptEvaluated, startTime, endTime, callFrames, sourceCodeLocation, null, profileData); + break; + } + + this._webTimelineScriptRecordsExpectingScriptProfilerEvents.push(record); + return record; + + case TimelineAgent.EventType.ConsoleProfile: + var profileData = recordPayload.data.profile; + // COMPATIBILITY (iOS 9): With the Sampling Profiler, profiles no longer include legacy profile data. + console.assert(profileData || TimelineAgent.setInstruments); + return new WebInspector.ScriptTimelineRecord(WebInspector.ScriptTimelineRecord.EventType.ConsoleProfileRecorded, startTime, endTime, callFrames, sourceCodeLocation, recordPayload.data.title, profileData); + + case TimelineAgent.EventType.TimerFire: + case TimelineAgent.EventType.EventDispatch: + case TimelineAgent.EventType.FireAnimationFrame: + // These are handled when the parent of FunctionCall or EvaluateScript. + break; + + case TimelineAgent.EventType.FunctionCall: + // FunctionCall always happens as a child of another record, and since the FunctionCall record + // has useful info we just make the timeline record here (combining the data from both records). + if (!parentRecordPayload) { + console.warn("Unexpectedly received a FunctionCall timeline record without a parent record"); + break; + } + + if (!sourceCodeLocation) { + var mainFrame = WebInspector.frameResourceManager.mainFrame; + var scriptResource = mainFrame.url === recordPayload.data.scriptName ? mainFrame.mainResource : mainFrame.resourceForURL(recordPayload.data.scriptName, true); + if (scriptResource) { + // The lineNumber is 1-based, but we expect 0-based. + var lineNumber = recordPayload.data.scriptLine - 1; + + // FIXME: No column number is provided. + sourceCodeLocation = scriptResource.createSourceCodeLocation(lineNumber, 0); + } + } + + var profileData = recordPayload.data.profile; + + var record; + switch (parentRecordPayload.type) { + case TimelineAgent.EventType.TimerFire: + record = new WebInspector.ScriptTimelineRecord(WebInspector.ScriptTimelineRecord.EventType.TimerFired, startTime, endTime, callFrames, sourceCodeLocation, parentRecordPayload.data.timerId, profileData); + break; + case TimelineAgent.EventType.EventDispatch: + record = new WebInspector.ScriptTimelineRecord(WebInspector.ScriptTimelineRecord.EventType.EventDispatched, startTime, endTime, callFrames, sourceCodeLocation, parentRecordPayload.data.type, profileData); + break; + case TimelineAgent.EventType.FireAnimationFrame: + record = new WebInspector.ScriptTimelineRecord(WebInspector.ScriptTimelineRecord.EventType.AnimationFrameFired, startTime, endTime, callFrames, sourceCodeLocation, parentRecordPayload.data.id, profileData); + break; + case TimelineAgent.EventType.FunctionCall: + record = new WebInspector.ScriptTimelineRecord(WebInspector.ScriptTimelineRecord.EventType.ScriptEvaluated, startTime, endTime, callFrames, sourceCodeLocation, parentRecordPayload.data.id, profileData); + break; + case TimelineAgent.EventType.RenderingFrame: + record = new WebInspector.ScriptTimelineRecord(WebInspector.ScriptTimelineRecord.EventType.ScriptEvaluated, startTime, endTime, callFrames, sourceCodeLocation, parentRecordPayload.data.id, profileData); + break; + + default: + console.assert(false, "Missed FunctionCall embedded inside of: " + parentRecordPayload.type); + break; + } + + if (record) { + this._webTimelineScriptRecordsExpectingScriptProfilerEvents.push(record); + return record; + } + break; + + case TimelineAgent.EventType.ProbeSample: + // Pass the startTime as the endTime since this record type has no duration. + sourceCodeLocation = WebInspector.probeManager.probeForIdentifier(recordPayload.data.probeId).breakpoint.sourceCodeLocation; + return new WebInspector.ScriptTimelineRecord(WebInspector.ScriptTimelineRecord.EventType.ProbeSampleRecorded, startTime, startTime, callFrames, sourceCodeLocation, recordPayload.data.probeId); + + case TimelineAgent.EventType.TimerInstall: + console.assert(isNaN(endTime)); + + // Pass the startTime as the endTime since this record type has no duration. + var timerDetails = {timerId: recordPayload.data.timerId, timeout: recordPayload.data.timeout, repeating: !recordPayload.data.singleShot}; + return new WebInspector.ScriptTimelineRecord(WebInspector.ScriptTimelineRecord.EventType.TimerInstalled, startTime, startTime, callFrames, sourceCodeLocation, timerDetails); + + case TimelineAgent.EventType.TimerRemove: + console.assert(isNaN(endTime)); + + // Pass the startTime as the endTime since this record type has no duration. + return new WebInspector.ScriptTimelineRecord(WebInspector.ScriptTimelineRecord.EventType.TimerRemoved, startTime, startTime, callFrames, sourceCodeLocation, recordPayload.data.timerId); + + case TimelineAgent.EventType.RequestAnimationFrame: + console.assert(isNaN(endTime)); + + // Pass the startTime as the endTime since this record type has no duration. + return new WebInspector.ScriptTimelineRecord(WebInspector.ScriptTimelineRecord.EventType.AnimationFrameRequested, startTime, startTime, callFrames, sourceCodeLocation, recordPayload.data.id); + + case TimelineAgent.EventType.CancelAnimationFrame: + console.assert(isNaN(endTime)); + + // Pass the startTime as the endTime since this record type has no duration. + return new WebInspector.ScriptTimelineRecord(WebInspector.ScriptTimelineRecord.EventType.AnimationFrameCanceled, startTime, startTime, callFrames, sourceCodeLocation, recordPayload.data.id); + + default: + console.error("Missing handling of Timeline Event Type: " + recordPayload.type); + } + + return null; + } + + _processEvent(recordPayload, parentRecordPayload) + { + switch (recordPayload.type) { + case TimelineAgent.EventType.TimeStamp: + var timestamp = this.activeRecording.computeElapsedTime(recordPayload.startTime); + var eventMarker = new WebInspector.TimelineMarker(timestamp, WebInspector.TimelineMarker.Type.TimeStamp, recordPayload.data.message); + this._activeRecording.addEventMarker(eventMarker); + break; + + case TimelineAgent.EventType.Time: + case TimelineAgent.EventType.TimeEnd: + // FIXME: Web Inspector: Show console.time/timeEnd ranges in Timeline + // FIXME: Make use of "message" payload properties. + break; + + default: + return this._processRecord(recordPayload, parentRecordPayload); + } + + return null; + } + + _loadNewRecording() + { + if (this._activeRecording && this._activeRecording.isEmpty()) + return; + + let instruments = this.enabledTimelineTypes.map((type) => WebInspector.Instrument.createForTimelineType(type)); + let identifier = this._nextRecordingIdentifier++; + let newRecording = new WebInspector.TimelineRecording(identifier, WebInspector.UIString("Timeline Recording %d").format(identifier), instruments); + + this._recordings.push(newRecording); + this.dispatchEventToListeners(WebInspector.TimelineManager.Event.RecordingCreated, {recording: newRecording}); + + if (this._isCapturing) + this.stopCapturing(); + + var oldRecording = this._activeRecording; + if (oldRecording) + oldRecording.unloaded(); + + this._activeRecording = newRecording; + + // COMPATIBILITY (iOS 8): When using Legacy timestamps, a navigation will have computed + // the main resource's will send request timestamp in terms of the last page's base timestamp. + // Now that we have navigated, we should reset the legacy base timestamp and the + // will send request timestamp for the new main resource. This way, all new timeline + // records will be computed relative to the new navigation. + if (this._mainResourceForAutoCapturing && WebInspector.TimelineRecording.isLegacy) { + console.assert(this._mainResourceForAutoCapturing.originalRequestWillBeSentTimestamp); + this._activeRecording.setLegacyBaseTimestamp(this._mainResourceForAutoCapturing.originalRequestWillBeSentTimestamp); + this._mainResourceForAutoCapturing._requestSentTimestamp = 0; + } + + this.dispatchEventToListeners(WebInspector.TimelineManager.Event.RecordingLoaded, {oldRecording}); + } + + _callFramesFromPayload(payload) + { + if (!payload) + return null; + + return payload.map((x) => WebInspector.CallFrame.fromPayload(WebInspector.assumingMainTarget(), x)); + } + + _addRecord(record) + { + this._activeRecording.addRecord(record); + + // Only worry about dead time after the load event. + if (WebInspector.frameResourceManager.mainFrame && isNaN(WebInspector.frameResourceManager.mainFrame.loadEventTimestamp)) + this._resetAutoRecordingDeadTimeTimeout(); + } + + _attemptAutoCapturingForFrame(frame) + { + if (!this._autoCaptureOnPageLoad) + return false; + + if (!frame.isMainFrame()) + return false; + + // COMPATIBILITY (iOS 9): Timeline.setAutoCaptureEnabled did not exist. + // Perform auto capture in the frontend. + if (!TimelineAgent.setAutoCaptureEnabled) + return this._legacyAttemptStartAutoCapturingForFrame(frame); + + if (!this._shouldSetAutoCapturingMainResource) + return false; + + console.assert(this._isCapturing, "We saw autoCaptureStarted so we should already be capturing"); + + let mainResource = frame.provisionalMainResource || frame.mainResource; + if (mainResource === this._mainResourceForAutoCapturing) + return false; + + let oldMainResource = frame.mainResource || null; + this._isCapturingPageReload = oldMainResource !== null && oldMainResource.url === mainResource.url; + + this._mainResourceForAutoCapturing = mainResource; + + this._addRecord(new WebInspector.ResourceTimelineRecord(mainResource)); + + this._resetAutoRecordingMaxTimeTimeout(); + + this._shouldSetAutoCapturingMainResource = false; + + return true; + } + + _legacyAttemptStartAutoCapturingForFrame(frame) + { + if (this._isCapturing && !this._mainResourceForAutoCapturing) + return false; + + let mainResource = frame.provisionalMainResource || frame.mainResource; + if (mainResource === this._mainResourceForAutoCapturing) + return false; + + let oldMainResource = frame.mainResource || null; + this._isCapturingPageReload = oldMainResource !== null && oldMainResource.url === mainResource.url; + + if (this._isCapturing) + this.stopCapturing(); + + this._mainResourceForAutoCapturing = mainResource; + + this._loadNewRecording(); + + this.startCapturing(); + + this._addRecord(new WebInspector.ResourceTimelineRecord(mainResource)); + + this._resetAutoRecordingMaxTimeTimeout(); + + return true; + } + + _stopAutoRecordingSoon() + { + // Only auto stop when auto capturing. + if (!this._isCapturing || !this._mainResourceForAutoCapturing) + return; + + if (this._stopCapturingTimeout) + clearTimeout(this._stopCapturingTimeout); + this._stopCapturingTimeout = setTimeout(this._boundStopCapturing, WebInspector.TimelineManager.MaximumAutoRecordDurationAfterLoadEvent); + } + + _resetAutoRecordingMaxTimeTimeout() + { + if (this._stopCapturingTimeout) + clearTimeout(this._stopCapturingTimeout); + this._stopCapturingTimeout = setTimeout(this._boundStopCapturing, WebInspector.TimelineManager.MaximumAutoRecordDuration); + } + + _resetAutoRecordingDeadTimeTimeout() + { + // Only monitor dead time when auto capturing. + if (!this._isCapturing || !this._mainResourceForAutoCapturing) + return; + + // Avoid unnecessary churning of timeout identifier by not tickling until 10ms have passed. + let now = Date.now(); + if (now <= this._lastDeadTimeTickle) + return; + this._lastDeadTimeTickle = now + 10; + + if (this._deadTimeTimeout) + clearTimeout(this._deadTimeTimeout); + this._deadTimeTimeout = setTimeout(this._boundStopCapturing, WebInspector.TimelineManager.DeadTimeRequiredToStopAutoRecordingEarly); + } + + _provisionalLoadStarted(event) + { + this._attemptAutoCapturingForFrame(event.target); + } + + _mainResourceDidChange(event) + { + let frame = event.target; + if (frame.isMainFrame() && WebInspector.settings.clearNetworkOnNavigate.value) + this._persistentNetworkTimeline.reset(); + + let mainResource = frame.mainResource; + let record = new WebInspector.ResourceTimelineRecord(mainResource); + if (!isNaN(record.startTime)) + this._persistentNetworkTimeline.addRecord(record); + + // Ignore resource events when there isn't a main frame yet. Those events are triggered by + // loading the cached resources when the inspector opens, and they do not have timing information. + if (!WebInspector.frameResourceManager.mainFrame) + return; + + if (this._attemptAutoCapturingForFrame(frame)) + return; + + if (!this._isCapturing) + return; + + if (mainResource === this._mainResourceForAutoCapturing) + return; + + this._addRecord(record); + } + + _resourceWasAdded(event) + { + var record = new WebInspector.ResourceTimelineRecord(event.data.resource); + if (!isNaN(record.startTime)) + this._persistentNetworkTimeline.addRecord(record); + + // Ignore resource events when there isn't a main frame yet. Those events are triggered by + // loading the cached resources when the inspector opens, and they do not have timing information. + if (!WebInspector.frameResourceManager.mainFrame) + return; + + if (!this._isCapturing) + return; + + this._addRecord(record); + } + + _garbageCollected(event) + { + if (!this._isCapturing) + return; + + let collection = event.data.collection; + this._addRecord(new WebInspector.ScriptTimelineRecord(WebInspector.ScriptTimelineRecord.EventType.GarbageCollected, collection.startTime, collection.endTime, null, null, collection)); + } + + _memoryPressure(event) + { + if (!this._isCapturing) + return; + + this.activeRecording.addMemoryPressureEvent(event.data.memoryPressureEvent); + } + + _scriptProfilerTypeToScriptTimelineRecordType(type) + { + switch (type) { + case ScriptProfilerAgent.EventType.API: + return WebInspector.ScriptTimelineRecord.EventType.APIScriptEvaluated; + case ScriptProfilerAgent.EventType.Microtask: + return WebInspector.ScriptTimelineRecord.EventType.MicrotaskDispatched; + case ScriptProfilerAgent.EventType.Other: + return WebInspector.ScriptTimelineRecord.EventType.ScriptEvaluated; + } + } + + scriptProfilerProgrammaticCaptureStarted() + { + // FIXME: Generalize the concept of Instruments on the backend to work equally for JSContext and Web inspection + console.assert(WebInspector.debuggableType === WebInspector.DebuggableType.JavaScript); + console.assert(!this._isCapturing); + + this.programmaticCaptureStarted(); + } + + scriptProfilerProgrammaticCaptureStopped() + { + // FIXME: Generalize the concept of Instruments on the backend to work equally for JSContext and Web inspection + console.assert(WebInspector.debuggableType === WebInspector.DebuggableType.JavaScript); + console.assert(this._isCapturing); + + this.programmaticCaptureStopped(); + } + + scriptProfilerTrackingStarted(timestamp) + { + this._scriptProfilerRecords = []; + + this.capturingStarted(timestamp); + } + + scriptProfilerTrackingUpdated(event) + { + let {startTime, endTime, type} = event; + let scriptRecordType = this._scriptProfilerTypeToScriptTimelineRecordType(type); + let record = new WebInspector.ScriptTimelineRecord(scriptRecordType, startTime, endTime, null, null, null, null); + record.__scriptProfilerType = type; + this._scriptProfilerRecords.push(record); + + // "Other" events, generated by Web content, will have wrapping Timeline records + // and need to be merged. Non-Other events, generated purely by the JavaScript + // engine or outside of the page via APIs, will not have wrapping Timeline + // records, so these records can just be added right now. + if (type !== ScriptProfilerAgent.EventType.Other) + this._addRecord(record); + } + + scriptProfilerTrackingCompleted(samples) + { + console.assert(!this._webTimelineScriptRecordsExpectingScriptProfilerEvents || this._scriptProfilerRecords.length >= this._webTimelineScriptRecordsExpectingScriptProfilerEvents.length); + + if (samples) { + let {stackTraces} = samples; + let topDownCallingContextTree = this.activeRecording.topDownCallingContextTree; + let bottomUpCallingContextTree = this.activeRecording.bottomUpCallingContextTree; + let topFunctionsTopDownCallingContextTree = this.activeRecording.topFunctionsTopDownCallingContextTree; + let topFunctionsBottomUpCallingContextTree = this.activeRecording.topFunctionsBottomUpCallingContextTree; + + // Calculate a per-sample duration. + let timestampIndex = 0; + let timestampCount = stackTraces.length; + let sampleDurations = new Array(timestampCount); + let sampleDurationIndex = 0; + const defaultDuration = 1 / 1000; // 1ms. + for (let i = 0; i < this._scriptProfilerRecords.length; ++i) { + let record = this._scriptProfilerRecords[i]; + + // Use a default duration for timestamps recorded outside of ScriptProfiler events. + while (timestampIndex < timestampCount && stackTraces[timestampIndex].timestamp < record.startTime) { + sampleDurations[sampleDurationIndex++] = defaultDuration; + timestampIndex++; + } + + // Average the duration per sample across all samples during the record. + let samplesInRecord = 0; + while (timestampIndex < timestampCount && stackTraces[timestampIndex].timestamp < record.endTime) { + timestampIndex++; + samplesInRecord++; + } + if (samplesInRecord) { + let averageDuration = (record.endTime - record.startTime) / samplesInRecord; + sampleDurations.fill(averageDuration, sampleDurationIndex, sampleDurationIndex + samplesInRecord); + sampleDurationIndex += samplesInRecord; + } + } + + // Use a default duration for timestamps recorded outside of ScriptProfiler events. + if (timestampIndex < timestampCount) + sampleDurations.fill(defaultDuration, sampleDurationIndex); + + for (let i = 0; i < stackTraces.length; i++) { + topDownCallingContextTree.updateTreeWithStackTrace(stackTraces[i], sampleDurations[i]); + bottomUpCallingContextTree.updateTreeWithStackTrace(stackTraces[i], sampleDurations[i]); + topFunctionsTopDownCallingContextTree.updateTreeWithStackTrace(stackTraces[i], sampleDurations[i]); + topFunctionsBottomUpCallingContextTree.updateTreeWithStackTrace(stackTraces[i], sampleDurations[i]); + } + + // FIXME: This transformation should not be needed after introducing ProfileView. + // Once we eliminate ProfileNodeTreeElements and ProfileNodeDataGridNodes. + // Web Inspector: Timelines UI redesign: Remove TimelineSidebarPanel + for (let i = 0; i < this._scriptProfilerRecords.length; ++i) { + let record = this._scriptProfilerRecords[i]; + record.profilePayload = topDownCallingContextTree.toCPUProfilePayload(record.startTime, record.endTime); + } + } + + // Associate the ScriptProfiler created records with Web Timeline records. + // Filter out the already added ScriptProfiler events which should not have been wrapped. + if (WebInspector.debuggableType !== WebInspector.DebuggableType.JavaScript) { + this._scriptProfilerRecords = this._scriptProfilerRecords.filter((x) => x.__scriptProfilerType === ScriptProfilerAgent.EventType.Other); + this._mergeScriptProfileRecords(); + } + + this._scriptProfilerRecords = null; + + let timeline = this.activeRecording.timelineForRecordType(WebInspector.TimelineRecord.Type.Script); + timeline.refresh(); + } + + _mergeScriptProfileRecords() + { + let nextRecord = function(list) { return list.shift() || null; }; + let nextWebTimelineRecord = nextRecord.bind(null, this._webTimelineScriptRecordsExpectingScriptProfilerEvents); + let nextScriptProfilerRecord = nextRecord.bind(null, this._scriptProfilerRecords); + let recordEnclosesRecord = function(record1, record2) { + return record1.startTime <= record2.startTime && record1.endTime >= record2.endTime; + }; + + let webRecord = nextWebTimelineRecord(); + let profilerRecord = nextScriptProfilerRecord(); + + while (webRecord && profilerRecord) { + // Skip web records with parent web records. For example an EvaluateScript with an EvaluateScript parent. + if (webRecord.parent instanceof WebInspector.ScriptTimelineRecord) { + console.assert(recordEnclosesRecord(webRecord.parent, webRecord), "Timeline Record incorrectly wrapping another Timeline Record"); + webRecord = nextWebTimelineRecord(); + continue; + } + + // Normal case of a Web record wrapping a Script record. + if (recordEnclosesRecord(webRecord, profilerRecord)) { + webRecord.profilePayload = profilerRecord.profilePayload; + profilerRecord = nextScriptProfilerRecord(); + + // If there are more script profile records in the same time interval, add them + // as individual script evaluated records with profiles. This can happen with + // web microtask checkpoints that are technically inside of other web records. + // FIXME: Web Inspector: Timeline Cleanup: Better Timeline Record for Microtask Checkpoints + while (profilerRecord && recordEnclosesRecord(webRecord, profilerRecord)) { + this._addRecord(profilerRecord); + profilerRecord = nextScriptProfilerRecord(); + } + + webRecord = nextWebTimelineRecord(); + continue; + } + + // Profiler Record is entirely after the Web Record. This would mean an empty web record. + if (profilerRecord.startTime > webRecord.endTime) { + console.warn("Unexpected case of a Timeline record not containing a ScriptProfiler event and profile data"); + webRecord = nextWebTimelineRecord(); + continue; + } + + // Non-wrapped profiler record. + console.warn("Unexpected case of a ScriptProfiler event not being contained by a Timeline record"); + this._addRecord(profilerRecord); + profilerRecord = nextScriptProfilerRecord(); + } + + // Skipping the remaining ScriptProfiler events to match the current UI for handling Timeline records. + // However, the remaining ScriptProfiler records are valid and could be shown. + // FIXME: Web Inspector: Timeline UI should keep up with processing all incoming records + } + + _updateAutoCaptureInstruments() + { + if (!window.TimelineAgent) + return; + + if (!TimelineAgent.setInstruments) + return; + + let instrumentSet = new Set; + let enabledTimelineTypes = this._enabledTimelineTypesSetting.value; + + for (let timelineType of enabledTimelineTypes) { + switch (timelineType) { + case WebInspector.TimelineRecord.Type.Script: + instrumentSet.add(TimelineAgent.Instrument.ScriptProfiler); + break; + case WebInspector.TimelineRecord.Type.HeapAllocations: + instrumentSet.add(TimelineAgent.Instrument.Heap); + break; + case WebInspector.TimelineRecord.Type.Network: + case WebInspector.TimelineRecord.Type.RenderingFrame: + case WebInspector.TimelineRecord.Type.Layout: + instrumentSet.add(TimelineAgent.Instrument.Timeline); + break; + case WebInspector.TimelineRecord.Type.Memory: + instrumentSet.add(TimelineAgent.Instrument.Memory); + break; + } + } + + TimelineAgent.setInstruments([...instrumentSet]); + } +}; + +WebInspector.TimelineManager.Event = { + RecordingCreated: "timeline-manager-recording-created", + RecordingLoaded: "timeline-manager-recording-loaded", + CapturingWillStart: "timeline-manager-capturing-will-start", + CapturingStarted: "timeline-manager-capturing-started", + CapturingStopped: "timeline-manager-capturing-stopped" +}; + +WebInspector.TimelineManager.MaximumAutoRecordDuration = 90000; // 90 seconds +WebInspector.TimelineManager.MaximumAutoRecordDurationAfterLoadEvent = 10000; // 10 seconds +WebInspector.TimelineManager.DeadTimeRequiredToStopAutoRecordingEarly = 2000; // 2 seconds diff --git a/Source/WebInspectorUI/UserInterface/Controllers/TypeTokenAnnotator.js b/Source/WebInspectorUI/UserInterface/Controllers/TypeTokenAnnotator.js new file mode 100644 index 000000000..7b820bbec --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/TypeTokenAnnotator.js @@ -0,0 +1,199 @@ +/* + * Copyright (C) 2014, 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.TypeTokenAnnotator = class TypeTokenAnnotator extends WebInspector.Annotator +{ + constructor(sourceCodeTextEditor, script) + { + super(sourceCodeTextEditor); + + this._script = script; + this._typeTokenNodes = []; + this._typeTokenBookmarks = []; + } + + // Protected + + insertAnnotations() + { + if (!this.isActive()) + return; + + var scriptSyntaxTree = this._script.scriptSyntaxTree; + + if (!scriptSyntaxTree) { + this._script.requestScriptSyntaxTree((syntaxTree) => { + // After requesting the tree, we still might get a null tree from a parse error. + if (syntaxTree) + this.insertAnnotations(); + }); + return; + } + + if (!scriptSyntaxTree.parsedSuccessfully) + return; + + var {startOffset, endOffset} = this.sourceCodeTextEditor.visibleRangeOffsets(); + + var startTime = Date.now(); + var allNodesInRange = scriptSyntaxTree.filterByRange(startOffset, endOffset); + scriptSyntaxTree.updateTypes(allNodesInRange, (nodesWithUpdatedTypes) => { + // Because this is an asynchronous call, we could have been deactivated before the callback function is called. + if (!this.isActive()) + return; + + nodesWithUpdatedTypes.forEach(this._insertTypeToken, this); + + let totalTime = Date.now() - startTime; + let timeoutTime = Number.constrain(8 * totalTime, 500, 2000); + this._timeoutIdentifier = setTimeout(() => { + this._timeoutIdentifier = null; + this.insertAnnotations(); + }, timeoutTime); + }); + } + + clearAnnotations() + { + this._clearTypeTokens(); + } + + // Private + + _insertTypeToken(node) + { + if (node.type === WebInspector.ScriptSyntaxTree.NodeType.Identifier) { + if (!node.attachments.__typeToken && node.attachments.types && node.attachments.types.valid) + this._insertToken(node.range[0], node, false, WebInspector.TypeTokenView.TitleType.Variable, node.name); + + if (node.attachments.__typeToken) + node.attachments.__typeToken.update(node.attachments.types); + + return; + } + + console.assert(node.type === WebInspector.ScriptSyntaxTree.NodeType.FunctionDeclaration || node.type === WebInspector.ScriptSyntaxTree.NodeType.FunctionExpression || node.type === WebInspector.ScriptSyntaxTree.NodeType.ArrowFunctionExpression); + + var functionReturnType = node.attachments.returnTypes; + if (!functionReturnType || !functionReturnType.valid) + return; + + // If a function does not have an explicit return statement with an argument (i.e, "return x;" instead of "return;") + // then don't show a return type unless we think it's a constructor. + var scriptSyntaxTree = this._script._scriptSyntaxTree; + if (!node.attachments.__typeToken && (scriptSyntaxTree.containsNonEmptyReturnStatement(node.body) || !functionReturnType.typeSet.isContainedIn(WebInspector.TypeSet.TypeBit.Undefined))) { + var functionName = node.id ? node.id.name : null; + this._insertToken(node.typeProfilingReturnDivot, node, true, WebInspector.TypeTokenView.TitleType.ReturnStatement, functionName); + } + + if (node.attachments.__typeToken) + node.attachments.__typeToken.update(node.attachments.returnTypes); + } + + _insertToken(originalOffset, node, shouldTranslateOffsetToAfterParameterList, typeTokenTitleType, functionOrVariableName) + { + var tokenPosition = this.sourceCodeTextEditor.originalOffsetToCurrentPosition(originalOffset); + var currentOffset = this.sourceCodeTextEditor.currentPositionToCurrentOffset(tokenPosition); + var sourceString = this.sourceCodeTextEditor.string; + + if (shouldTranslateOffsetToAfterParameterList) { + // Translate the position to the closing parenthesis of the function arguments: + // translate from: [type-token] function foo() {} => to: function foo() [type-token] {} + currentOffset = this._translateToOffsetAfterFunctionParameterList(node, currentOffset, sourceString); + tokenPosition = this.sourceCodeTextEditor.currentOffsetToCurrentPosition(currentOffset); + } + + // Note: bookmarks render to the left of the character they're being displayed next to. + // This is why right margin checks the current offset. And this is okay to do because JavaScript can't be written right-to-left. + var isSpaceRegexp = /\s/; + var shouldHaveLeftMargin = currentOffset !== 0 && !isSpaceRegexp.test(sourceString[currentOffset - 1]); + var shouldHaveRightMargin = !isSpaceRegexp.test(sourceString[currentOffset]); + var typeToken = new WebInspector.TypeTokenView(this, shouldHaveRightMargin, shouldHaveLeftMargin, typeTokenTitleType, functionOrVariableName); + var bookmark = this.sourceCodeTextEditor.setInlineWidget(tokenPosition, typeToken.element); + node.attachments.__typeToken = typeToken; + this._typeTokenNodes.push(node); + this._typeTokenBookmarks.push(bookmark); + } + + _translateToOffsetAfterFunctionParameterList(node, offset, sourceString) + { + // The assumption here is that we get the offset starting at the function keyword (or after the get/set keywords). + // We will return the offset for the closing parenthesis in the function declaration. + // All this code is just a way to find this parenthesis while ignoring comments. + + var isMultiLineComment = false; + var isSingleLineComment = false; + var shouldIgnore = false; + const isArrowFunction = node.type === WebInspector.ScriptSyntaxTree.NodeType.ArrowFunctionExpression; + + function isLineTerminator(char) + { + // Reference EcmaScript 5 grammar for single line comments and line terminators: + // http://www.ecma-international.org/ecma-262/5.1/#sec-7.3 + // http://www.ecma-international.org/ecma-262/5.1/#sec-7.4 + return char === "\n" || char === "\r" || char === "\u2028" || char === "\u2029"; + } + + while (((!isArrowFunction && sourceString[offset] !== ")") + || (isArrowFunction && sourceString[offset] !== ">") + || shouldIgnore) + && offset < sourceString.length) { + if (isSingleLineComment && isLineTerminator(sourceString[offset])) { + isSingleLineComment = false; + shouldIgnore = false; + } else if (isMultiLineComment && sourceString[offset] === "*" && sourceString[offset + 1] === "/") { + isMultiLineComment = false; + shouldIgnore = false; + offset++; + } else if (!shouldIgnore && sourceString[offset] === "/") { + offset++; + if (sourceString[offset] === "*") + isMultiLineComment = true; + else if (sourceString[offset] === "/") + isSingleLineComment = true; + else + throw new Error("Bad parsing. Couldn't parse comment preamble."); + shouldIgnore = true; + } + + offset++; + } + + return offset + 1; + } + + _clearTypeTokens() + { + this._typeTokenNodes.forEach(function(node) { + node.attachments.__typeToken = null; + }); + this._typeTokenBookmarks.forEach(function(bookmark) { + bookmark.clear(); + }); + + this._typeTokenNodes = []; + this._typeTokenBookmarks = []; + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Controllers/VisualStyleCompletionsController.js b/Source/WebInspectorUI/UserInterface/Controllers/VisualStyleCompletionsController.js new file mode 100644 index 000000000..d2a40b9d4 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/VisualStyleCompletionsController.js @@ -0,0 +1,132 @@ +/* + * Copyright (C) 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.VisualStyleCompletionsController = class VisualStyleCompletionsController extends WebInspector.Object +{ + constructor(delegate) + { + super(); + + this._delegate = delegate || null; + this._suggestionsView = new WebInspector.CompletionSuggestionsView(this); + this._completions = null; + this._currentCompletions = []; + this._selectedCompletionIndex = 0; + } + + // Public + + get visible() + { + return this._completions && this._currentCompletions.length && this._suggestionsView.visible; + } + + get hasCompletions() + { + return !!this._completions; + } + + get currentCompletion() + { + if (!this.hasCompletions) + return null; + + return this._currentCompletions[this._selectedCompletionIndex] || null; + } + + set completions(completions) + { + this._completions = completions || null; + } + + completionSuggestionsViewCustomizeCompletionElement(suggestionsView, element, item) + { + if (this._delegate && typeof this._delegate.visualStyleCompletionsControllerCustomizeCompletionElement === "function") + this._delegate.visualStyleCompletionsControllerCustomizeCompletionElement(suggestionsView, element, item); + } + + completionSuggestionsClickedCompletion(suggestionsView, text) + { + suggestionsView.hide(); + this.dispatchEventToListeners(WebInspector.VisualStyleCompletionsController.Event.CompletionSelected, {text}); + } + + previous() + { + this._suggestionsView.selectPrevious(); + this._selectedCompletionIndex = this._suggestionsView.selectedIndex; + } + + next() + { + this._suggestionsView.selectNext(); + this._selectedCompletionIndex = this._suggestionsView.selectedIndex; + } + + update(value) + { + if (!this.hasCompletions) + return false; + + this._currentCompletions = this._completions.startsWith(value); + + var currentCompletionsLength = this._currentCompletions.length; + if (currentCompletionsLength) { + if (currentCompletionsLength === 1 && this._currentCompletions[0] === value) { + this.hide(); + return false; + } + + if (this._selectedCompletionIndex >= currentCompletionsLength) + this._selectedCompletionIndex = 0; + + this._suggestionsView.update(this._currentCompletions, this._selectedCompletionIndex); + return true; + } + + this.hide(); + return false; + } + + show(bounds, padding) + { + if (!bounds) + return; + + this._suggestionsView.show(bounds.pad(padding || 0)); + } + + hide() + { + if (this._suggestionsView.isHandlingClickEvent()) + return; + + this._suggestionsView.hide(); + } +}; + +WebInspector.VisualStyleCompletionsController.Event = { + CompletionSelected: "visual-style-completions-controller-completion-selected" +}; diff --git a/Source/WebInspectorUI/UserInterface/Controllers/WorkerManager.js b/Source/WebInspectorUI/UserInterface/Controllers/WorkerManager.js new file mode 100644 index 000000000..99cd3f6ee --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Controllers/WorkerManager.js @@ -0,0 +1,69 @@ +/* + * Copyright (C) 2016 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.WorkerManager = class WorkerManager extends WebInspector.Object +{ + constructor() + { + super(); + + this._connections = new Map; + + if (window.WorkerAgent) + WorkerAgent.enable(); + } + + // Public + + workerCreated(workerId, url) + { + let connection = new InspectorBackend.WorkerConnection(workerId); + let workerTarget = new WebInspector.WorkerTarget(workerId, url, connection); + WebInspector.targetManager.addTarget(workerTarget); + + this._connections.set(workerId, connection); + + // Unpause the worker now that we have sent all initialization messages. + WorkerAgent.initialized(workerId); + } + + workerTerminated(workerId) + { + let connection = this._connections.take(workerId); + + WebInspector.targetManager.removeTarget(connection.target); + } + + dispatchMessageFromWorker(workerId, message) + { + let connection = this._connections.get(workerId); + + console.assert(connection); + if (!connection) + return; + + connection.dispatch(message); + } +}; diff --git a/Source/WebInspectorUI/UserInterface/CookieIcon.css b/Source/WebInspectorUI/UserInterface/CookieIcon.css deleted file mode 100644 index 95f3e6365..000000000 --- a/Source/WebInspectorUI/UserInterface/CookieIcon.css +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.cookie-icon .icon { - content: -webkit-image-set(url(Images/Cookie.png) 1x, url(Images/Cookie@2x.png) 2x); -} diff --git a/Source/WebInspectorUI/UserInterface/CookieStorageContentView.css b/Source/WebInspectorUI/UserInterface/CookieStorageContentView.css deleted file mode 100644 index 8eb7df1c9..000000000 --- a/Source/WebInspectorUI/UserInterface/CookieStorageContentView.css +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.content-view.cookie-storage > .data-grid { - position: absolute; - top: 0; - left: 0; - right: 0; - bottom: 0; - border: none; -} diff --git a/Source/WebInspectorUI/UserInterface/CookieStorageContentView.js b/Source/WebInspectorUI/UserInterface/CookieStorageContentView.js deleted file mode 100644 index f378dd641..000000000 --- a/Source/WebInspectorUI/UserInterface/CookieStorageContentView.js +++ /dev/null @@ -1,262 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.CookieStorageContentView = function(representedObject) -{ - WebInspector.ContentView.call(this, representedObject); - - this.element.classList.add(WebInspector.CookieStorageContentView.StyleClassName); - - this.update(); -}; - -WebInspector.CookieStorageContentView.StyleClassName = "cookie-storage"; - -WebInspector.CookieStorageContentView.prototype = { - constructor: WebInspector.CookieStorageContentView, - - // Public - - update: function() - { - function callback(error, cookies) - { - if (error) - return; - - this._cookies = this._filterCookies(cookies); - this._rebuildTable(); - } - - PageAgent.getCookies(callback.bind(this)); - }, - - updateLayout: function() - { - if (this._dataGrid) - this._dataGrid.updateLayout(); - }, - - saveToCookie: function(cookie) - { - cookie.type = WebInspector.ContentViewCookieType.CookieStorage; - cookie.host = this.representedObject.host; - }, - - get scrollableElements() - { - if (!this._dataGrid) - return []; - return [this._dataGrid.scrollContainer]; - }, - - // Private - - _rebuildTable: function() - { - // FIXME: If there are no cookies, do we want to show an empty datagrid, or do something like the old - // inspector and show some text saying there are no cookies? - if (!this._dataGrid) { - var columns = { 0: {}, 1: {}, 2: {}, 3: {}, 4: {}, 5: {}, 6: {}, 7: {} }; - columns[0].title = WebInspector.UIString("Name"); - columns[0].sortable = true; - columns[0].width = "24%"; - columns[1].title = WebInspector.UIString("Value"); - columns[1].sortable = true; - columns[1].width = "34%"; - columns[2].title = WebInspector.UIString("Domain"); - columns[2].sortable = true; - columns[2].width = "7%"; - columns[3].title = WebInspector.UIString("Path"); - columns[3].sortable = true; - columns[3].width = "7%"; - columns[4].title = WebInspector.UIString("Expires"); - columns[4].sortable = true; - columns[4].width = "7%"; - columns[5].title = WebInspector.UIString("Size"); - columns[5].aligned = "right"; - columns[5].sortable = true; - columns[5].width = "7%"; - columns[6].title = WebInspector.UIString("HTTP"); - columns[6].aligned = "centered"; - columns[6].sortable = true; - columns[6].width = "7%"; - columns[7].title = WebInspector.UIString("Secure"); - columns[7].aligned = "centered"; - columns[7].sortable = true; - columns[7].width = "7%"; - - this._dataGrid = new WebInspector.DataGrid(columns, null, this._deleteCallback.bind(this)); - this._dataGrid.addEventListener(WebInspector.DataGrid.Event.SortChanged, this._rebuildTable, this); - - this.element.appendChild(this._dataGrid.element); - this._dataGrid.updateLayout(); - } - - console.assert(this._dataGrid); - this._dataGrid.removeChildren(); - - this._sortCookies(this._cookies); - - for (var i = 0; i < this._cookies.length; ++i) { - const cookie = this._cookies[i]; - - var data = {}; - data[0] = cookie.name; - data[1] = cookie.value; - data[2] = cookie.domain || ""; - data[3] = cookie.path || ""; - - if (cookie.type === WebInspector.CookieType.Request) - data[4] = ""; - else - data[4] = cookie.session ? WebInspector.UIString("Session") : new Date(cookie.expires).toLocaleString(); - - data[5] = Number.bytesToString(cookie.size); - const checkmark = "\u2713"; - data[6] = cookie.httpOnly ? checkmark : ""; - data[7] = cookie.secure ? checkmark : ""; - - var node = new WebInspector.DataGridNode(data); - node.cookie = cookie; - node.selectable = true; - - this._dataGrid.appendChild(node); - } - }, - - _filterCookies: function(cookies) - { - var filteredCookies = []; - var resourcesForDomain = []; - - var frames = WebInspector.frameResourceManager.frames; - for (var i = 0; i < frames.length; ++i) { - var resources = frames[i].resources; - for (var j = 0; j < resources.length; ++j) { - var urlComponents = resources[j].urlComponents; - if (urlComponents && urlComponents.host && urlComponents.host === this.representedObject.host) - resourcesForDomain.push(resources[j].url); - } - - // The main resource isn't always in the list of resources, make sure to add it to the list of resources - // we get the URLs from. - var mainResourceURLComponents = frames[i].mainResource.urlComponents; - if (mainResourceURLComponents && mainResourceURLComponents.host && mainResourceURLComponents.host == this.representedObject.host) - resourcesForDomain.push(frames[i].mainResource.url); - } - - for (var i = 0; i < cookies.length; ++i) { - for (var j = 0; j < resourcesForDomain.length; ++j) { - if (WebInspector.cookieMatchesResourceURL(cookies[i], resourcesForDomain[j])) { - filteredCookies.push(cookies[i]); - break; - } - } - } - - return filteredCookies; - }, - - _sortCookies: function(cookies) - { - var sortDirection = this._dataGrid.sortOrder === "ascending" ? 1 : -1; - - function localeCompare(field, cookie1, cookie2) - { - return sortDirection * (cookie1[field] + "").localeCompare(cookie2[field] + "") - } - - function numberCompare(field, cookie1, cookie2) - { - return sortDirection * (cookie1[field] - cookie2[field]); - } - - function expiresCompare(cookie1, cookie2) - { - if (cookie1.session !== cookie2.session) - return sortDirection * (cookie1.session ? 1 : -1); - - if (cookie1.session) - return 0; - - return sortDirection * (cookie1.expires - cookie2.expires); - } - - var comparator; - switch (parseInt(this._dataGrid.sortColumnIdentifier, 10)) { - case 0: comparator = localeCompare.bind(this, "name"); break; - case 1: comparator = localeCompare.bind(this, "value"); break; - case 2: comparator = localeCompare.bind(this, "domain"); break; - case 3: comparator = localeCompare.bind(this, "path"); break; - case 4: comparator = expiresCompare; break; - case 5: comparator = numberCompare.bind(this, "size"); break; - case 6: comparator = localeCompare.bind(this, "httpOnly"); break; - case 7: comparator = localeCompare.bind(this, "secure"); break; - default: localeCompare.bind(this, "name"); - } - - cookies.sort(comparator); - }, - - _deleteCallback: function(node) - { - if (!node || !node.cookie) - return; - - var cookie = node.cookie; - var cookieURL = (cookie.secure ? "https://" : "http://") + cookie.domain + cookie.path; - - // COMPATIBILITY (iOS 6): PageAgent.deleteCookie used to take 'domain', now takes 'url'. Send both. - PageAgent.deleteCookie.invoke({cookieName: cookie.name, domain: cookie.domain, url: cookieURL}); - - this.update(); - } -}; - -WebInspector.CookieStorageContentView.prototype.__proto__ = WebInspector.ContentView.prototype; - -WebInspector.cookieMatchesResourceURL = function(cookie, resourceURL) -{ - var parsedURL = parseURL(resourceURL); - if (!parsedURL || !WebInspector.cookieDomainMatchesResourceDomain(cookie.domain, parsedURL.host)) - return false; - - return (parsedURL.path.startsWith(cookie.path) - && (!cookie.port || parsedURL.port == cookie.port) - && (!cookie.secure || parsedURL.scheme === "https")); -} - -WebInspector.cookieDomainMatchesResourceDomain = function(cookieDomain, resourceDomain) -{ - if (cookieDomain.charAt(0) !== '.') - return resourceDomain === cookieDomain; - return !!resourceDomain.match(new RegExp("^([^\\.]+\\.)?" + cookieDomain.substring(1).escapeForRegExp() + "$"), "i"); -} - -WebInspector.CookieType = { - Request: 0, - Response: 1 -}; diff --git a/Source/WebInspectorUI/UserInterface/CookieStorageObject.js b/Source/WebInspectorUI/UserInterface/CookieStorageObject.js deleted file mode 100644 index d1ca96eb0..000000000 --- a/Source/WebInspectorUI/UserInterface/CookieStorageObject.js +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.CookieStorageObject = function(host) -{ - this._host = host; -}; - -WebInspector.CookieStorageObject.TypeIdentifier = "cookie-storage"; -WebInspector.CookieStorageObject.CookieHostCookieKey = "cookie-storage-host"; - -WebInspector.CookieStorageObject.prototype = { - constructor: WebInspector.CookieStorageObject, - - get host() - { - return this._host; - }, - - saveIdentityToCookie: function(cookie) - { - cookie[WebInspector.CookieStorageObject.CookieHostCookieKey] = this.host; - } - // FIXME: This class will need to look up cookies that are set for this host. -}; diff --git a/Source/WebInspectorUI/UserInterface/CookieStorageTreeElement.js b/Source/WebInspectorUI/UserInterface/CookieStorageTreeElement.js deleted file mode 100644 index 15c9937b8..000000000 --- a/Source/WebInspectorUI/UserInterface/CookieStorageTreeElement.js +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.CookieStorageTreeElement = function(representedObject) -{ - console.assert(representedObject instanceof WebInspector.CookieStorageObject); - - WebInspector.StorageTreeElement.call(this, WebInspector.CookieStorageTreeElement.CookieIconStyleClassName, WebInspector.displayNameForHost(representedObject.host), representedObject); -}; - -WebInspector.CookieStorageTreeElement.CookieIconStyleClassName = "cookie-icon"; - -WebInspector.CookieStorageTreeElement.prototype = { - constructor: WebInspector.CookieStorageTreeElement, - - // Public - - get name() - { - return this.representedObject.host; - }, - - get categoryName() - { - return WebInspector.UIString("Cookies"); - } -}; - -WebInspector.CookieStorageTreeElement.prototype.__proto__ = WebInspector.StorageTreeElement.prototype; diff --git a/Source/WebInspectorUI/UserInterface/DOMDetailsSidebarPanel.js b/Source/WebInspectorUI/UserInterface/DOMDetailsSidebarPanel.js deleted file mode 100644 index 66d1d4110..000000000 --- a/Source/WebInspectorUI/UserInterface/DOMDetailsSidebarPanel.js +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.DOMDetailsSidebarPanel = function(identifier, displayName, singularDisplayName, image, keyboardShortcutKey, element) { - WebInspector.DetailsSidebarPanel.call(this, identifier, displayName, singularDisplayName, image, keyboardShortcutKey, element); - - this.element.addEventListener("click", this._mouseWasClicked.bind(this), true); - - this._domNode = null; -}; - -WebInspector.DOMDetailsSidebarPanel.prototype = { - constructor: WebInspector.DOMDetailsSidebarPanel, - - // Public - - inspect: function(objects) - { - // Convert to a single item array if needed. - if (!(objects instanceof Array)) - objects = [objects]; - - var nodeToInspect = null; - - // Iterate over the objects to find a WebInspector.DOMNode to inspect. - for (var i = 0; i < objects.length; ++i) { - if (objects[i] instanceof WebInspector.DOMNode) { - nodeToInspect = objects[i]; - break; - } - } - - if (nodeToInspect && !this.supportsDOMNode(nodeToInspect)) - nodeToInspect = null; - - this.domNode = nodeToInspect; - - return !!this._domNode; - }, - - get domNode() - { - return this._domNode; - }, - - set domNode(domNode) - { - if (domNode === this._domNode) - return; - - if (this._domNode) - this.removeEventListeners(); - - this._domNode = domNode; - - if (this._domNode) - this.addEventListeners(); - - this.needsRefresh(); - }, - - supportsDOMNode: function(nodeToInspect) - { - // Implemented by subclasses. - return true; - }, - - addEventListeners: function() - { - // Implemented by subclasses. - }, - - removeEventListeners: function() - { - // Implemented by subclasses. - }, - - // Private - - _mouseWasClicked: function(event) - { - if (this._domNode && this._domNode.ownerDocument) { - var mainResource = WebInspector.frameResourceManager.resourceForURL(this._domNode.ownerDocument.documentURL); - if (mainResource) - var parentFrame = mainResource.parentFrame; - } - - WebInspector.handlePossibleLinkClick(event, parentFrame); - } -}; - -WebInspector.DOMDetailsSidebarPanel.prototype.__proto__ = WebInspector.DetailsSidebarPanel.prototype; diff --git a/Source/WebInspectorUI/UserInterface/DOMNode.js b/Source/WebInspectorUI/UserInterface/DOMNode.js deleted file mode 100644 index ee002783c..000000000 --- a/Source/WebInspectorUI/UserInterface/DOMNode.js +++ /dev/null @@ -1,690 +0,0 @@ -/* - * Copyright (C) 2009, 2010 Google Inc. All rights reserved. - * Copyright (C) 2009 Joseph Pecoraro - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/** - * @constructor - * @param {WebInspector.DOMAgent} domAgent - * @param {?WebInspector.DOMNode} doc - * @param {boolean} isInShadowTree - * @param {DOMAgent.Node} payload - */ -WebInspector.DOMNode = function(domAgent, doc, isInShadowTree, payload) { - WebInspector.Object.call(this); - - this._domAgent = domAgent; - this._isInShadowTree = isInShadowTree; - - this.id = payload.nodeId; - domAgent._idToDOMNode[this.id] = this; - - this._nodeType = payload.nodeType; - this._nodeName = payload.nodeName; - this._localName = payload.localName; - this._nodeValue = payload.nodeValue; - - if (this._nodeType === Node.DOCUMENT_NODE) - this.ownerDocument = this; - else - this.ownerDocument = doc; - - this._attributes = []; - this._attributesMap = {}; - if (payload.attributes) - this._setAttributesPayload(payload.attributes); - - this._childNodeCount = payload.childNodeCount; - this._children = null; - this._filteredChildren = null; - this._filteredChildrenNeedsUpdating = true; - - this._nextSibling = null; - this._previousSibling = null; - this.parentNode = null; - - this._enabledPseudoClasses = []; - - this._shadowRoots = []; - if (payload.shadowRoots) { - for (var i = 0; i < payload.shadowRoots.length; ++i) { - var root = payload.shadowRoots[i]; - var node = new WebInspector.DOMNode(this._domAgent, this.ownerDocument, true, root); - this._shadowRoots.push(node); - } - } - - if (payload.children) - this._setChildrenPayload(payload.children); - - if (payload.contentDocument) { - this._contentDocument = new WebInspector.DOMNode(domAgent, null, false, payload.contentDocument); - this._children = [this._contentDocument]; - this._renumber(); - } - - if (this._nodeType === Node.ELEMENT_NODE) { - // HTML and BODY from internal iframes should not overwrite top-level ones. - 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; - if (payload.documentURL) - this.documentURL = payload.documentURL; - } 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.DOCUMENT_NODE) { - this.documentURL = payload.documentURL; - this.xmlVersion = payload.xmlVersion; - } else if (this._nodeType === Node.ATTRIBUTE_NODE) { - this.name = payload.name; - this.value = payload.value; - } -} - -WebInspector.Object.addConstructorFunctions(WebInspector.DOMNode); - -WebInspector.DOMNode.Event = { - EnabledPseudoClassesChanged: "dom-node-enabled-pseudo-classes-did-change", - AttributeModified: "dom-node-attribute-modified", - AttributeRemoved: "dom-node-attribute-removed" -}; - -WebInspector.DOMNode.prototype = { - constructor: WebInspector.DOMNode, - - get children() - { - if (!this._children) - return null; - - if (WebInspector.showShadowDOMSetting.value) - return this._children; - - if (this._filteredChildrenNeedsUpdating) { - this._filteredChildrenNeedsUpdating = false; - this._filteredChildren = this._children.filter(function(node) { - return !node._isInShadowTree; - }); - } - - return this._filteredChildren; - }, - - get firstChild() - { - var children = this.children; - - if (children && children.length > 0) - return children[0]; - - return null; - }, - - get lastChild() - { - var children = this.children; - - if (children && children.length > 0) - return children.lastValue; - - return null; - }, - - get nextSibling() - { - if (WebInspector.showShadowDOMSetting.value) - return this._nextSibling; - - var node = this._nextSibling; - while (node) { - if (!node._isInShadowTree) - return node; - node = node._nextSibling; - } - return null; - }, - - get previousSibling() - { - if (WebInspector.showShadowDOMSetting.value) - return this._previousSibling; - - var node = this._previousSibling; - while (node) { - if (!node._isInShadowTree) - return node; - node = node._previousSibling; - } - return null; - }, - - get childNodeCount() - { - var children = this.children; - if (children) - return children.length; - - if (WebInspector.showShadowDOMSetting.value) - return this._childNodeCount + this._shadowRoots.length; - - return this._childNodeCount; - }, - - set childNodeCount(count) - { - this._childNodeCount = count; - }, - - /** - * @return {boolean} - */ - hasAttributes: function() - { - return this._attributes.length > 0; - }, - - /** - * @return {boolean} - */ - hasChildNodes: function() - { - return this.childNodeCount > 0; - }, - - /** - * @return {boolean} - */ - hasShadowRoots: function() - { - return !!this._shadowRoots.length; - }, - - /** - * @return {boolean} - */ - isInShadowTree: function() - { - return this._isInShadowTree; - }, - - /** - * @return {number} - */ - nodeType: function() - { - return this._nodeType; - }, - - /** - * @return {string} - */ - nodeName: function() - { - return this._nodeName; - }, - - /** - * @return {string} - */ - nodeNameInCorrectCase: function() - { - return this.isXMLNode() ? this.nodeName() : this.nodeName().toLowerCase(); - }, - - /** - * @param {string} name - * @param {function()=} callback - */ - setNodeName: function(name, callback) - { - DOMAgent.setNodeName(this.id, name, this._makeUndoableCallback(callback)); - }, - - /** - * @return {string} - */ - localName: function() - { - return this._localName; - }, - - /** - * @return {string} - */ - nodeValue: function() - { - return this._nodeValue; - }, - - /** - * @param {string} value - * @param {function(?Protocol.Error)=} callback - */ - setNodeValue: function(value, callback) - { - DOMAgent.setNodeValue(this.id, value, this._makeUndoableCallback(callback)); - }, - - /** - * @param {string} name - * @return {string} - */ - getAttribute: function(name) - { - var attr = this._attributesMap[name]; - return attr ? attr.value : undefined; - }, - - /** - * @param {string} name - * @param {string} text - * @param {function()=} callback - */ - setAttribute: function(name, text, callback) - { - DOMAgent.setAttributesAsText(this.id, text, name, this._makeUndoableCallback(callback)); - }, - - /** - * @param {string} name - * @param {string} value - * @param {function()=} callback - */ - setAttributeValue: function(name, value, callback) - { - DOMAgent.setAttributeValue(this.id, name, value, this._makeUndoableCallback(callback)); - }, - - /** - * @return {Object} - */ - attributes: function() - { - return this._attributes; - }, - - /** - * @param {string} name - * @param {function()=} callback - */ - removeAttribute: function(name, callback) - { - function mycallback(error, success) - { - 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._makeUndoableCallback(callback)(error); - } - DOMAgent.removeAttribute(this.id, name, mycallback.bind(this)); - }, - - /** - * @param {function(Array.)=} callback - */ - getChildNodes: function(callback) - { - if (this.children) { - if (callback) - callback(this.children); - return; - } - - /** - * @this {WebInspector.DOMNode} - * @param {?Protocol.Error} error - */ - function mycallback(error) { - if (!error && callback) - callback(this.children); - } - - DOMAgent.requestChildNodes(this.id, mycallback.bind(this)); - }, - - /** - * @param {number} depth - * @param {function(Array.)=} callback - */ - getSubtree: function(depth, callback) - { - /** - * @this {WebInspector.DOMNode} - * @param {?Protocol.Error} error - */ - function mycallback(error) - { - if (callback) - callback(error ? null : this.children); - } - - DOMAgent.requestChildNodes(this.id, depth, mycallback.bind(this)); - }, - - /** - * @param {function(?Protocol.Error)=} callback - */ - getOuterHTML: function(callback) - { - DOMAgent.getOuterHTML(this.id, callback); - }, - - /** - * @param {string} html - * @param {function(?Protocol.Error)=} callback - */ - setOuterHTML: function(html, callback) - { - DOMAgent.setOuterHTML(this.id, html, this._makeUndoableCallback(callback)); - }, - - /** - * @param {function(?Protocol.Error)=} callback - */ - removeNode: function(callback) - { - DOMAgent.removeNode(this.id, this._makeUndoableCallback(callback)); - }, - - copyNode: function() - { - function copy(error, text) - { - if (!error) - InspectorFrontendHost.copyText(text); - } - DOMAgent.getOuterHTML(this.id, copy); - }, - - /** - * @param {function(?Protocol.Error)=} callback - */ - eventListeners: function(callback) - { - DOMAgent.getEventListenersForNode(this.id, callback); - }, - - /** - * @return {string} - */ - path: function() - { - var path = []; - var node = this; - while (node && "index" in node && node._nodeName.length) { - path.push([node.index, node._nodeName]); - node = node.parentNode; - } - path.reverse(); - return path.join(","); - }, - - /** - * @param {boolean} justSelector - * @return {string} - */ - appropriateSelectorFor: function(justSelector) - { - var lowerCaseName = this.localName() || this.nodeName().toLowerCase(); - - var id = this.getAttribute("id"); - if (id) { - if (/[\s'"]/.test(id)) { - id = id.replace(/\\/g, "\\\\").replace(/\"/g, "\\\""); - selector = lowerCaseName + "[id=\"" + id + "\"]"; - } else - selector = "#" + id; - return (justSelector ? selector : lowerCaseName + selector); - } - - var className = this.getAttribute("class"); - if (className) { - var selector = "." + className.trim().replace(/\s+/, "."); - return (justSelector ? selector : lowerCaseName + selector); - } - - if (lowerCaseName === "input" && this.getAttribute("type")) - return lowerCaseName + "[type=\"" + this.getAttribute("type") + "\"]"; - - return lowerCaseName; - }, - - /** - * @param {WebInspector.DOMNode} node - * @return {boolean} - */ - isAncestor: function(node) - { - if (!node) - return false; - - var currentNode = node.parentNode; - while (currentNode) { - if (this === currentNode) - return true; - currentNode = currentNode.parentNode; - } - return false; - }, - - /** - * @param {WebInspector.DOMNode} descendant - * @return {boolean} - */ - isDescendant: function(descendant) - { - return descendant !== null && descendant.isAncestor(this); - }, - - /** - * @param {Array.} attrs - */ - _setAttributesPayload: function(attrs) - { - this._attributes = []; - this._attributesMap = {}; - for (var i = 0; i < attrs.length; i += 2) - this._addAttribute(attrs[i], attrs[i + 1]); - }, - - /** - * @param {WebInspector.DOMNode} prev - * @param {DOMAgent.Node} payload - * @return {WebInspector.DOMNode} - */ - _insertChild: function(prev, payload) - { - var node = new WebInspector.DOMNode(this._domAgent, this.ownerDocument, this._isInShadowTree, payload); - if (!prev) { - if (!this._children) { - // First node - this._children = this._shadowRoots.concat([node]); - } else - this._children.unshift(node); - } else - this._children.splice(this._children.indexOf(prev) + 1, 0, node); - this._renumber(); - return node; - }, - - /** - * @param {WebInspector.DOMNode} node - */ - _removeChild: function(node) - { - this._children.splice(this._children.indexOf(node), 1); - node.parentNode = null; - this._renumber(); - }, - - /** - * @param {Array.} payloads - */ - _setChildrenPayload: function(payloads) - { - // We set children in the constructor. - if (this._contentDocument) - return; - - this._children = this._shadowRoots.slice(); - for (var i = 0; i < payloads.length; ++i) { - var payload = payloads[i]; - var node = new WebInspector.DOMNode(this._domAgent, this.ownerDocument, this._isInShadowTree, payload); - this._children.push(node); - } - this._renumber(); - }, - - _renumber: function() - { - this._filteredChildrenNeedsUpdating = true; - - var childNodeCount = this._children.length; - if (childNodeCount === 0) - return; - - for (var i = 0; i < childNodeCount; ++i) { - var child = this._children[i]; - child.index = i; - child._nextSibling = i + 1 < childNodeCount ? this._children[i + 1] : null; - child._previousSibling = i - 1 >= 0 ? this._children[i - 1] : null; - child.parentNode = this; - } - }, - - /** - * @param {string} name - * @param {string} value - */ - _addAttribute: function(name, value) - { - var attr = { - name: name, - value: value, - _node: this - }; - this._attributesMap[name] = attr; - this._attributes.push(attr); - }, - - /** - * @param {string} name - * @param {string} value - */ - _setAttribute: function(name, value) - { - var attr = this._attributesMap[name]; - if (attr) - attr.value = value; - else - this._addAttribute(name, value); - }, - - /** - * @param {string} name - */ - _removeAttribute: function(name) - { - var attr = this._attributesMap[name]; - if (attr) { - this._attributes.remove(attr); - delete this._attributesMap[name]; - } - }, - - /** - * @param {WebInspector.DOMNode} targetNode - * @param {?WebInspector.DOMNode} anchorNode - * @param {function(?Protocol.Error)=} callback - */ - moveTo: function(targetNode, anchorNode, callback) - { - DOMAgent.moveTo(this.id, targetNode.id, anchorNode ? anchorNode.id : undefined, this._makeUndoableCallback(callback)); - }, - - /** - * @return {boolean} - */ - isXMLNode: function() - { - return !!this.ownerDocument && !!this.ownerDocument.xmlVersion; - }, - - get enabledPseudoClasses() - { - return this._enabledPseudoClasses; - }, - - setPseudoClassEnabled: function(pseudoClass, enabled) - { - var pseudoClasses = this._enabledPseudoClasses; - if (enabled) { - if (pseudoClasses.contains(pseudoClass)) - return; - pseudoClasses.push(pseudoClass); - } else { - if (!pseudoClasses.contains(pseudoClass)) - return; - pseudoClasses.remove(pseudoClass); - } - - function changed(error) - { - if (!error) - this.dispatchEventToListeners(WebInspector.DOMNode.Event.EnabledPseudoClassesChanged); - } - - CSSAgent.forcePseudoState(this.id, pseudoClasses, changed.bind(this)); - }, - - _makeUndoableCallback: function(callback) - { - return function(error) - { - if (!error) - DOMAgent.markUndoableState(); - - if (callback) - callback.apply(null, arguments); - }; - } -} - -WebInspector.DOMNode.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/DOMNodeDetailsSidebarPanel.js b/Source/WebInspectorUI/UserInterface/DOMNodeDetailsSidebarPanel.js deleted file mode 100644 index 3062852e5..000000000 --- a/Source/WebInspectorUI/UserInterface/DOMNodeDetailsSidebarPanel.js +++ /dev/null @@ -1,281 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.DOMNodeDetailsSidebarPanel = function() { - WebInspector.DOMDetailsSidebarPanel.call(this, "dom-node-details", WebInspector.UIString("Node"), WebInspector.UIString("Node"), "Images/NavigationItemAngleBrackets.svg", "2"); - - WebInspector.domTreeManager.addEventListener(WebInspector.DOMTreeManager.Event.AttributeModified, this._attributesChanged, this); - WebInspector.domTreeManager.addEventListener(WebInspector.DOMTreeManager.Event.AttributeRemoved, this._attributesChanged, this); - - this.element.classList.add(WebInspector.DOMNodeDetailsSidebarPanel.StyleClassName); - - this._identityNodeTypeRow = new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("Type")); - this._identityNodeNameRow = new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("Name")); - this._identityNodeValueRow = new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("Value")); - - var identityGroup = new WebInspector.DetailsSectionGroup([this._identityNodeTypeRow, this._identityNodeNameRow, this._identityNodeValueRow]); - var identitySection = new WebInspector.DetailsSection("dom-node-identity", WebInspector.UIString("Identity"), [identityGroup]); - - this._attributesDataGridRow = new WebInspector.DetailsSectionDataGridRow(null, WebInspector.UIString("No Attributes")); - - var attributesGroup = new WebInspector.DetailsSectionGroup([this._attributesDataGridRow]); - var attributesSection = new WebInspector.DetailsSection("dom-node-attributes", WebInspector.UIString("Attributes"), [attributesGroup]); - - this._propertiesRow = new WebInspector.DetailsSectionRow; - - var propertiesGroup = new WebInspector.DetailsSectionGroup([this._propertiesRow]); - var propertiesSection = new WebInspector.DetailsSection("dom-node-properties", WebInspector.UIString("Properties"), [propertiesGroup]); - - this._eventListenersSectionGroup = new WebInspector.DetailsSectionGroup; - var eventListenersSection = new WebInspector.DetailsSection("dom-node-event-listeners", WebInspector.UIString("Event Listeners"), [this._eventListenersSectionGroup]); - - this.element.appendChild(identitySection.element); - this.element.appendChild(attributesSection.element); - this.element.appendChild(propertiesSection.element); - this.element.appendChild(eventListenersSection.element); -}; - -WebInspector.DOMNodeDetailsSidebarPanel.StyleClassName = "dom-node"; -WebInspector.DOMNodeDetailsSidebarPanel.PropertiesObjectGroupName = "dom-node-details-sidebar-properties-object-group"; - -WebInspector.DOMNodeDetailsSidebarPanel.prototype = { - constructor: WebInspector.DOMNodeDetailsSidebarPanel, - - // Public - - refresh: function() - { - var domNode = this.domNode; - if (!domNode) - return; - - this._identityNodeTypeRow.value = this._nodeTypeDisplayName(); - this._identityNodeNameRow.value = domNode.nodeNameInCorrectCase(); - this._identityNodeValueRow.value = domNode.nodeValue(); - - this._refreshAttributes(); - this._refreshProperties(); - this._refreshEventListeners(); - }, - - // Private - - _refreshAttributes: function() - { - this._attributesDataGridRow.dataGrid = this._createAttributesDataGrid(); - }, - - _refreshProperties: function() - { - var domNode = this.domNode; - if (!domNode) - return; - - RuntimeAgent.releaseObjectGroup(WebInspector.DOMNodeDetailsSidebarPanel.PropertiesObjectGroupName); - WebInspector.RemoteObject.resolveNode(domNode, WebInspector.DOMNodeDetailsSidebarPanel.PropertiesObjectGroupName, nodeResolved.bind(this)); - - function nodeResolved(object) - { - if (!object) - return; - - // Bail if the DOM node changed while we were waiting for the async response. - if (this.domNode !== domNode) - return; - - function collectPrototypes() - { - // This builds an object with numeric properties. This is easier than dealing with arrays - // with the way RemoteObject works. Start at 1 since we use parseInt later and parseInt - // returns 0 for non-numeric strings make it ambiguous. - var prototype = this; - var result = []; - var counter = 1; - - while (prototype) { - result[counter++] = prototype; - prototype = prototype.__proto__; - } - - return result; - } - - object.callFunction(collectPrototypes, undefined, nodePrototypesReady.bind(this)); - object.release(); - } - - function nodePrototypesReady(object) - { - if (!object) - return; - - // Bail if the DOM node changed while we were waiting for the async response. - if (this.domNode !== domNode) - return; - - object.getOwnProperties(fillSection.bind(this)); - } - - function fillSection(prototypes) - { - if (!prototypes) - return; - - // Bail if the DOM node changed while we were waiting for the async response. - if (this.domNode !== domNode) - return; - - var element = this._propertiesRow.element; - element.removeChildren(); - - // Get array of prototype user-friendly names. - for (var i = 0; i < prototypes.length; ++i) { - // The only values we care about are numeric, as assigned in collectPrototypes. - if (!parseInt(prototypes[i].name, 10)) - continue; - - var prototype = prototypes[i].value; - var title = prototype.description; - if (title.match(/Prototype$/)) - title = title.replace(/Prototype$/, WebInspector.UIString(" (Prototype)")); - else if (title === "Object") - title = title + WebInspector.UIString(" (Prototype)"); - - var propertiesSection = new WebInspector.ObjectPropertiesSection(prototype); - - var detailsSection = new WebInspector.DetailsSection(prototype.description.hash + "-prototype-properties", title, null, null, true); - detailsSection.groups[0].rows = [new WebInspector.DetailsSectionPropertiesRow(propertiesSection)]; - - element.appendChild(detailsSection.element); - } - } - }, - - _refreshEventListeners: function() - { - var domNode = this.domNode; - if (!domNode) - return; - - domNode.eventListeners(eventListenersCallback.bind(this)); - - function eventListenersCallback(error, eventListeners) - { - if (error) - return; - - // Bail if the DOM node changed while we were waiting for the async response. - if (this.domNode !== domNode) - return; - - var eventListenerTypes = []; - var eventListenerSections = {}; - for (var i = 0; i < eventListeners.length; ++i) { - var eventListener = eventListeners[i]; - eventListener.node = WebInspector.domTreeManager.nodeForId(eventListener.nodeId); - - var type = eventListener.type; - var section = eventListenerSections[type]; - if (!section) { - section = new WebInspector.EventListenerSection(type, domNode.id); - eventListenerSections[type] = section; - eventListenerTypes.push(type); - } - - section.addListener(eventListener); - } - - if (!eventListenerTypes.length) { - var emptyRow = new WebInspector.DetailsSectionRow(WebInspector.UIString("No Event Listeners")); - emptyRow.showEmptyMessage(); - this._eventListenersSectionGroup.rows = [emptyRow]; - return; - } - - eventListenerTypes.sort(); - - var rows = []; - for (var i = 0; i < eventListenerTypes.length; ++i) - rows.push(eventListenerSections[eventListenerTypes[i]]); - this._eventListenersSectionGroup.rows = rows; - } - }, - - _attributesChanged: function(event) - { - if (event.data.node !== this.domNode) - return; - this._refreshAttributes(); - }, - - _nodeTypeDisplayName: function() - { - switch (this.domNode.nodeType()) { - case Node.ELEMENT_NODE: - return WebInspector.UIString("Element"); - case Node.TEXT_NODE: - return WebInspector.UIString("Text Node"); - case Node.COMMENT_NODE: - return WebInspector.UIString("Comment"); - case Node.DOCUMENT_NODE: - return WebInspector.UIString("Document"); - case Node.DOCUMENT_TYPE_NODE: - return WebInspector.UIString("Document Type"); - case Node.DOCUMENT_FRAGMENT_NODE: - return WebInspector.UIString("Document Fragment"); - case Node.CDATA_SECTION_NODE: - return WebInspector.UIString("Character Data"); - case Node.PROCESSING_INSTRUCTION_NODE: - return WebInspector.UIString("Processing Instruction"); - default: - console.error("Unknown DOM node type: ", this.domNode.nodeType()); - return this.domNode.nodeType(); - } - }, - - _createAttributesDataGrid: function() - { - var domNode = this.domNode; - if (!domNode || !domNode.hasAttributes()) - return null; - - var columns = {name: {title: WebInspector.UIString("Name"), width: "30%"}, value: {title: WebInspector.UIString("Value")}}; - var dataGrid = new WebInspector.DataGrid(columns); - - var attributes = domNode.attributes(); - for (var i = 0; i < attributes.length; ++i) { - var attribute = attributes[i]; - - var node = new WebInspector.DataGridNode({name: attribute.name, value: attribute.value || ""}, false); - node.selectable = true; - - dataGrid.appendChild(node); - } - - return dataGrid; - } -}; - -WebInspector.DOMNodeDetailsSidebarPanel.prototype.__proto__ = WebInspector.DOMDetailsSidebarPanel.prototype; diff --git a/Source/WebInspectorUI/UserInterface/DOMNodeStyles.js b/Source/WebInspectorUI/UserInterface/DOMNodeStyles.js deleted file mode 100644 index d5c5801b5..000000000 --- a/Source/WebInspectorUI/UserInterface/DOMNodeStyles.js +++ /dev/null @@ -1,1050 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.DOMNodeStyles = function(node) -{ - WebInspector.Object.call(this); - - console.assert(node); - this._node = node || null; - - this._rulesMap = {}; - this._styleDeclarationsMap = {}; - - this._matchedRules = []; - this._inheritedRules = []; - this._pseudoElements = {}; - this._inlineStyle = null; - this._attributesStyle = null; - this._computedStyle = null; - this._orderedStyles = []; - this._stylesNeedingTextCommited = []; - - this._propertyNameToEffectivePropertyMap = {}; - - this.refresh(); -}; - -WebInspector.Object.addConstructorFunctions(WebInspector.DOMNodeStyles); - -WebInspector.DOMNodeStyles.Event = { - NeedsRefresh: "dom-node-styles-needs-refresh", - Refreshed: "dom-node-styles-refreshed" -}; - -WebInspector.DOMNodeStyles.prototype = { - constructor: WebInspector.DOMNodeStyles, - - // Public - - get node() - { - return this._node; - }, - - get needsRefresh() - { - return this._refreshPending || this._needsRefresh; - }, - - refreshIfNeeded: function() - { - if (!this._needsRefresh) - return; - this.refresh(); - }, - - refresh: function() - { - if (this._refreshPending) - return; - - this._needsRefresh = false; - this._refreshPending = true; - - function parseRuleMatchArrayPayload(matchArray, node, inherited) - { - var result = []; - - var ruleOccurrences = {}; - - // Iterate in reverse order to match the cascade order. - for (var i = matchArray.length - 1; i >= 0; --i) { - // COMPATIBILITY (iOS 6): This was just an array of rules, now it is an array of matches that have - // a 'rule' property. Support both here. And 'matchingSelectors' does not exist on iOS 6. - var matchedSelectorIndices = matchArray[i].matchingSelectors || []; - var rule = this._parseRulePayload(matchArray[i].rule || matchArray[i], matchedSelectorIndices, node, inherited, ruleOccurrences); - if (!rule) - continue; - result.push(rule); - } - - return result; - } - - function fetchedMatchedStyles(error, matchedRulesPayload, pseudoElementRulesPayload, inheritedRulesPayload) - { - matchedRulesPayload = matchedRulesPayload || []; - pseudoElementRulesPayload = pseudoElementRulesPayload || []; - inheritedRulesPayload = inheritedRulesPayload || []; - - // Move the current maps to previous. - this._previousRulesMap = this._rulesMap; - this._previousStyleDeclarationsMap = this._styleDeclarationsMap; - - // Clear the current maps. - this._rulesMap = {}; - this._styleDeclarationsMap = {}; - - this._matchedRules = parseRuleMatchArrayPayload.call(this, matchedRulesPayload, this._node); - - this._pseudoElements = {}; - for (var i = 0; i < pseudoElementRulesPayload.length; ++i) { - var pseudoElementRulePayload = pseudoElementRulesPayload[i]; - - // COMPATIBILITY (iOS 6): The entry payload had a 'rules' property, now it has a 'matches' property. Support both here. - var pseudoElementRules = parseRuleMatchArrayPayload.call(this, pseudoElementRulePayload.matches || pseudoElementRulePayload.rules, this._node); - this._pseudoElements[pseudoElementRulePayload.pseudoId] = {matchedRules: pseudoElementRules}; - } - - this._inheritedRules = []; - - var i = 0; - var currentNode = this._node.parentNode; - while (currentNode && i < inheritedRulesPayload.length) { - var inheritedRulePayload = inheritedRulesPayload[i]; - - var inheritedRuleInfo = {node: currentNode}; - inheritedRuleInfo.inlineStyle = inheritedRulePayload.inlineStyle ? this._parseStyleDeclarationPayload(inheritedRulePayload.inlineStyle, currentNode, true, WebInspector.CSSStyleDeclaration.Type.Inline) : null; - inheritedRuleInfo.matchedRules = inheritedRulePayload.matchedCSSRules ? parseRuleMatchArrayPayload.call(this, inheritedRulePayload.matchedCSSRules, currentNode, true) : []; - - if (inheritedRuleInfo.inlineStyle || inheritedRuleInfo.matchedRules.length) - this._inheritedRules.push(inheritedRuleInfo); - - currentNode = currentNode.parentNode; - ++i; - } - } - - function fetchedInlineStyles(error, inlineStylePayload, attributesStylePayload) - { - this._inlineStyle = inlineStylePayload ? this._parseStyleDeclarationPayload(inlineStylePayload, this._node, false, WebInspector.CSSStyleDeclaration.Type.Inline) : null; - this._attributesStyle = attributesStylePayload ? this._parseStyleDeclarationPayload(attributesStylePayload, this._node, false, WebInspector.CSSStyleDeclaration.Type.Attribute) : null; - - this._updateStyleCascade(); - } - - function fetchedComputedStyle(error, computedPropertiesPayload) - { - var properties = []; - for (var i = 0; computedPropertiesPayload && i < computedPropertiesPayload.length; ++i) { - var propertyPayload = computedPropertiesPayload[i]; - - var canonicalName = WebInspector.cssStyleManager.canonicalNameForPropertyName(propertyPayload.name); - propertyPayload.implicit = !this._propertyNameToEffectivePropertyMap[canonicalName]; - - var property = this._parseStylePropertyPayload(propertyPayload, NaN, this._computedStyle); - properties.push(property); - } - - if (this._computedStyle) - this._computedStyle.update(null, properties); - else - this._computedStyle = new WebInspector.CSSStyleDeclaration(this, null, null, WebInspector.CSSStyleDeclaration.Type.Computed, this._node, false, null, properties); - - this._refreshPending = false; - - var significantChange = this._previousSignificantChange || false; - if (!significantChange) { - for (var key in this._styleDeclarationsMap) { - // Check if the same key exists in the previous map and has the same style objects. - if (key in this._previousStyleDeclarationsMap && Object.shallowEqual(this._styleDeclarationsMap[key], this._previousStyleDeclarationsMap[key])) - continue; - - if (!this._includeUserAgentRulesOnNextRefresh) { - // We can assume all the styles with the same key are from the same stylesheet and rule, so we only check the first. - var firstStyle = this._styleDeclarationsMap[key][0]; - if (firstStyle && firstStyle.ownerRule && firstStyle.ownerRule.type === WebInspector.CSSRule.Type.UserAgent) { - // User Agent styles get different identifiers after some edits. This would cause us to fire a significant refreshed - // event more than it is helpful. And since the user agent stylesheet is static it shouldn't match differently - // between refreshes for the same node. This issue is tracked by: https://webkit.org/b/110055 - continue; - } - } - - // This key is new or has different style objects than before. This is a significant change. - significantChange = true; - break; - } - } - - if (!significantChange) { - for (var key in this._previousStyleDeclarationsMap) { - // Check if the same key exists in current map. If it does exist it was already checked for equality above. - if (key in this._styleDeclarationsMap) - continue; - - if (!this._includeUserAgentRulesOnNextRefresh) { - // See above for why we skip user agent style rules. - var firstStyle = this._previousStyleDeclarationsMap[key][0]; - if (firstStyle && firstStyle.ownerRule && firstStyle.ownerRule.type === WebInspector.CSSRule.Type.UserAgent) - continue; - } - - // This key no longer exists. This is a significant change. - significantChange = true; - break; - } - } - - delete this._includeUserAgentRulesOnNextRefresh; - - // Delete the previous maps now that any reused rules and style have been moved over. - delete this._previousRulesMap; - delete this._previousStyleDeclarationsMap; - - var styleToCommit = this._stylesNeedingTextCommited.shift(); - if (styleToCommit) { - // Remember the significant change flag so we can pass it along when the pending style - // changes trigger a refresh. If we wait to scan later we might not find a significant change - // and fail to tell listeners about it. - this._previousSignificantChange = significantChange; - - this.changeStyleText(styleToCommit, styleToCommit.__pendingText); - - return; - } - - // Delete the previous saved significant change flag so we rescan for a significant change next time. - delete this._previousSignificantChange; - - this.dispatchEventToListeners(WebInspector.DOMNodeStyles.Event.Refreshed, {significantChange: significantChange}); - } - - CSSAgent.getMatchedStylesForNode.invoke({nodeId: this._node.id, includePseudo: true, includeInherited: true}, fetchedMatchedStyles.bind(this)); - CSSAgent.getInlineStylesForNode.invoke({nodeId: this._node.id}, fetchedInlineStyles.bind(this)); - CSSAgent.getComputedStyleForNode.invoke({nodeId: this._node.id}, fetchedComputedStyle.bind(this)); - }, - - addRule: function(selector) - { - function addedRule(error, rulePayload) - { - if (error) - return; - - DOMAgent.markUndoableState(); - - this.refresh(); - } - - selector = selector || this._node.appropriateSelectorFor(true); - - CSSAgent.addRule.invoke({contextNodeId: this._node.id, selector: selector}, addedRule.bind(this)); - }, - - get matchedRules() - { - return this._matchedRules; - }, - - get inheritedRules() - { - return this._inheritedRules; - }, - - get inlineStyle() - { - return this._inlineStyle; - }, - - get attributesStyle() - { - return this._attributesStyle; - }, - - get pseudoElements() - { - return this._pseudoElements; - }, - - get computedStyle() - { - return this._computedStyle; - }, - - get orderedStyles() - { - return this._orderedStyles; - }, - - effectivePropertyForName: function(name) - { - var canonicalName = WebInspector.cssStyleManager.canonicalNameForPropertyName(name); - return this._propertyNameToEffectivePropertyMap[canonicalName] || null; - }, - - // Protected - - mediaQueryResultDidChange: function() - { - this._markAsNeedsRefresh(); - }, - - pseudoClassesDidChange: function(node) - { - this._includeUserAgentRulesOnNextRefresh = true; - this._markAsNeedsRefresh(); - }, - - attributeDidChange: function(node, attributeName) - { - // Ignore the attribute we know we just changed and handled above. - if (this._ignoreNextStyleAttributeDidChangeEvent && node === this._node && attributeName === "style") { - delete this._ignoreNextStyleAttributeDidChangeEvent; - return; - } - - this._markAsNeedsRefresh(); - }, - - changeRuleSelector: function(rule, selector) - { - selector = selector || ""; - - function ruleSelectorChanged(error, rulePayload) - { - DOMAgent.markUndoableState(); - - // Do a full refresh incase the rule no longer matches the node or the - // matched selector indices changed. - this.refresh(); - } - - this._needsRefresh = true; - this._ignoreNextContentDidChangeForStyleSheet = rule.ownerStyleSheet; - - CSSAgent.setRuleSelector(rule.id, selector, ruleSelectorChanged.bind(this)); - }, - - changeStyleText: function(style, text) - { - if (!style.ownerStyleSheet || !style.styleSheetTextRange) - return; - - text = text || ""; - - if (CSSAgent.setStyleText) { - function styleChanged(error, stylePayload) - { - if (error) - return; - this.refresh(); - } - - CSSAgent.setStyleText(style.id, text, styleChanged.bind(this)); - return; - } - - // COMPATIBILITY (iOS 6): CSSAgent.setStyleText was not available in iOS 6. - - // Setting the text on CSSStyleSheet for inline styles causes a crash. https://webkit.org/b/110359 - // So we just set the style attribute to get the same affect. This also avoids SourceCodeRevisions. - if (style.type === WebInspector.CSSStyleDeclaration.Type.Inline) { - text = text.trim(); - - function attributeChanged(error) - { - if (error) - return; - this.refresh(); - } - - this._ignoreNextStyleAttributeDidChangeEvent = true; - - if (text) - style.node.setAttributeValue("style", text, attributeChanged.bind(this)); - else - style.node.removeAttribute("style", attributeChanged.bind(this)); - - return; - } - - if (this._needsRefresh || this._refreshPending) { - // If we need refreshed then it is not safe to use the styleSheetTextRange since the range likely has - // changed and we need updated ranges. Store the text and remember the style so we can commit it after - // the next refresh. - - style.__pendingText = text; - - if (!this._stylesNeedingTextCommited.contains(style)) - this._stylesNeedingTextCommited.push(style); - - return; - } - - function fetchedStyleSheetContent(styleSheet, content) - { - console.assert(style.styleSheetTextRange); - if (!style.styleSheetTextRange) - return; - - var startOffset = style.styleSheetTextRange.startOffset; - var endOffset = style.styleSheetTextRange.endOffset; - - if (isNaN(startOffset) || isNaN(endOffset)) { - style.styleSheetTextRange.resolveOffsets(content); - - startOffset = style.styleSheetTextRange.startOffset; - endOffset = style.styleSheetTextRange.endOffset; - } - - console.assert(!isNaN(startOffset)); - console.assert(!isNaN(endOffset)); - if (isNaN(startOffset) || isNaN(endOffset)) - return; - - function contentDidChange() - { - style.ownerStyleSheet.removeEventListener(WebInspector.CSSStyleSheet.Event.ContentDidChange, contentDidChange, this); - - this.refresh(); - } - - style.ownerStyleSheet.addEventListener(WebInspector.CSSStyleSheet.Event.ContentDidChange, contentDidChange, this); - - var newContent = content.substring(0, startOffset) + text + content.substring(endOffset); - - WebInspector.branchManager.currentBranch.revisionForRepresentedObject(style.ownerStyleSheet).content = newContent; - } - - this._stylesNeedingTextCommited.remove(style); - delete style.__pendingText; - - this._needsRefresh = true; - this._ignoreNextContentDidChangeForStyleSheet = style.ownerStyleSheet; - - style.ownerStyleSheet.requestContent(fetchedStyleSheetContent.bind(this)); - }, - - changeProperty: function(property, name, value, priority) - { - var text = name ? name + ": " + value + (priority ? " !" + priority : "") + ";" : ""; - this.changePropertyText(property, text); - }, - - changePropertyText: function(property, text) - { - text = text || ""; - - var index = property.index; - var newProperty = isNaN(index); - var overwrite = true; - - // If this is a new property, then give it an index at the end of the current properties. - // Also don't overwrite, which will cause the property to be added at that index. - if (newProperty) { - index = property.ownerStyle.properties.length; - overwrite = false; - } - - if (text && text.charAt(text.length - 1) !== ";") - text += ";"; - - this._needsRefresh = true; - this._ignoreNextContentDidChangeForStyleSheet = property.ownerStyle.ownerStyleSheet; - - CSSAgent.setPropertyText(property.ownerStyle.id, index, text, overwrite, this._handlePropertyChange.bind(this, property)); - }, - - changePropertyEnabledState: function(property, enabled) - { - enabled = !!enabled; - - // Can't change a pending property with a NaN index. - if (isNaN(property.index)) - return; - - this._ignoreNextContentDidChangeForStyleSheet = property.ownerStyle.ownerStyleSheet; - - CSSAgent.toggleProperty(property.ownerStyle.id, property.index, !enabled, this._handlePropertyChange.bind(this, property)); - }, - - addProperty: function(property) - { - // Can't add a property unless it has a NaN index. - if (!isNaN(property.index)) - return; - - // Adding is done by setting the text. - this.changePropertyText(property, property.text); - }, - - removeProperty: function(property) - { - // Can't remove a pending property with a NaN index. - if (isNaN(property.index)) - return; - - // Removing is done by setting text to an empty string. - this.changePropertyText(property, ""); - }, - - // Private - - _handlePropertyChange: function(property, error, stylePayload) - { - if (error) - return; - - DOMAgent.markUndoableState(); - - // Do a refresh instead of handling stylePayload so computed style is updated and we get valid - // styleSheetTextRange values for all the rules after this change. - this.refresh(); - }, - - _createSourceCodeLocation: function(sourceURL, sourceLine, sourceColumn) - { - if (!sourceURL) - return null; - - var sourceCode; - - // Try to use the node to find the frame which has the correct resource first. - if (this._node.ownerDocument) { - var mainResource = WebInspector.frameResourceManager.resourceForURL(this._node.ownerDocument.documentURL); - if (mainResource) { - var parentFrame = mainResource.parentFrame; - sourceCode = parentFrame.resourceForURL(sourceURL); - } - } - - // If that didn't find the resource, then search all frames. - if (!sourceCode) - sourceCode = WebInspector.frameResourceManager.resourceForURL(sourceURL); - - if (!sourceCode) - return null; - - return sourceCode.createSourceCodeLocation(sourceLine || 0, sourceColumn || 0); - }, - - _parseSourceRangePayload: function(payload, text) - { - if (!payload) - return null; - - // COMPATIBILITY (iOS 6): The range use to only contain start and end offsets. Now it - // has line and column for the start and end position. Support both here. - if ("start" in payload && "end" in payload) { - var textRange = new WebInspector.TextRange(payload.start, payload.end); - if (typeof text === "string") - textRange.resolveLinesAndColumns(text); - return textRange; - } - - return new WebInspector.TextRange(payload.startLine, payload.startColumn, payload.endLine, payload.endColumn); - }, - - _parseStylePropertyPayload: function(payload, index, styleDeclaration, styleText) - { - var text = payload.text || ""; - var name = payload.name; - var value = (payload.value || "").replace(/\s*!important\s*$/, ""); - var priority = payload.priority || ""; - - var enabled = true; - var overridden = false; - var implicit = payload.implicit || false; - var anonymous = false; - var valid = "parsedOk" in payload ? payload.parsedOk : true; - - switch (payload.status || "style") { - case "active": - enabled = true; - break; - case "inactive": - overridden = true; - enabled = true; - break; - case "disabled": - enabled = false; - break; - case "style": - anonymous = true; - break; - } - - var styleSheetTextRange = null; - var styleDeclarationTextRange = null; - - // COMPATIBILITY (iOS 6): The range is in the style text, not the whole stylesheet. - // Later the range was changed to be in the whole stylesheet. - if (payload.range && "start" in payload.range && "end" in payload.range) - styleDeclarationTextRange = this._parseSourceRangePayload(payload.range, styleText); - else - styleSheetTextRange = this._parseSourceRangePayload(payload.range); - - if (styleDeclaration) { - // Use propertyForName when the index is NaN since propertyForName is fast in that case. - var property = isNaN(index) ? styleDeclaration.propertyForName(name, true) : styleDeclaration.properties[index]; - - // Reuse a property if the index and name matches. Otherwise it is a different property - // and should be created from scratch. This works in the simple cases where only existing - // properties change in place and no properties are inserted or deleted at the beginning. - // FIXME: This could be smarter by ignoring index and just go by name. However, that gets - // tricky for rules that have more than one property with the same name. - if (property && property.name === name && (property.index === index || (isNaN(property.index) && isNaN(index)))) { - property.update(text, name, value, priority, enabled, overridden, implicit, anonymous, valid, styleSheetTextRange, styleDeclarationTextRange); - return property; - } - - // Reuse a pending property with the same name. These properties are pending being committed, - // so if we find a match that likely means it got committed and we should use it. - var pendingProperties = styleDeclaration.pendingProperties; - for (var i = 0; i < pendingProperties.length; ++i) { - var pendingProperty = pendingProperties[i]; - if (pendingProperty.name === name && isNaN(pendingProperty.index)) { - pendingProperty.index = index; - pendingProperty.update(text, name, value, priority, enabled, overridden, implicit, anonymous, valid, styleSheetTextRange, styleDeclarationTextRange); - return pendingProperty; - } - } - } - - return new WebInspector.CSSProperty(index, text, name, value, priority, enabled, overridden, implicit, anonymous, valid, styleSheetTextRange, styleDeclarationTextRange); - }, - - _parseStyleDeclarationPayload: function(payload, node, inherited, type, rule, updateAllStyles) - { - if (!payload) - return null; - - rule = rule || null; - inherited = inherited || false; - - var id = payload.styleId; - var mapKey = id ? id.styleSheetId + ":" + id.ordinal : null; - - var styleDeclaration = rule ? rule.style : null; - var styleDeclarations = []; - - // Look for existing styles in the previous map if there is one, otherwise use the current map. - var previousStyleDeclarationsMap = this._previousStyleDeclarationsMap || this._styleDeclarationsMap; - if (mapKey && mapKey in previousStyleDeclarationsMap) { - styleDeclarations = previousStyleDeclarationsMap[mapKey]; - - // If we need to update all styles, then stop here and call _parseStyleDeclarationPayload for each style. - // We need to parse multiple times so we reuse the right properties from each style. - if (updateAllStyles && styleDeclarations.length) { - for (var i = 0; i < styleDeclarations.length; ++i) { - var styleDeclaration = styleDeclarations[i]; - this._parseStyleDeclarationPayload(payload, styleDeclaration.node, styleDeclaration.inherited, styleDeclaration.type, styleDeclaration.ownerRule); - } - - return; - } - - if (!styleDeclaration) { - var filteredStyleDeclarations = styleDeclarations.filter(function(styleDeclaration) { - // This case only applies for styles that are not part of a rule. - if (styleDeclaration.ownerRule) { - console.assert(!rule); - return false; - } - - if (styleDeclaration.node !== node) - return false; - - if (styleDeclaration.inherited !== inherited) - return false; - - return true; - }); - - console.assert(filteredStyleDeclarations.length <= 1); - styleDeclaration = filteredStyleDeclarations[0] || null; - } - } - - if (previousStyleDeclarationsMap !== this._styleDeclarationsMap) { - // If the previous and current maps differ then make sure the found styleDeclaration is added to the current map. - styleDeclarations = mapKey && mapKey in this._styleDeclarationsMap ? this._styleDeclarationsMap[mapKey] : [] ; - - if (styleDeclaration && !styleDeclarations.contains(styleDeclaration)) { - styleDeclarations.push(styleDeclaration); - this._styleDeclarationsMap[mapKey] = styleDeclarations; - } - } - - var shorthands = {}; - for (var i = 0; payload.shorthandEntries && i < payload.shorthandEntries.length; ++i) { - var shorthand = payload.shorthandEntries[i]; - shorthands[shorthand.name] = shorthand.value; - } - - var text = payload.cssText; - - var inheritedPropertyCount = 0; - - var properties = []; - for (var i = 0; payload.cssProperties && i < payload.cssProperties.length; ++i) { - var propertyPayload = payload.cssProperties[i]; - - if (inherited && propertyPayload.name in WebInspector.CSSKeywordCompletions.InheritedProperties) - ++inheritedPropertyCount; - - var property = this._parseStylePropertyPayload(propertyPayload, i, styleDeclaration, text); - properties.push(property); - } - - if (inherited && !inheritedPropertyCount) - return null; - - var styleSheetTextRange = this._parseSourceRangePayload(payload.range); - - if (styleDeclaration) { - styleDeclaration.update(text, properties, styleSheetTextRange); - return styleDeclaration; - } - - var styleSheet = id ? WebInspector.cssStyleManager.styleSheetForIdentifier(id.styleSheetId) : null; - if (styleSheet) - styleSheet.addEventListener(WebInspector.CSSStyleSheet.Event.ContentDidChange, this._styleSheetContentDidChange, this); - - styleDeclaration = new WebInspector.CSSStyleDeclaration(this, styleSheet, id, type, node, inherited, text, properties, styleSheetTextRange); - - if (mapKey) { - styleDeclarations.push(styleDeclaration); - this._styleDeclarationsMap[mapKey] = styleDeclarations; - } - - return styleDeclaration; - }, - - _parseRulePayload: function(payload, matchedSelectorIndices, node, inherited, ruleOccurrences) - { - if (!payload) - return null; - - // User and User Agent rules don't have 'ruleId' in the payload. However, their style's have 'styleId' and - // 'styleId' is the same identifier the backend uses for Author rule identifiers, so do the same here. - // They are excluded by the backend because they are not editable, however our front-end does not determine - // editability solely based on the existence of the id like the open source front-end does. - var id = payload.ruleId || payload.style.styleId; - - var mapKey = id ? id.styleSheetId + ":" + id.ordinal + ":" + (inherited ? "I" : "N") + ":" + node.id : null; - - // Rules can match multiple times if they have multiple selectors or because of inheritance. We keep a count - // of occurrences so we have unique rules per occurrence, that way properties will be correctly marked as overridden. - var occurrence = 0; - if (mapKey) { - if (mapKey in ruleOccurrences) - occurrence = ++ruleOccurrences[mapKey]; - else - ruleOccurrences[mapKey] = occurrence; - } - - // Append the occurrence number to the map key for lookup in the rules map. - mapKey += ":" + occurrence; - - var rule = null; - - // Look for existing rules in the previous map if there is one, otherwise use the current map. - var previousRulesMap = this._previousRulesMap || this._rulesMap; - if (mapKey && mapKey in previousRulesMap) { - rule = previousRulesMap[mapKey]; - - if (previousRulesMap !== this._rulesMap) { - // If the previous and current maps differ then make sure the found rule is added to the current map. - this._rulesMap[mapKey] = rule; - } - } - - var style = this._parseStyleDeclarationPayload(payload.style, node, inherited, WebInspector.CSSStyleDeclaration.Type.Rule, rule); - if (!style) - return null; - - // COMPATIBILITY (iOS 6): The payload had 'selectorText' as a property, - // now it has 'selectorList' with a 'text' property. Support both here. - var selectorText = payload.selectorList ? payload.selectorList.text : payload.selectorText; - var selectors = payload.selectorList ? payload.selectorList.selectors : []; - - // COMPATIBILITY (iOS 6): The payload did not have 'selectorList'. - // Fallback to using 'sourceLine' without column information. - if (payload.selectorList && payload.selectorList.range) { - var sourceRange = payload.selectorList.range; - var sourceCodeLocation = this._createSourceCodeLocation(payload.sourceURL, sourceRange.startLine, sourceRange.startColumn); - } else - var sourceCodeLocation = this._createSourceCodeLocation(payload.sourceURL, payload.sourceLine); - - var type; - switch (payload.origin) { - case "regular": - type = WebInspector.CSSRule.Type.Author; - break; - case "user": - type = WebInspector.CSSRule.Type.User; - break; - case "user-agent": - type = WebInspector.CSSRule.Type.UserAgent; - break; - case "inspector": - type = WebInspector.CSSRule.Type.Inspector; - break; - } - - var mediaList = []; - for (var i = 0; payload.media && i < payload.media.length; ++i) { - var mediaItem = payload.media[i]; - - var mediaType; - switch (mediaItem.source) { - case "mediaRule": - mediaType = WebInspector.CSSMedia.Type.MediaRule; - break; - case "importRule": - mediaType = WebInspector.CSSMedia.Type.ImportRule; - break; - case "linkedSheet": - mediaType = WebInspector.CSSMedia.Type.LinkedStyleSheet; - break; - case "inlineSheet": - mediaType = WebInspector.CSSMedia.Type.InlineStyleSheet; - break; - } - - var mediaText = mediaItem.text; - var mediaSourceCodeLocation = this._createSourceCodeLocation(mediaItem.sourceURL, mediaItem.sourceLine); - - mediaList.push(new WebInspector.CSSMedia(mediaType, mediaText, mediaSourceCodeLocation)); - } - - if (rule) { - rule.update(sourceCodeLocation, selectorText, selectors, matchedSelectorIndices, style, mediaList); - return rule; - } - - var styleSheet = id ? WebInspector.cssStyleManager.styleSheetForIdentifier(id.styleSheetId) : null; - if (styleSheet) - styleSheet.addEventListener(WebInspector.CSSStyleSheet.Event.ContentDidChange, this._styleSheetContentDidChange, this); - - rule = new WebInspector.CSSRule(this, styleSheet, id, type, sourceCodeLocation, selectorText, selectors, matchedSelectorIndices, style, mediaList); - - if (mapKey) - this._rulesMap[mapKey] = rule; - - return rule; - }, - - _markAsNeedsRefresh: function() - { - this._needsRefresh = true; - this.dispatchEventToListeners(WebInspector.DOMNodeStyles.Event.NeedsRefresh); - }, - - _styleSheetContentDidChange: function(event) - { - var styleSheet = event.target; - console.assert(styleSheet); - if (!styleSheet) - return; - - // Ignore the stylesheet we know we just changed and handled above. - if (styleSheet === this._ignoreNextContentDidChangeForStyleSheet) { - delete this._ignoreNextContentDidChangeForStyleSheet; - return; - } - - this._markAsNeedsRefresh(); - }, - - _updateStyleCascade: function() - { - var cascadeOrderedStyleDeclarations = this._collectStylesInCascadeOrder(this._matchedRules, this._inlineStyle, this._attributesStyle); - - for (var i = 0; i < this._inheritedRules.length; ++i) { - var inheritedStyleInfo = this._inheritedRules[i]; - var inheritedCascadeOrder = this._collectStylesInCascadeOrder(inheritedStyleInfo.matchedRules, inheritedStyleInfo.inlineStyle, null); - cascadeOrderedStyleDeclarations = cascadeOrderedStyleDeclarations.concat(inheritedCascadeOrder); - } - - this._orderedStyles = cascadeOrderedStyleDeclarations; - - this._propertyNameToEffectivePropertyMap = {}; - - this._markOverriddenProperties(cascadeOrderedStyleDeclarations, this._propertyNameToEffectivePropertyMap); - this._associateRelatedProperties(cascadeOrderedStyleDeclarations, this._propertyNameToEffectivePropertyMap); - - for (var pseudoIdentifier in this._pseudoElements) { - var pseudoElementInfo = this._pseudoElements[pseudoIdentifier]; - pseudoElementInfo.orderedStyles = this._collectStylesInCascadeOrder(pseudoElementInfo.matchedRules, null, null); - this._markOverriddenProperties(pseudoElementInfo.orderedStyles); - this._associateRelatedProperties(pseudoElementInfo.orderedStyles); - } - }, - - _collectStylesInCascadeOrder: function(matchedRules, inlineStyle, attributesStyle) - { - var result = []; - - // Inline style has the greatest specificity. So it goes first in the cascade order. - if (inlineStyle) - result.push(inlineStyle); - - var userAndUserAgentStyles = []; - - for (var i = 0; i < matchedRules.length; ++i) { - var rule = matchedRules[i]; - - // Only append to the result array here for author and inspector rules since attribute - // styles come between author rules and user/user agent rules. - switch (rule.type) { - case WebInspector.CSSRule.Type.Inspector: - case WebInspector.CSSRule.Type.Author: - result.push(rule.style); - break; - - case WebInspector.CSSRule.Type.User: - case WebInspector.CSSRule.Type.UserAgent: - userAndUserAgentStyles.push(rule.style); - break; - } - } - - // Style properties from HTML attributes are next. - if (attributesStyle) - result.push(attributesStyle); - - // Finally add the user and user stylesheet's matched style rules we collected earlier. - result = result.concat(userAndUserAgentStyles); - - return result; - }, - - _markOverriddenProperties: function(styles, propertyNameToEffectiveProperty) - { - propertyNameToEffectiveProperty = propertyNameToEffectiveProperty || {}; - - for (var i = 0; i < styles.length; ++i) { - var style = styles[i]; - var properties = style.properties; - - for (var j = 0; j < properties.length; ++j) { - var property = properties[j]; - if (!property.enabled || property.anonymous || !property.valid) { - property.overridden = false; - continue; - } - - if (style.inherited && !property.inherited) { - property.overridden = false; - continue; - } - - var canonicalName = property.canonicalName; - if (canonicalName in propertyNameToEffectiveProperty) { - var effectiveProperty = propertyNameToEffectiveProperty[canonicalName]; - - if (effectiveProperty.ownerStyle === property.ownerStyle) { - if (effectiveProperty.important && !property.important) { - property.overridden = true; - continue; - } - } else if (effectiveProperty.important || !property.important || effectiveProperty.ownerStyle.node !== property.ownerStyle.node) { - property.overridden = true; - continue; - } - - effectiveProperty.overridden = true; - } - - property.overridden = false; - - propertyNameToEffectiveProperty[canonicalName] = property; - } - } - }, - - _associateRelatedProperties: function(styles, propertyNameToEffectiveProperty) - { - for (var i = 0; i < styles.length; ++i) { - var properties = styles[i].properties; - - var knownShorthands = {}; - - for (var j = 0; j < properties.length; ++j) { - var property = properties[j]; - - if (!property.valid) - continue; - - if (!WebInspector.CSSCompletions.cssNameCompletions.isShorthandPropertyName(property.name)) - continue; - - if (knownShorthands[property.canonicalName] && !knownShorthands[property.canonicalName].overridden) { - console.assert(property.overridden); - continue; - } - - knownShorthands[property.canonicalName] = property; - } - - for (var j = 0; j < properties.length; ++j) { - var property = properties[j]; - - if (!property.valid) - continue; - - var shorthandProperty = null; - - if (!isEmptyObject(knownShorthands)) { - var possibleShorthands = WebInspector.CSSCompletions.cssNameCompletions.shorthandsForLonghand(property.canonicalName); - for (var k = 0; k < possibleShorthands.length; ++k) { - if (possibleShorthands[k] in knownShorthands) { - shorthandProperty = knownShorthands[possibleShorthands[k]]; - break; - } - } - } - - if (!shorthandProperty || shorthandProperty.overridden !== property.overridden) { - property.relatedShorthandProperty = null; - property.clearRelatedLonghandProperties(); - continue; - } - - shorthandProperty.addRelatedLonghandProperty(property); - property.relatedShorthandProperty = shorthandProperty; - - if (propertyNameToEffectiveProperty && propertyNameToEffectiveProperty[shorthandProperty.canonicalName] === shorthandProperty) - propertyNameToEffectiveProperty[property.canonicalName] = property; - } - } - } -}; - -WebInspector.DOMNodeStyles.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/DOMObserver.js b/Source/WebInspectorUI/UserInterface/DOMObserver.js deleted file mode 100644 index 9b9e8e8d6..000000000 --- a/Source/WebInspectorUI/UserInterface/DOMObserver.js +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.DOMObserver = function() -{ - WebInspector.Object.call(this); -}; - -WebInspector.DOMObserver.prototype = { - constructor: WebInspector.DOMObserver, - - // Events defined by the "DOM" domain. - - documentUpdated: function() - { - WebInspector.domTreeManager._documentUpdated(); - }, - - setChildNodes: function(parentId, payloads) - { - WebInspector.domTreeManager._setChildNodes(parentId, payloads); - }, - - attributeModified: function(nodeId, name, value) - { - WebInspector.domTreeManager._attributeModified(nodeId, name, value); - }, - - attributeRemoved: function(nodeId, name) - { - WebInspector.domTreeManager._attributeRemoved(nodeId, name); - }, - - inlineStyleInvalidated: function(nodeIds) - { - WebInspector.domTreeManager._inlineStyleInvalidated(nodeIds); - }, - - characterDataModified: function(nodeId, characterData) - { - WebInspector.domTreeManager._characterDataModified(nodeId, characterData); - }, - - childNodeCountUpdated: function(nodeId, childNodeCount) - { - WebInspector.domTreeManager._childNodeCountUpdated(nodeId, childNodeCount); - }, - - childNodeInserted: function(parentNodeId, previousNodeId, payload) - { - WebInspector.domTreeManager._childNodeInserted(parentNodeId, previousNodeId, payload); - }, - - childNodeRemoved: function(parentNodeId, nodeId) - { - WebInspector.domTreeManager._childNodeRemoved(parentNodeId, nodeId); - }, - - shadowRootPushed: function(parentNodeId, nodeId) - { - WebInspector.domTreeManager._childNodeInserted(parentNodeId, 0, nodeId); - }, - - shadowRootPopped: function(parentNodeId, nodeId) - { - WebInspector.domTreeManager._childNodeRemoved(parentNodeId, nodeId); - } -}; - -WebInspector.DOMObserver.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/DOMSearchMatchObject.js b/Source/WebInspectorUI/UserInterface/DOMSearchMatchObject.js deleted file mode 100644 index 6ba045727..000000000 --- a/Source/WebInspectorUI/UserInterface/DOMSearchMatchObject.js +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.DOMSearchMatchObject = function(resource, domNode, title, searchTerm, textRange) -{ - console.assert(resource instanceof WebInspector.Resource); - console.assert(domNode instanceof WebInspector.DOMNode); - - WebInspector.Object.call(this); - - this._resource = resource; - this._domNode = domNode; - this._title = title; - this._searchTerm = searchTerm; - this._sourceCodeTextRange = resource.createSourceCodeTextRange(textRange); -}; - -WebInspector.DOMSearchMatchObject.DOMMatchElementIconStyleClassName = "dom-match-element-icon"; -WebInspector.DOMSearchMatchObject.DOMMatchTextNodeIconStyleClassName = "dom-match-text-node-icon"; -WebInspector.DOMSearchMatchObject.DOMMatchCommentIconStyleClassName = "dom-match-comment-icon"; -WebInspector.DOMSearchMatchObject.DOMMatchDocumentTypeIconStyleClassName = "dom-match-document-type-icon"; -WebInspector.DOMSearchMatchObject.DOMMatchCharacterDataIconStyleClassName = "dom-match-character-data-icon"; -WebInspector.DOMSearchMatchObject.DOMMatchNodeIconStyleClassName = "dom-match-node-icon"; - -WebInspector.DOMSearchMatchObject.prototype = { - constructor: WebInspector.DOMSearchMatchObject, - - // Public - - get domNode() - { - return this._domNode; - }, - - get title() - { - return this._title; - }, - - get className() - { - if (!this._className) - this._className = this._generateClassName(); - - return this._className; - }, - - get searchTerm() - { - return this._searchTerm; - }, - - get sourceCodeTextRange() - { - return this._sourceCodeTextRange; - }, - - // Private - - _generateClassName: function() - { - switch (this._domNode.nodeType()) { - case Node.ELEMENT_NODE: - return WebInspector.DOMSearchMatchObject.DOMMatchElementIconStyleClassName; - - case Node.TEXT_NODE: - return WebInspector.DOMSearchMatchObject.DOMMatchTextNodeIconStyleClassName; - - case Node.COMMENT_NODE: - return WebInspector.DOMSearchMatchObject.DOMMatchCommentIconStyleClassName; - - case Node.DOCUMENT_TYPE_NODE: - return WebInspector.DOMSearchMatchObject.DOMMatchDocumentTypeIconStyleClassName; - - case Node.CDATA_SECTION_NODE: - return WebInspector.DOMSearchMatchObject.DOMMatchCharacterDataIconStyleClassName; - - default: - console.error("Unknown DOM node type: ", node.nodeType()); - return WebInspector.DOMSearchMatchObject.DOMMatchNodeIconStyleClassName; - } - } -}; - -WebInspector.DOMSearchMatchObject.titleForDOMNode = function(domNode) -{ - switch (domNode.nodeType()) { - case Node.ELEMENT_NODE: - var title = "<" + domNode.nodeNameInCorrectCase(); - - for (var i = 0; i < domNode.attributes().length; ++i) { - title += " " + domNode.attributes()[i].name; - if (domNode.attributes()[i].value.length) - title += "=\"" + domNode.attributes()[i].value + "\""; - } - - return title + ">"; - - case Node.TEXT_NODE: - return "\"" + domNode.nodeValue() + "\""; - - case Node.COMMENT_NODE: - return ""; - - case Node.DOCUMENT_TYPE_NODE: - var title = ""; - - case Node.CDATA_SECTION_NODE: - return "" + domNode + ""; - - default: - console.error("Unknown DOM node type: ", domNode.nodeType()); - return domNode.nodeNameInCorrectCase(); - } -} - -WebInspector.DOMSearchMatchObject.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/DOMStorageContentView.css b/Source/WebInspectorUI/UserInterface/DOMStorageContentView.css deleted file mode 100644 index 234dec65d..000000000 --- a/Source/WebInspectorUI/UserInterface/DOMStorageContentView.css +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.content-view.dom-storage > .data-grid { - position: absolute; - top: 0; - left: 0; - right: 0; - bottom: 0; - outline: none; - border: none; -} diff --git a/Source/WebInspectorUI/UserInterface/DOMStorageContentView.js b/Source/WebInspectorUI/UserInterface/DOMStorageContentView.js deleted file mode 100644 index 31ba7fa5b..000000000 --- a/Source/WebInspectorUI/UserInterface/DOMStorageContentView.js +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * Copyright (C) 2013 Samsung Electronics. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.DOMStorageContentView = function(representedObject) -{ - WebInspector.ContentView.call(this, representedObject); - - this.element.classList.add(WebInspector.DOMStorageContentView.StyleClassName); - - this.update(); -}; - -WebInspector.DOMStorageContentView.StyleClassName = "dom-storage"; - -WebInspector.DOMStorageContentView.prototype = { - constructor: WebInspector.DOMStorageContentView, - - // Public - - update: function() - { - this.representedObject.getEntries(this._showDOMStorageEntries.bind(this)); - }, - - saveToCookie: function(cookie) - { - cookie.type = WebInspector.ContentViewCookieType.DOMStorage; - cookie.isLocalStorage = this.representedObject.isLocalStorage(); - cookie.host = this.representedObject.host; - }, - - itemsCleared: function() - { - this._dataGrid.removeChildren(); - this._dataGrid.addCreationNode(false); - }, - - itemRemoved: function(key) - { - for (var i = 0; i < this._dataGrid.children.length; ++i) { - var childNode = this._dataGrid.children[i]; - if (childNode.data[0] === key) { - this._dataGrid.removeChild(childNode); - return; - } - } - }, - - itemAdded: function(key, value) - { - for (var i = 0; i < this._dataGrid.children.length; ++i) { - if (this._dataGrid.children[i][0] === key) - return; - } - - var data = {}; - data[0] = key; - data[1] = value; - - var childNode = new WebInspector.DataGridNode(data, false); - - this._dataGrid.insertChild(childNode, this._dataGrid.children.length - 1); - if (this._dataGrid.sortOrder) - this._sortDataGrid(); - }, - - itemUpdated: function(key, oldValue, value) - { - var keyFound = false; - for (var i = 0; i < this._dataGrid.children.length; ++i) { - var childNode = this._dataGrid.children[i]; - if (childNode.data[0] === key) { - if (keyFound) { - this._dataGrid.removeChild(childNode); - return; - } - - keyFound = true; - childNode.data[1] = value; - childNode.refresh(); - } - } - }, - - updateLayout: function() - { - if (this._dataGrid) - this._dataGrid.updateLayout(); - }, - - get scrollableElements() - { - if (!this._dataGrid) - return []; - return [this._dataGrid.scrollContainer]; - }, - - // Private - - _showDOMStorageEntries: function(error, entries) - { - if (error) - return; - - this._updateDataGridForDOMStorageEntries(entries); - - this._dataGrid.updateLayout(); - }, - - _updateDataGridForDOMStorageEntries: function(entries) - { - if (!this._dataGrid) { - var columns = {}; - columns[0] = {title: WebInspector.UIString("Key"), sortable: true}; - columns[1] = {title: WebInspector.UIString("Value"), sortable: true}; - - this._dataGrid = new WebInspector.DataGrid(columns, this._editingCallback.bind(this), this._deleteCallback.bind(this)); - this._dataGrid.addEventListener(WebInspector.DataGrid.Event.SortChanged, this._sortDataGrid, this); - - this.element.appendChild(this._dataGrid.element); - } - - console.assert(this._dataGrid); - - var nodes = []; - for (var i = 0; i < entries.length; ++i) { - var data = {}; - - var key = entries[i][0]; - var value = entries[i][1]; - - data[0] = key; - data[1] = value; - - var node = new WebInspector.DataGridNode(data, false); - node.selectable = true; - - nodes.push(node); - } - - if (this._dataGrid.creationNode) - this._dataGrid.removeChild(this._dataGrid.creationNode); - - this._insertNodesIntoDataGridWithSort(nodes); - - if (nodes.length > 0) - nodes[0].selected = true; - }, - - _sortDataGrid: function() - { - if (this._dataGrid.creationNode) - this._dataGrid.removeChild(this._dataGrid.creationNode); - - var nodes = this._dataGrid.children.slice(); - this._insertNodesIntoDataGridWithSort(nodes); - }, - - _insertNodesIntoDataGridWithSort: function(nodes) - { - console.assert(!this._dataGrid.creationNode); - - var sortColumnIdentifier = this._dataGrid.sortColumnIdentifier; - var sortAscending = this._dataGrid.sortOrder === "ascending"; - - function comparator(a, b) - { - var result = b.data[sortColumnIdentifier].localeCompare(a.data[sortColumnIdentifier]); - return sortAscending ? -result : result; - } - - if (sortColumnIdentifier) - nodes.sort(comparator); - - this._dataGrid.removeChildren(); - for (var i = 0; i < nodes.length; i++) - this._dataGrid.appendChild(nodes[i]); - this._dataGrid.addCreationNode(false); - }, - - _deleteCallback: function(node) - { - if (!node || node.isCreationNode) - return; - - if (this.representedObject) - this.representedObject.removeItem(node.data[0]); - - this.update(); - }, - - _editingCallback: function(editingNode, columnIdentifier, oldText, newText) - { - var domStorage = this.representedObject; - if (columnIdentifier === "0") { - if (oldText) - domStorage.removeItem(oldText); - - domStorage.setItem(newText, editingNode.data[1]); - } else - domStorage.setItem(editingNode.data[0], newText); - - this.update(); - } -}; - -WebInspector.DOMStorageContentView.prototype.__proto__ = WebInspector.ContentView.prototype; diff --git a/Source/WebInspectorUI/UserInterface/DOMStorageIcons.css b/Source/WebInspectorUI/UserInterface/DOMStorageIcons.css deleted file mode 100644 index 08d16070c..000000000 --- a/Source/WebInspectorUI/UserInterface/DOMStorageIcons.css +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.local-storage-icon .icon { - content: -webkit-image-set(url(Images/LocalStorage.png) 1x, url(Images/LocalStorage@2x.png) 2x); -} - -.session-storage-icon .icon { - content: -webkit-image-set(url(Images/SessionStorage.png) 1x, url(Images/SessionStorage@2x.png) 2x); -} diff --git a/Source/WebInspectorUI/UserInterface/DOMStorageObject.js b/Source/WebInspectorUI/UserInterface/DOMStorageObject.js deleted file mode 100644 index d6fd1e046..000000000 --- a/Source/WebInspectorUI/UserInterface/DOMStorageObject.js +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.DOMStorageObject = function(id, host, isLocalStorage) -{ - this._id = id; - this._host = host; - this._isLocalStorage = isLocalStorage; -}; - -WebInspector.DOMStorageObject.TypeIdentifier = "dom-storage"; -WebInspector.DOMStorageObject.HostCookieKey = "dom-storage-object-host"; -WebInspector.DOMStorageObject.LocalStorageCookieKey = "dom-storage-object-local-storage"; - -WebInspector.DOMStorageObject.prototype = { - constructor: WebInspector.DOMStorageObject, - - get id() - { - return this._id; - }, - - get host() - { - return this._host; - }, - - saveIdentityToCookie: function(cookie) - { - cookie[WebInspector.DOMStorageObject.HostCookieKey] = this.host; - cookie[WebInspector.DOMStorageObject.LocalStorageCookieKey] = this.isLocalStorage(); - }, - - isLocalStorage: function() - { - return this._isLocalStorage; - }, - - getEntries: function(callback) - { - // COMPATIBILITY (iOS 6): The getDOMStorageItems function was later renamed to getDOMStorageItems. - if (DOMStorageAgent.getDOMStorageEntries) - DOMStorageAgent.getDOMStorageEntries(this._id, callback); - else - DOMStorageAgent.getDOMStorageItems(this._id, callback); - }, - - removeItem: function(key, callback) - { - DOMStorageAgent.removeDOMStorageItem(this._id, key, callback); - }, - - setItem: function(key, value, callback) - { - DOMStorageAgent.setDOMStorageItem(this._id, key, value, callback); - } -}; diff --git a/Source/WebInspectorUI/UserInterface/DOMStorageObserver.js b/Source/WebInspectorUI/UserInterface/DOMStorageObserver.js deleted file mode 100644 index 9b1b15d3a..000000000 --- a/Source/WebInspectorUI/UserInterface/DOMStorageObserver.js +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * Copyright (C) 2013 Samsung Electronics. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.DOMStorageObserver = function() -{ - WebInspector.Object.call(this); -}; - -WebInspector.DOMStorageObserver.prototype = { - constructor: WebInspector.DOMStorageObserver, - - // Events defined by the "DOMStorage" domain. - - // COMPATIBILITY (iOS 6): This event no longer exists. It is still needed and called on iOS 6. - addDOMStorage: function(storage) - { - WebInspector.storageManager.domStorageWasAdded(storage.id, storage.host, storage.isLocalStorage); - }, - - // COMPATIBILITY (iOS 6): This event was split into the granular events below. - updateDOMStorage: function(storageId) - { - WebInspector.storageManager.domStorageWasUpdated(storageId); - }, - - domStorageItemsCleared: function(storageId) - { - WebInspector.storageManager.domStorageItemsCleared(storageId); - }, - - domStorageItemRemoved: function(storageId, key) - { - WebInspector.storageManager.domStorageItemRemoved(storageId, key); - }, - - domStorageItemAdded: function(storageId, key, value) - { - WebInspector.storageManager.domStorageItemAdded(storageId, key, value); - }, - - domStorageItemUpdated: function(storageId, key, oldValue, value) - { - WebInspector.storageManager.domStorageItemUpdated(storageId, key, oldValue, value); - } -}; - -WebInspector.DOMStorageObserver.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/DOMStorageTreeElement.js b/Source/WebInspectorUI/UserInterface/DOMStorageTreeElement.js deleted file mode 100644 index 3b3e60c79..000000000 --- a/Source/WebInspectorUI/UserInterface/DOMStorageTreeElement.js +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.DOMStorageTreeElement = function(representedObject) -{ - console.assert(representedObject instanceof WebInspector.DOMStorageObject); - - if (representedObject.isLocalStorage()) - var className = WebInspector.DOMStorageTreeElement.LocalStorageIconStyleClassName; - else - var className = WebInspector.DOMStorageTreeElement.SessionStorageIconStyleClassName; - - WebInspector.StorageTreeElement.call(this, className, WebInspector.displayNameForHost(representedObject.host), representedObject); -}; - -WebInspector.DOMStorageTreeElement.LocalStorageIconStyleClassName = "local-storage-icon"; -WebInspector.DOMStorageTreeElement.SessionStorageIconStyleClassName = "session-storage-icon"; - -WebInspector.DOMStorageTreeElement.prototype = { - constructor: WebInspector.DOMStorageTreeElement, - - // Public - - get name() - { - return WebInspector.displayNameForHost(this.representedObject.host); - }, - - get categoryName() - { - if (this.representedObject.isLocalStorage()) - return WebInspector.UIString("Local Storage"); - return WebInspector.UIString("Session Storage"); - } -}; - -WebInspector.DOMStorageTreeElement.prototype.__proto__ = WebInspector.StorageTreeElement.prototype; diff --git a/Source/WebInspectorUI/UserInterface/DOMTree.js b/Source/WebInspectorUI/UserInterface/DOMTree.js deleted file mode 100644 index 9e2a6d5d4..000000000 --- a/Source/WebInspectorUI/UserInterface/DOMTree.js +++ /dev/null @@ -1,334 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.DOMTree = function(frame) -{ - WebInspector.Object.call(this); - - this._frame = frame; - - this._rootDOMNode = null; - this._requestIdentifier = 0; - this._flowMap = {}; - - this._frame.addEventListener(WebInspector.Frame.Event.PageExecutionContextChanged, this._framePageExecutionContextChanged, this); - - WebInspector.domTreeManager.addEventListener(WebInspector.DOMTreeManager.Event.DocumentUpdated, this._documentUpdated, this); - - // Only add extra event listeners when not the main frame. Since DocumentUpdated is enough for the main frame. - if (!this._frame.isMainFrame()) { - WebInspector.domTreeManager.addEventListener(WebInspector.DOMTreeManager.Event.NodeRemoved, this._nodeRemoved, this); - this._frame.addEventListener(WebInspector.Frame.Event.MainResourceDidChange, this._frameMainResourceDidChange, this); - } - - WebInspector.domTreeManager.addEventListener(WebInspector.DOMTreeManager.Event.ContentFlowListWasUpdated, this._contentFlowListWasUpdated, this); - WebInspector.domTreeManager.addEventListener(WebInspector.DOMTreeManager.Event.ContentFlowWasAdded, this._contentFlowWasAdded, this); - WebInspector.domTreeManager.addEventListener(WebInspector.DOMTreeManager.Event.ContentFlowWasRemoved, this._contentFlowWasRemoved, this); -}; - -WebInspector.Object.addConstructorFunctions(WebInspector.DOMTree); - -WebInspector.DOMTree.Event = { - RootDOMNodeInvalidated: "dom-tree-root-dom-node-invalidated", - ContentFlowWasAdded: "dom-tree-content-flow-was-added", - ContentFlowWasRemoved: "dom-tree-content-flow-was-removed" -}; - -WebInspector.DOMTree.prototype = { - constructor: WebInspector.DOMTree, - - // Public - - get frame() - { - return this._frame; - }, - - get flowMap() - { - return this._flowMap; - }, - - get flowsCount() - { - return Object.keys(this._flowMap).length; - }, - - invalidate: function() - { - // Set to null so it is fetched again next time requestRootDOMNode is called. - this._rootDOMNode = null; - - // Clear the pending callbacks. It is the responsibility of the client to listen for - // the RootDOMNodeInvalidated event and request the root DOM node again. - delete this._pendingRootDOMNodeRequests; - - if (this._invalidateTimeoutIdentifier) - return; - - function performInvalidate() - { - delete this._invalidateTimeoutIdentifier; - - this.dispatchEventToListeners(WebInspector.DOMTree.Event.RootDOMNodeInvalidated); - } - - // Delay the invalidation on a timeout to coalesce multiple calls to invalidate. - this._invalidateTimeoutIdentifier = setTimeout(performInvalidate.bind(this), 0); - }, - - requestRootDOMNode: function(callback) - { - console.assert(typeof callback === "function"); - if (typeof callback !== "function") - return; - - if (this._rootDOMNode) { - callback(this._rootDOMNode); - return; - } - - if (!this._frame.isMainFrame() && WebInspector.ExecutionContext.supported() && !this._frame.pageExecutionContext) { - this._rootDOMNodeRequestWaitingForExecutionContext = true; - if (!this._pendingRootDOMNodeRequests) - this._pendingRootDOMNodeRequests = []; - this._pendingRootDOMNodeRequests.push(callback); - return; - } - - if (this._pendingRootDOMNodeRequests) { - this._pendingRootDOMNodeRequests.push(callback); - return; - } - - this._pendingRootDOMNodeRequests = [callback]; - this._requestRootDOMNode(); - }, - - // Private - - _requestRootDOMNode: function() - { - console.assert(this._frame.isMainFrame() || !WebInspector.ExecutionContext.supported() || this._frame.pageExecutionContext); - console.assert(this._pendingRootDOMNodeRequests.length); - - // Bump the request identifier. This prevents pending callbacks for previous requests from completing. - var requestIdentifier = ++this._requestIdentifier; - - function rootObjectAvailable(error, result) - { - // Check to see if we have been invalidated (if the callbacks were cleared). - if (!this._pendingRootDOMNodeRequests || requestIdentifier != this._requestIdentifier) - return; - - if (error) { - console.error(JSON.stringify(error)); - - this._rootDOMNode = null; - dispatchCallbacks.call(this); - return; - } - - // Convert the RemoteObject to a DOMNode by asking the backend to push it to us. - var remoteObject = WebInspector.RemoteObject.fromPayload(result); - remoteObject.pushNodeToFrontend(rootDOMNodeAvailable.bind(this, remoteObject)); - } - - function rootDOMNodeAvailable(remoteObject, nodeId) - { - remoteObject.release(); - - // Check to see if we have been invalidated (if the callbacks were cleared). - if (!this._pendingRootDOMNodeRequests || requestIdentifier != this._requestIdentifier) - return; - - if (!nodeId) { - this._rootDOMNode = null; - dispatchCallbacks.call(this); - return; - } - - this._rootDOMNode = WebInspector.domTreeManager.nodeForId(nodeId); - - console.assert(this._rootDOMNode); - if (!this._rootDOMNode) { - dispatchCallbacks.call(this); - return; - } - - // Request the child nodes since the root node is often not shown in the UI, - // and the child nodes will be needed immediately. - this._rootDOMNode.getChildNodes(dispatchCallbacks.bind(this)); - } - - function mainDocumentAvailable(document) - { - this._rootDOMNode = document; - - dispatchCallbacks.call(this); - } - - function dispatchCallbacks() - { - // Check to see if we have been invalidated (if the callbacks were cleared). - if (!this._pendingRootDOMNodeRequests || requestIdentifier != this._requestIdentifier) - return; - - for (var i = 0; i < this._pendingRootDOMNodeRequests.length; ++i) - this._pendingRootDOMNodeRequests[i](this._rootDOMNode); - delete this._pendingRootDOMNodeRequests; - } - - // For the main frame we can use the more straight forward requestDocument function. For - // child frames we need to do a more roundabout approach since the protocol does not include - // a specific way to request a document given a frame identifier. The child frame approach - // involves evaluating the JavaScript "document" and resolving that into a DOMNode. - if (this._frame.isMainFrame()) - WebInspector.domTreeManager.requestDocument(mainDocumentAvailable.bind(this)); - else { - // COMPATIBILITY (iOS 6): Execution context identifiers (contextId) did not exist - // in iOS 6. Fallback to including the frame identifier (frameId). - var contextId = this._frame.pageExecutionContext ? this._frame.pageExecutionContext.id : undefined; - RuntimeAgent.evaluate.invoke({expression: "document", objectGroup: "", includeCommandLineAPI: false, doNotPauseOnExceptionsAndMuteConsole: true, contextId: contextId, frameId: this._frame.id, returnByValue: false, generatePreview: false}, rootObjectAvailable.bind(this)); - } - }, - - _nodeRemoved: function(event) - { - console.assert(!this._frame.isMainFrame()); - - if (event.data.node !== this._rootDOMNode) - return; - - this.invalidate(); - }, - - _documentUpdated: function(event) - { - this.invalidate(); - }, - - _frameMainResourceDidChange: function(event) - { - console.assert(!this._frame.isMainFrame()); - - this.invalidate(); - }, - - _framePageExecutionContextChanged: function(event) - { - if (this._rootDOMNodeRequestWaitingForExecutionContext) { - console.assert(this._frame.pageExecutionContext); - console.assert(this._pendingRootDOMNodeRequests && this._pendingRootDOMNodeRequests.length); - - delete this._rootDOMNodeRequestWaitingForExecutionContext; - - this._requestRootDOMNode(); - } - }, - - requestContentFlowList: function() - { - this.requestRootDOMNode(function(rootNode) { - // Let the backend know we are interested about the named flow events for this document. - WebInspector.domTreeManager.getNamedFlowCollection(rootNode.id); - }); - }, - - _isContentFlowInCurrentDocument: function(flow) - { - return this._rootDOMNode && this._rootDOMNode.id === flow.documentNodeIdentifier; - }, - - _contentFlowListWasUpdated: function(event) - { - if (!this._rootDOMNode || this._rootDOMNode.id !== event.data.documentNodeIdentifier) - return; - - // Assume that all the flows have been removed. - var deletedFlows = {}; - for (var flowId in this._flowMap) - deletedFlows[flowId] = this._flowMap[flowId]; - - var newFlows = []; - - var flows = event.data.flows; - for (var i = 0; i < flows.length; ++i) { - var flow = flows[i]; - // All the flows received from WebKit are part of the same document. - console.assert(this._isContentFlowInCurrentDocument(flow)); - - var flowId = flow.id; - if (this._flowMap.hasOwnProperty(flowId)) { - // Remove the flow name from the deleted list. - console.assert(deletedFlows.hasOwnProperty(flowId)); - delete deletedFlows[flowId]; - } else { - this._flowMap[flowId] = flow; - newFlows.push(flow); - } - } - - for (var flowId in deletedFlows) { - delete this._flowMap[flowId]; - } - - // Send update events to listeners. - - for (var flowId in deletedFlows) - this.dispatchEventToListeners(WebInspector.DOMTree.Event.ContentFlowWasRemoved, {flow: deletedFlows[flowId]}); - - for (var i = 0; i < newFlows.length; ++i) - this.dispatchEventToListeners(WebInspector.DOMTree.Event.ContentFlowWasAdded, {flow: newFlows[i]}); - }, - - _contentFlowWasAdded: function(event) - { - var flow = event.data.flow; - if (!this._isContentFlowInCurrentDocument(flow)) - return; - - var flowId = flow.id; - console.assert(!this._flowMap.hasOwnProperty(flowId)); - this._flowMap[flowId] = flow; - - this.dispatchEventToListeners(WebInspector.DOMTree.Event.ContentFlowWasAdded, {flow: flow}); - }, - - _contentFlowWasRemoved: function(event) - { - var flow = event.data.flow; - if (!this._isContentFlowInCurrentDocument(flow)) - return; - - var flowId = flow.id; - console.assert(this._flowMap.hasOwnProperty(flowId)); - delete this._flowMap[flowId]; - - this.dispatchEventToListeners(WebInspector.DOMTree.Event.ContentFlowWasRemoved, {flow: flow}); - } -}; - -WebInspector.DOMTree.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/DOMTreeContentView.css b/Source/WebInspectorUI/UserInterface/DOMTreeContentView.css deleted file mode 100644 index b00e8b196..000000000 --- a/Source/WebInspectorUI/UserInterface/DOMTreeContentView.css +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.content-view.dom-tree { - overflow: auto; -} diff --git a/Source/WebInspectorUI/UserInterface/DOMTreeContentView.js b/Source/WebInspectorUI/UserInterface/DOMTreeContentView.js deleted file mode 100644 index 6ed7c3675..000000000 --- a/Source/WebInspectorUI/UserInterface/DOMTreeContentView.js +++ /dev/null @@ -1,426 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.DOMTreeContentView = function(representedObject) -{ - console.assert(representedObject); - - WebInspector.ContentView.call(this, representedObject); - - this._compositingBordersButtonNavigationItem = new WebInspector.ActivateButtonNavigationItem("layer-borders", WebInspector.UIString("Show compositing borders"), WebInspector.UIString("Hide compositing borders"), "Images/LayerBorders.svg", 16, 16); - this._compositingBordersButtonNavigationItem.addEventListener(WebInspector.ButtonNavigationItem.Event.Clicked, this._toggleCompositingBorders, this); - this._compositingBordersButtonNavigationItem.enabled = !!PageAgent.getCompositingBordersVisible; - - WebInspector.showShadowDOMSetting.addEventListener(WebInspector.Setting.Event.Changed, this._showShadowDOMSettingChanged, this); - this._showsShadowDOMButtonNavigationItem = new WebInspector.ActivateButtonNavigationItem("shows-shadow-DOM", WebInspector.UIString("Show shadow DOM nodes"), WebInspector.UIString("Hide shadow DOM nodes"), "Images/ShadowDOM.svg", 16, 16); - this._showsShadowDOMButtonNavigationItem.addEventListener(WebInspector.ButtonNavigationItem.Event.Clicked, this._toggleShowsShadowDOMSetting, this); - this._showShadowDOMSettingChanged(); - - this.element.classList.add(WebInspector.DOMTreeContentView.StyleClassName); - this.element.addEventListener("click", this._mouseWasClicked.bind(this), false); - - this._domTreeOutline = new WebInspector.DOMTreeOutline(true, true, false); - this._domTreeOutline.addEventListener(WebInspector.DOMTreeOutline.Event.SelectedNodeChanged, this._selectedNodeDidChange, this); - this._domTreeOutline.wireToDomAgent(); - this.element.appendChild(this._domTreeOutline.element); - - WebInspector.domTreeManager.addEventListener(WebInspector.DOMTreeManager.Event.AttributeModified, this._domNodeChanged, this); - WebInspector.domTreeManager.addEventListener(WebInspector.DOMTreeManager.Event.AttributeRemoved, this._domNodeChanged, this); - WebInspector.domTreeManager.addEventListener(WebInspector.DOMTreeManager.Event.CharacterDataModified, this._domNodeChanged, this); - - this._lastSelectedNodePathSetting = new WebInspector.Setting("last-selected-node-path", null); - - this._numberOfSearchResults = null; -}; - -WebInspector.DOMTreeContentView.StyleClassName = "dom-tree"; - -WebInspector.DOMTreeContentView.prototype = { - constructor: WebInspector.DOMTreeContentView, - __proto__: WebInspector.ContentView.prototype, - - // Public - - get navigationItems() - { - return [this._showsShadowDOMButtonNavigationItem, this._compositingBordersButtonNavigationItem]; - }, - - get domTreeOutline() - { - return this._domTreeOutline; - }, - - get scrollableElements() - { - return [this.element]; - }, - - updateLayout: function() - { - this._domTreeOutline.updateSelection(); - }, - - shown: function() - { - this._domTreeOutline.setVisible(true, WebInspector.isConsoleFocused()); - this._updateCompositingBordersButtonToMatchPageSettings(); - }, - - hidden: function() - { - WebInspector.domTreeManager.hideDOMNodeHighlight(); - this._domTreeOutline.setVisible(false); - }, - - closed: function() - { - WebInspector.domTreeManager.removeEventListener(null, null, this); - - this._domTreeOutline.close(); - }, - - get selectionPathComponents() - { - var treeElement = this._domTreeOutline.selectedTreeElement; - var pathComponents = []; - - while (treeElement && !treeElement.root) { - // The close tag is contained within the element it closes. So skip it since we don't want to - // show the same node twice in the hierarchy. - if (treeElement.isCloseTag()) { - treeElement = treeElement.parent; - continue; - } - - var pathComponent = new WebInspector.DOMTreeElementPathComponent(treeElement, treeElement.representedObject); - pathComponent.addEventListener(WebInspector.HierarchicalPathComponent.Event.SiblingWasSelected, this._pathComponentSelected, this); - pathComponents.unshift(pathComponent); - treeElement = treeElement.parent; - } - - return pathComponents; - }, - - selectAndRevealDOMNode: function(domNode, preventFocusChange) - { - this._domTreeOutline.selectDOMNode(domNode, !preventFocusChange); - }, - - handleCopyEvent: function(event) - { - var selectedDOMNode = this._domTreeOutline.selectedDOMNode(); - if (!selectedDOMNode) - return; - - event.clipboardData.clearData(); - event.preventDefault(); - - selectedDOMNode.copyNode(); - }, - - get supportsSave() - { - return WebInspector.canArchiveMainFrame(); - }, - - get saveData() - { - function saveHandler(forceSaveAs) - { - WebInspector.archiveMainFrame(); - } - - return { customSaveHandler: saveHandler }; - }, - - get supportsSearch() - { - return true; - }, - - get numberOfSearchResults() - { - return this._numberOfSearchResults; - }, - - get hasPerformedSearch() - { - return this._numberOfSearchResults !== null; - }, - - set automaticallyRevealFirstSearchResult(reveal) - { - this._automaticallyRevealFirstSearchResult = reveal; - - // If we haven't shown a search result yet, reveal one now. - if (this._automaticallyRevealFirstSearchResult && this._numberOfSearchResults > 0) { - if (this._currentSearchResultIndex === -1) - this.revealNextSearchResult(); - } - }, - - performSearch: function(query) - { - if (this._searchQuery === query) - return; - - if (this._searchIdentifier) - DOMAgent.discardSearchResults(this._searchIdentifier); - - this._searchQuery = query; - this._searchIdentifier = null; - this._numberOfSearchResults = null; - this._currentSearchResultIndex = -1; - - function searchResultsReady(error, searchIdentifier, resultsCount) - { - if (error) - return; - - this._searchIdentifier = searchIdentifier; - this._numberOfSearchResults = resultsCount; - - this.dispatchEventToListeners(WebInspector.ContentView.Event.NumberOfSearchResultsDidChange); - - if (this._automaticallyRevealFirstSearchResult) - this.revealNextSearchResult(); - } - - function contextNodesReady(nodeIds) - { - DOMAgent.performSearch(query, nodeIds, searchResultsReady.bind(this)); - } - - this.getSearchContextNodes(contextNodesReady.bind(this)); - }, - - getSearchContextNodes: function(callback) - { - // Overwrite this to limit the search to just a subtree. - // Passing undefined will make DOMAgent.performSearch search through all the documents. - callback(undefined); - }, - - searchCleared: function() - { - if (this._searchIdentifier) - DOMAgent.discardSearchResults(this._searchIdentifier); - - this._searchQuery = null; - this._searchIdentifier = null; - this._numberOfSearchResults = null; - this._currentSearchResultIndex = -1; - }, - - revealPreviousSearchResult: function(changeFocus) - { - if (!this._numberOfSearchResults) - return; - - if (this._currentSearchResultIndex > 0) - --this._currentSearchResultIndex; - else - this._currentSearchResultIndex = this._numberOfSearchResults - 1; - - this._revealSearchResult(this._currentSearchResultIndex, changeFocus); - }, - - revealNextSearchResult: function(changeFocus) - { - if (!this._numberOfSearchResults) - return; - - if (this._currentSearchResultIndex + 1 < this._numberOfSearchResults) - ++this._currentSearchResultIndex; - else - this._currentSearchResultIndex = 0; - - this._revealSearchResult(this._currentSearchResultIndex, changeFocus); - }, - - // Private - - _revealSearchResult: function(index, changeFocus) - { - console.assert(this._searchIdentifier); - - var searchIdentifier = this._searchIdentifier; - - function revealResult(error, nodeIdentifiers) - { - if (error) - return; - - // Bail if the searchIdentifier changed since we started. - if (this._searchIdentifier !== searchIdentifier) - return; - - console.assert(nodeIdentifiers.length === 1); - - var domNode = WebInspector.domTreeManager.nodeForId(nodeIdentifiers[0]); - console.assert(domNode); - if (!domNode) - return; - - this._domTreeOutline.selectDOMNode(domNode, changeFocus); - } - - DOMAgent.getSearchResults(this._searchIdentifier, index, index + 1, revealResult.bind(this)); - }, - - _restoreSelectedNodeAfterUpdate: function(documentURL, defaultNode) - { - function selectNode(lastSelectedNode) - { - var nodeToFocus = lastSelectedNode; - if (!nodeToFocus) - nodeToFocus = defaultNode; - - if (!nodeToFocus) - return; - - this._dontSetLastSelectedNodePath = true; - this.selectAndRevealDOMNode(nodeToFocus, WebInspector.isConsoleFocused()); - this._dontSetLastSelectedNodePath = false; - - // If this wasn't the last selected node, then expand it. - if (!lastSelectedNode && this._domTreeOutline.selectedTreeElement) - this._domTreeOutline.selectedTreeElement.expand(); - } - - function selectLastSelectedNode(nodeId) - { - selectNode.call(this, WebInspector.domTreeManager.nodeForId(nodeId)); - } - - if (documentURL && this._lastSelectedNodePathSetting.value && this._lastSelectedNodePathSetting.value.path && this._lastSelectedNodePathSetting.value.url === documentURL.hash) - WebInspector.domTreeManager.pushNodeByPathToFrontend(this._lastSelectedNodePathSetting.value.path, selectLastSelectedNode.bind(this)); - else - selectNode.call(this); - }, - - _selectedNodeDidChange: function(event) - { - var selectedDOMNode = this._domTreeOutline.selectedDOMNode(); - if (selectedDOMNode && !this._dontSetLastSelectedNodePath) - this._lastSelectedNodePathSetting.value = {url: selectedDOMNode.ownerDocument.documentURL.hash, path: selectedDOMNode.path()}; - - if (selectedDOMNode) - ConsoleAgent.addInspectedNode(selectedDOMNode.id); - - this.dispatchEventToListeners(WebInspector.ContentView.Event.SelectionPathComponentsDidChange); - }, - - _pathComponentSelected: function(event) - { - console.assert(event.data.pathComponent instanceof WebInspector.DOMTreeElementPathComponent); - console.assert(event.data.pathComponent.domTreeElement instanceof WebInspector.DOMTreeElement); - - this._domTreeOutline.selectDOMNode(event.data.pathComponent.domTreeElement.representedObject, true); - }, - - _domNodeChanged: function(event) - { - var selectedDOMNode = this._domTreeOutline.selectedDOMNode(); - if (selectedDOMNode !== event.data.node) - return; - - this.dispatchEventToListeners(WebInspector.ContentView.Event.SelectionPathComponentsDidChange); - }, - - _mouseWasClicked: function(event) - { - var anchorElement = event.target.enclosingNodeOrSelfWithNodeName("a"); - if (!anchorElement || !anchorElement.href) - return; - - // Prevent the link from navigating, since we don't do any navigation by following links normally. - event.preventDefault(); - event.stopPropagation(); - - if (WebInspector.isBeingEdited(anchorElement)) { - // Don't follow the link when it is being edited. - return; - } - - // Cancel any pending link navigation. - if (this._followLinkTimeoutIdentifier) { - clearTimeout(this._followLinkTimeoutIdentifier); - delete this._followLinkTimeoutIdentifier; - } - - // If this is a double-click (or multiple-click), return early. - if (event.detail > 1) - return; - - function followLink() - { - // Since followLink is delayed, the call to WebInspector.openURL can't look at window.event - // to see if the command key is down like it normally would. So we need to do that check - // before calling WebInspector.openURL. - var alwaysOpenExternally = event ? event.metaKey : false; - WebInspector.openURL(anchorElement.href, this._frame, alwaysOpenExternally, anchorElement.lineNumber); - } - - // Start a timeout since this is a single click, if the timeout is canceled before it fires, - // then a double-click happened or another link was clicked. - // FIXME: The duration might be longer or shorter than the user's configured double click speed. - this._followLinkTimeoutIdentifier = setTimeout(followLink.bind(this), 333); - }, - - _toggleCompositingBorders: function(event) - { - console.assert(PageAgent.setCompositingBordersVisible); - - var activated = !this._compositingBordersButtonNavigationItem.activated; - this._compositingBordersButtonNavigationItem.activated = activated; - PageAgent.setCompositingBordersVisible(activated); - }, - - _updateCompositingBordersButtonToMatchPageSettings: function() - { - if (!PageAgent.getCompositingBordersVisible) - return; - - var button = this._compositingBordersButtonNavigationItem; - - // We need to sync with the page settings since these can be controlled - // in a different way than just using the navigation bar button. - PageAgent.getCompositingBordersVisible(function(error, compositingBordersVisible) { - button.activated = error ? false : compositingBordersVisible; - }); - }, - - _showShadowDOMSettingChanged: function(event) - { - this._showsShadowDOMButtonNavigationItem.activated = WebInspector.showShadowDOMSetting.value; - }, - - _toggleShowsShadowDOMSetting: function(event) - { - WebInspector.showShadowDOMSetting.value = !WebInspector.showShadowDOMSetting.value; - } -}; diff --git a/Source/WebInspectorUI/UserInterface/DOMTreeDataGrid.css b/Source/WebInspectorUI/UserInterface/DOMTreeDataGrid.css deleted file mode 100644 index 0c2766aa3..000000000 --- a/Source/WebInspectorUI/UserInterface/DOMTreeDataGrid.css +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - - .dom-tree-data-grid .data-grid { - position: relative; - top: 0; - width: 100%; - height: 100%; - /* Turn off the default borders, we want to snap to edges. */ - border: none; -} - -.dom-tree-data-grid .data-grid table.data { - background-size: 100% 44px; -} - -.dom-tree-data-grid .data-container { - position: absolute; - /* Leave room for the data grid header. */ - top: 16px; - /* Use all remaining vertical space in the container. */ - bottom: 0; - /* Let the inline table content scroll, independently of the header. */ - overflow-y: auto; - overflow-x: hidden; -} - -.dom-tree-data-grid .data-container tr { - height: 22px; -} - -.dom-tree-data-grid .data-container td > div { - display: -webkit-flex; - width: 100%; - height: 100%; - -webkit-align-items: center; - -webkit-justify-content: flex-end; -} - -.dom-tree-data-grid .data-container .name-column { - padding-right: 0; -} - -.dom-tree-data-grid .data-container .name-column .icon { - vertical-align: top; - width: 16px; - height: 16px; - /* FIXME: There can be multiple types of DOM nodes that we might need to support in the future. */ - content: url(Images/DOMElement.svg); -} - -.dom-tree-data-grid .data-container .name-column .label { - -webkit-flex: 1; - padding: 0 4px; - - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; -} - -.dom-tree-data-grid .data-container tr:hover .name-column .label { - padding-right: 0; -} - -.dom-tree-data-grid .data-container .go-to-arrow { - display: none; -} - -.dom-tree-data-grid .data-container tr:hover .go-to-arrow { - display: block; -} - -.dom-tree-data-grid .data-container tbody > tr:nth-child(2n) { - background-color: white; -} - -.dom-tree-data-grid .data-container tbody > tr:nth-child(2n+1) { - background-color: rgb(243, 246, 250); -} diff --git a/Source/WebInspectorUI/UserInterface/DOMTreeDataGrid.js b/Source/WebInspectorUI/UserInterface/DOMTreeDataGrid.js deleted file mode 100644 index e9783cf05..000000000 --- a/Source/WebInspectorUI/UserInterface/DOMTreeDataGrid.js +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (C) 2013 Adobe Systems Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.DOMTreeDataGrid = function() { - WebInspector.DataGrid.call(this, { - name: { title: WebInspector.UIString("Node"), sortable: false } - }); - - this._previousHoveredElement = null; - - this.element.classList.add("dom-tree-data-grid"); - - this.element.addEventListener("mousemove", this._onmousemove.bind(this), false); - this.element.addEventListener("mouseout", this._onmouseout.bind(this), false); -}; - -WebInspector.DOMTreeDataGrid.prototype = { - constructor: WebInspector.DOMTreeDataGrid, - __proto__: WebInspector.DataGrid.prototype, - - _onmousemove: function(event) - { - var gridNode = this.dataGridNodeFromNode(event.target); - if (!gridNode || this._previousHoveredElement === gridNode.domNode) - return; - this._previousHoveredElement = gridNode.domNode; - WebInspector.domTreeManager.highlightDOMNode(gridNode.domNode.id); - }, - - _onmouseout: function(event) { - if (!this._previousHoveredElement) - return; - WebInspector.domTreeManager.hideDOMNodeHighlight(); - this._previousHoveredElement = null; - } -}; - diff --git a/Source/WebInspectorUI/UserInterface/DOMTreeDataGridNode.js b/Source/WebInspectorUI/UserInterface/DOMTreeDataGridNode.js deleted file mode 100644 index 0a978e30f..000000000 --- a/Source/WebInspectorUI/UserInterface/DOMTreeDataGridNode.js +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (C) 2013 Adobe Systems Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.DOMTreeDataGridNode = function(domNode) -{ - WebInspector.DataGridNode.call(this); - - this._nameLabel = null; - this._domNode = domNode; - this._updateNodeName(); -}; - -WebInspector.DOMTreeDataGridNode.prototype = { - constructor: WebInspector.DOMTreeDataGridNode, - __proto__: WebInspector.DataGridNode.prototype, - - get domNode() - { - return this._domNode; - }, - - // DataGridNode Overrides. - - createCellContent: function(columnIdentifier, cell) - { - if (columnIdentifier !== "name") - return WebInspector.DataGridNode.prototype.createCellContent.call(this, columnIdentifier, cell); - - var cell = this._makeNameCell(); - this._updateNameCellData(); - return cell; - }, - - // Private - - _updateNodeName: function() - { - this.data = {name: WebInspector.displayNameForNode(this._domNode)}; - }, - - _makeNameCell: function() - { - var fragment = document.createDocumentFragment(); - - fragment.appendChild(document.createElement("img")).className = "icon"; - - this._nameLabel = document.createElement("div"); - this._nameLabel.className = "label"; - fragment.appendChild(this._nameLabel); - - var goToButton = fragment.appendChild(WebInspector.createGoToArrowButton()); - goToButton.addEventListener("click", this._goToArrowWasClicked.bind(this), false); - - return fragment; - }, - - _updateNameCellData: function() - { - this._nameLabel.textContent = this.data.name; - }, - - _goToArrowWasClicked: function() - { - WebInspector.resourceSidebarPanel.showMainFrameDOMTree(this._domNode, true); - } -}; - diff --git a/Source/WebInspectorUI/UserInterface/DOMTreeElement.js b/Source/WebInspectorUI/UserInterface/DOMTreeElement.js deleted file mode 100644 index 07bd89e31..000000000 --- a/Source/WebInspectorUI/UserInterface/DOMTreeElement.js +++ /dev/null @@ -1,1319 +0,0 @@ -/* - * Copyright (C) 2007, 2008, 2013 Apple Inc. All rights reserved. - * Copyright (C) 2008 Matt Lilek - * Copyright (C) 2009 Joseph Pecoraro - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/** - * @constructor - * @extends {TreeElement} - * @param {boolean=} elementCloseTag - */ -WebInspector.DOMTreeElement = function(node, elementCloseTag) -{ - this._elementCloseTag = elementCloseTag; - var hasChildrenOverride = !elementCloseTag && node.hasChildNodes() && !this._showInlineText(node); - - // The title will be updated in onattach. - TreeElement.call(this, "", node, hasChildrenOverride); - - if (this.representedObject.nodeType() == Node.ELEMENT_NODE && !elementCloseTag) - this._canAddAttributes = true; - this._searchQuery = null; - this._expandedChildrenLimit = WebInspector.DOMTreeElement.InitialChildrenLimit; -} - -WebInspector.DOMTreeElement.InitialChildrenLimit = 500; -WebInspector.DOMTreeElement.MaximumInlineTextChildLength = 80; - -// A union of HTML4 and HTML5-Draft elements that explicitly -// or implicitly (for HTML5) forbid the closing tag. -// FIXME: Revise once HTML5 Final is published. -WebInspector.DOMTreeElement.ForbiddenClosingTagElements = [ - "area", "base", "basefont", "br", "canvas", "col", "command", "embed", "frame", - "hr", "img", "input", "isindex", "keygen", "link", "meta", "param", "source" -].keySet(); - -// These tags we do not allow editing their tag name. -WebInspector.DOMTreeElement.EditTagBlacklist = [ - "html", "head", "body" -].keySet(); - -WebInspector.DOMTreeElement.prototype = { - isCloseTag: function() - { - return this._elementCloseTag; - }, - - highlightSearchResults: function(searchQuery) - { - if (this._searchQuery !== searchQuery) { - this._updateSearchHighlight(false); - delete this._highlightResult; // A new search query. - } - - this._searchQuery = searchQuery; - this._searchHighlightsVisible = true; - this.updateTitle(true); - }, - - hideSearchHighlights: function() - { - delete this._searchHighlightsVisible; - this._updateSearchHighlight(false); - }, - - _updateSearchHighlight: function(show) - { - if (!this._highlightResult) - return; - - function updateEntryShow(entry) - { - switch (entry.type) { - case "added": - entry.parent.insertBefore(entry.node, entry.nextSibling); - break; - case "changed": - entry.node.textContent = entry.newText; - break; - } - } - - function updateEntryHide(entry) - { - switch (entry.type) { - case "added": - if (entry.node.parentElement) - entry.node.parentElement.removeChild(entry.node); - break; - case "changed": - entry.node.textContent = entry.oldText; - break; - } - } - - var updater = show ? updateEntryShow : updateEntryHide; - - for (var i = 0, size = this._highlightResult.length; i < size; ++i) - updater(this._highlightResult[i]); - }, - - get hovered() - { - return this._hovered; - }, - - set hovered(x) - { - if (this._hovered === x) - return; - - this._hovered = x; - - if (this.listItemElement) { - if (x) { - this.updateSelection(); - this.listItemElement.classList.add("hovered"); - } else { - this.listItemElement.classList.remove("hovered"); - } - } - }, - - get expandedChildrenLimit() - { - return this._expandedChildrenLimit; - }, - - set expandedChildrenLimit(x) - { - if (this._expandedChildrenLimit === x) - return; - - this._expandedChildrenLimit = x; - if (this.treeOutline && !this._updateChildrenInProgress) - this._updateChildren(true); - }, - - get expandedChildCount() - { - var count = this.children.length; - if (count && this.children[count - 1]._elementCloseTag) - count--; - if (count && this.children[count - 1].expandAllButton) - count--; - return count; - }, - - showChild: function(index) - { - if (this._elementCloseTag) - return; - - if (index >= this.expandedChildrenLimit) { - this._expandedChildrenLimit = index + 1; - this._updateChildren(true); - } - - // Whether index-th child is visible in the children tree - return this.expandedChildCount > index; - }, - - _createTooltipForNode: function() - { - var node = /** @type {WebInspector.DOMNode} */ this.representedObject; - if (!node.nodeName() || node.nodeName().toLowerCase() !== "img") - return; - - function setTooltip(result) - { - if (!result || result.type !== "string") - return; - - try { - var properties = JSON.parse(result.description); - var offsetWidth = properties[0]; - var offsetHeight = properties[1]; - var naturalWidth = properties[2]; - var naturalHeight = properties[3]; - if (offsetHeight === naturalHeight && offsetWidth === naturalWidth) - this.tooltip = WebInspector.UIString("%d \xd7 %d pixels").format(offsetWidth, offsetHeight); - else - this.tooltip = WebInspector.UIString("%d \xd7 %d pixels (Natural: %d \xd7 %d pixels)").format(offsetWidth, offsetHeight, naturalWidth, naturalHeight); - } catch (e) { - console.error(e); - } - } - - function resolvedNode(object) - { - if (!object) - return; - - function dimensions() - { - return "[" + this.offsetWidth + "," + this.offsetHeight + "," + this.naturalWidth + "," + this.naturalHeight + "]"; - } - - object.callFunction(dimensions, undefined, setTooltip.bind(this)); - object.release(); - } - WebInspector.RemoteObject.resolveNode(node, "", resolvedNode.bind(this)); - }, - - updateSelection: function() - { - var listItemElement = this.listItemElement; - if (!listItemElement) - return; - - if (document.body.offsetWidth <= 0) { - // The stylesheet hasn't loaded yet or the window is closed, - // so we can't calculate what is need. Return early. - return; - } - - if (!this.selectionElement) { - this.selectionElement = document.createElement("div"); - this.selectionElement.className = "selection selected"; - listItemElement.insertBefore(this.selectionElement, listItemElement.firstChild); - } - - this.selectionElement.style.height = listItemElement.offsetHeight + "px"; - }, - - onattach: function() - { - if (this._hovered) { - this.updateSelection(); - this.listItemElement.classList.add("hovered"); - } - - this.updateTitle(); - this.listItemElement.draggable = true; - this.listItemElement.addEventListener("dragstart", this); - }, - - onpopulate: function() - { - if (this.children.length || this._showInlineText(this.representedObject) || this._elementCloseTag) - return; - - this.updateChildren(); - }, - - expandRecursively: function() - { - function callback() - { - TreeElement.prototype.expandRecursively.call(this, Number.MAX_VALUE); - } - - this.representedObject.getSubtree(-1, callback.bind(this)); - }, - - /** - * @param {boolean=} fullRefresh - */ - updateChildren: function(fullRefresh) - { - if (this._elementCloseTag) - return; - this.representedObject.getChildNodes(this._updateChildren.bind(this, fullRefresh)); - }, - - /** - * @param {boolean=} closingTag - */ - insertChildElement: function(child, index, closingTag) - { - var newElement = new WebInspector.DOMTreeElement(child, closingTag); - newElement.selectable = this.treeOutline._selectEnabled; - this.insertChild(newElement, index); - return newElement; - }, - - moveChild: function(child, targetIndex) - { - var wasSelected = child.selected; - this.removeChild(child); - this.insertChild(child, targetIndex); - if (wasSelected) - child.select(); - }, - - /** - * @param {boolean=} fullRefresh - */ - _updateChildren: function(fullRefresh) - { - if (this._updateChildrenInProgress || !this.treeOutline._visible) - return; - - this._updateChildrenInProgress = true; - var selectedNode = this.treeOutline.selectedDOMNode(); - var originalScrollTop = 0; - if (fullRefresh) { - var treeOutlineContainerElement = this.treeOutline.element.parentNode; - originalScrollTop = treeOutlineContainerElement.scrollTop; - var selectedTreeElement = this.treeOutline.selectedTreeElement; - if (selectedTreeElement && selectedTreeElement.hasAncestor(this)) - this.select(); - this.removeChildren(); - } - - var treeElement = this; - var treeChildIndex = 0; - var elementToSelect; - - function updateChildrenOfNode(node) - { - var treeOutline = treeElement.treeOutline; - var child = node.firstChild; - while (child) { - var currentTreeElement = treeElement.children[treeChildIndex]; - if (!currentTreeElement || currentTreeElement.representedObject !== child) { - // Find any existing element that is later in the children list. - var existingTreeElement = null; - for (var i = (treeChildIndex + 1), size = treeElement.expandedChildCount; i < size; ++i) { - if (treeElement.children[i].representedObject === child) { - existingTreeElement = treeElement.children[i]; - break; - } - } - - if (existingTreeElement && existingTreeElement.parent === treeElement) { - // If an existing element was found and it has the same parent, just move it. - treeElement.moveChild(existingTreeElement, treeChildIndex); - } else { - // No existing element found, insert a new element. - if (treeChildIndex < treeElement.expandedChildrenLimit) { - var newElement = treeElement.insertChildElement(child, treeChildIndex); - if (child === selectedNode) - elementToSelect = newElement; - if (treeElement.expandedChildCount > treeElement.expandedChildrenLimit) - treeElement.expandedChildrenLimit++; - } - } - } - - child = child.nextSibling; - ++treeChildIndex; - } - } - - // Remove any tree elements that no longer have this node (or this node's contentDocument) as their parent. - for (var i = (this.children.length - 1); i >= 0; --i) { - var currentChild = this.children[i]; - var currentNode = currentChild.representedObject; - var currentParentNode = currentNode.parentNode; - - if (currentParentNode === this.representedObject) - continue; - - var selectedTreeElement = this.treeOutline.selectedTreeElement; - if (selectedTreeElement && (selectedTreeElement === currentChild || selectedTreeElement.hasAncestor(currentChild))) - this.select(); - - this.removeChildAtIndex(i); - } - - updateChildrenOfNode(this.representedObject); - this.adjustCollapsedRange(); - - var lastChild = this.children.lastValue; - if (this.representedObject.nodeType() == Node.ELEMENT_NODE && (!lastChild || !lastChild._elementCloseTag)) - this.insertChildElement(this.representedObject, this.children.length, true); - - // We want to restore the original selection and tree scroll position after a full refresh, if possible. - if (fullRefresh && elementToSelect) { - elementToSelect.select(); - if (treeOutlineContainerElement && originalScrollTop <= treeOutlineContainerElement.scrollHeight) - treeOutlineContainerElement.scrollTop = originalScrollTop; - } - - delete this._updateChildrenInProgress; - }, - - adjustCollapsedRange: function() - { - // Ensure precondition: only the tree elements for node children are found in the tree - // (not the Expand All button or the closing tag). - if (this.expandAllButtonElement && this.expandAllButtonElement.__treeElement.parent) - this.removeChild(this.expandAllButtonElement.__treeElement); - - const node = this.representedObject; - if (!node.children) - return; - const childNodeCount = node.children.length; - - // In case some nodes from the expanded range were removed, pull some nodes from the collapsed range into the expanded range at the bottom. - for (var i = this.expandedChildCount, limit = Math.min(this.expandedChildrenLimit, childNodeCount); i < limit; ++i) - this.insertChildElement(node.children[i], i); - - const expandedChildCount = this.expandedChildCount; - if (childNodeCount > this.expandedChildCount) { - var targetButtonIndex = expandedChildCount; - if (!this.expandAllButtonElement) { - var button = document.createElement("button"); - button.className = "show-all-nodes"; - button.value = ""; - var item = new TreeElement(button, null, false); - item.selectable = false; - item.expandAllButton = true; - this.insertChild(item, targetButtonIndex); - this.expandAllButtonElement = item.listItemElement.firstChild; - this.expandAllButtonElement.__treeElement = item; - this.expandAllButtonElement.addEventListener("click", this.handleLoadAllChildren.bind(this), false); - } else if (!this.expandAllButtonElement.__treeElement.parent) - this.insertChild(this.expandAllButtonElement.__treeElement, targetButtonIndex); - this.expandAllButtonElement.textContent = WebInspector.UIString("Show All Nodes (%d More)").format(childNodeCount - expandedChildCount); - } else if (this.expandAllButtonElement) - delete this.expandAllButtonElement; - }, - - handleLoadAllChildren: function() - { - this.expandedChildrenLimit = Math.max(this.representedObject.childNodeCount, this.expandedChildrenLimit + WebInspector.DOMTreeElement.InitialChildrenLimit); - }, - - onexpand: function() - { - if (this._elementCloseTag) - return; - - this.updateTitle(); - this.treeOutline.updateSelection(); - }, - - oncollapse: function() - { - if (this._elementCloseTag) - return; - - this.updateTitle(); - this.treeOutline.updateSelection(); - }, - - onreveal: function() - { - if (this.listItemElement) { - var tagSpans = this.listItemElement.getElementsByClassName("html-tag-name"); - if (tagSpans.length) - tagSpans[0].scrollIntoViewIfNeeded(false); - else - this.listItemElement.scrollIntoViewIfNeeded(false); - } - }, - - onselect: function(treeElement, selectedByUser) - { - this.treeOutline.suppressRevealAndSelect = true; - this.treeOutline.selectDOMNode(this.representedObject, selectedByUser); - if (selectedByUser) - WebInspector.domTreeManager.highlightDOMNode(this.representedObject.id); - this.updateSelection(); - this.treeOutline.suppressRevealAndSelect = false; - }, - - ondeselect: function(treeElement) - { - this.treeOutline.selectDOMNode(null); - }, - - ondelete: function() - { - var startTagTreeElement = this.treeOutline.findTreeElement(this.representedObject); - startTagTreeElement ? startTagTreeElement.remove() : this.remove(); - return true; - }, - - onenter: function() - { - // On Enter or Return start editing the first attribute - // or create a new attribute on the selected element. - if (this.treeOutline.editing) - return false; - - this._startEditing(); - - // prevent a newline from being immediately inserted - return true; - }, - - selectOnMouseDown: function(event) - { - TreeElement.prototype.selectOnMouseDown.call(this, event); - - if (this._editing) - return; - - // Prevent selecting the nearest word on double click. - if (event.detail >= 2) - event.preventDefault(); - }, - - ondblclick: function(event) - { - if (this._editing || this._elementCloseTag) - return; - - if (this._startEditingTarget(event.target)) - return; - - if (this.hasChildren && !this.expanded) - this.expand(); - }, - - _insertInLastAttributePosition: function(tag, node) - { - if (tag.getElementsByClassName("html-attribute").length > 0) - tag.insertBefore(node, tag.lastChild); - else { - var nodeName = tag.textContent.match(/^<(.*?)>$/)[1]; - tag.textContent = ''; - tag.appendChild(document.createTextNode('<'+nodeName)); - tag.appendChild(node); - tag.appendChild(document.createTextNode('>')); - } - - this.updateSelection(); - }, - - _startEditingTarget: function(eventTarget) - { - if (this.treeOutline.selectedDOMNode() != this.representedObject) - return; - - if (this.representedObject.nodeType() != Node.ELEMENT_NODE && this.representedObject.nodeType() != Node.TEXT_NODE) - return false; - - var textNode = eventTarget.enclosingNodeOrSelfWithClass("html-text-node"); - if (textNode) - return this._startEditingTextNode(textNode); - - var attribute = eventTarget.enclosingNodeOrSelfWithClass("html-attribute"); - if (attribute) - return this._startEditingAttribute(attribute, eventTarget); - - var tagName = eventTarget.enclosingNodeOrSelfWithClass("html-tag-name"); - if (tagName) - return this._startEditingTagName(tagName); - - var newAttribute = eventTarget.enclosingNodeOrSelfWithClass("add-attribute"); - if (newAttribute) - return this._addNewAttribute(); - - return false; - }, - - _populateTagContextMenu: function(contextMenu, event) - { - var attribute = event.target.enclosingNodeOrSelfWithClass("html-attribute"); - var newAttribute = event.target.enclosingNodeOrSelfWithClass("add-attribute"); - - // Add attribute-related actions. - contextMenu.appendItem(WebInspector.UIString("Add Attribute"), this._addNewAttribute.bind(this)); - if (attribute && !newAttribute) - contextMenu.appendItem(WebInspector.UIString("Edit Attribute"), this._startEditingAttribute.bind(this, attribute, event.target)); - contextMenu.appendSeparator(); - - if (WebInspector.cssStyleManager.canForcePseudoClasses()) { - var pseudoSubMenu = contextMenu.appendSubMenuItem(WebInspector.UIString("Forced Pseudo-Classes")); - this._populateForcedPseudoStateItems(pseudoSubMenu); - contextMenu.appendSeparator(); - } - - this._populateNodeContextMenu(contextMenu); - this.treeOutline._populateContextMenu(contextMenu, this.representedObject); - }, - - _populateForcedPseudoStateItems: function(subMenu) - { - var node = this.representedObject; - var enabledPseudoClasses = node.enabledPseudoClasses; - // These strings don't need to be localized as they are CSS pseudo-classes. - WebInspector.CSSStyleManager.ForceablePseudoClasses.forEach(function(pseudoClass) { - var label = pseudoClass.capitalize(); - var enabled = enabledPseudoClasses.contains(pseudoClass); - subMenu.appendCheckboxItem(label, function() { - node.setPseudoClassEnabled(pseudoClass, !enabled); - }, enabled, false); - }); - }, - - _populateTextContextMenu: function(contextMenu, textNode) - { - contextMenu.appendItem(WebInspector.UIString("Edit Text"), this._startEditingTextNode.bind(this, textNode)); - this._populateNodeContextMenu(contextMenu); - }, - - _populateNodeContextMenu: function(contextMenu) - { - // Add free-form node-related actions. - contextMenu.appendItem(WebInspector.UIString("Edit as HTML"), this._editAsHTML.bind(this)); - contextMenu.appendItem(WebInspector.UIString("Copy as HTML"), this._copyHTML.bind(this)); - contextMenu.appendItem(WebInspector.UIString("Delete Node"), this.remove.bind(this)); - }, - - _startEditing: function() - { - if (this.treeOutline.selectedDOMNode() !== this.representedObject) - return; - - var listItem = this._listItemNode; - - if (this._canAddAttributes) { - var attribute = listItem.getElementsByClassName("html-attribute")[0]; - if (attribute) - return this._startEditingAttribute(attribute, attribute.getElementsByClassName("html-attribute-value")[0]); - - return this._addNewAttribute(); - } - - if (this.representedObject.nodeType() === Node.TEXT_NODE) { - var textNode = listItem.getElementsByClassName("html-text-node")[0]; - if (textNode) - return this._startEditingTextNode(textNode); - return; - } - }, - - _addNewAttribute: function() - { - // Cannot just convert the textual html into an element without - // a parent node. Use a temporary span container for the HTML. - var container = document.createElement("span"); - this._buildAttributeDOM(container, " ", ""); - var attr = container.firstChild; - attr.style.marginLeft = "2px"; // overrides the .editing margin rule - attr.style.marginRight = "2px"; // overrides the .editing margin rule - - var tag = this.listItemElement.getElementsByClassName("html-tag")[0]; - this._insertInLastAttributePosition(tag, attr); - return this._startEditingAttribute(attr, attr); - }, - - _triggerEditAttribute: function(attributeName) - { - var attributeElements = this.listItemElement.getElementsByClassName("html-attribute-name"); - for (var i = 0, len = attributeElements.length; i < len; ++i) { - if (attributeElements[i].textContent === attributeName) { - for (var elem = attributeElements[i].nextSibling; elem; elem = elem.nextSibling) { - if (elem.nodeType !== Node.ELEMENT_NODE) - continue; - - if (elem.classList.contains("html-attribute-value")) - return this._startEditingAttribute(elem.parentNode, elem); - } - } - } - }, - - _startEditingAttribute: function(attribute, elementForSelection) - { - if (WebInspector.isBeingEdited(attribute)) - return true; - - var attributeNameElement = attribute.getElementsByClassName("html-attribute-name")[0]; - if (!attributeNameElement) - return false; - - var attributeName = attributeNameElement.textContent; - - function removeZeroWidthSpaceRecursive(node) - { - if (node.nodeType === Node.TEXT_NODE) { - node.nodeValue = node.nodeValue.replace(/\u200B/g, ""); - return; - } - - if (node.nodeType !== Node.ELEMENT_NODE) - return; - - for (var child = node.firstChild; child; child = child.nextSibling) - removeZeroWidthSpaceRecursive(child); - } - - // Remove zero-width spaces that were added by nodeTitleInfo. - removeZeroWidthSpaceRecursive(attribute); - - var config = new WebInspector.EditingConfig(this._attributeEditingCommitted.bind(this), this._editingCancelled.bind(this), attributeName); - this._editing = WebInspector.startEditing(attribute, config); - - window.getSelection().setBaseAndExtent(elementForSelection, 0, elementForSelection, 1); - - return true; - }, - - _startEditingTextNode: function(textNode) - { - if (WebInspector.isBeingEdited(textNode)) - return true; - - var config = new WebInspector.EditingConfig(this._textNodeEditingCommitted.bind(this), this._editingCancelled.bind(this)); - config.spellcheck = true; - this._editing = WebInspector.startEditing(textNode, config); - window.getSelection().setBaseAndExtent(textNode, 0, textNode, 1); - - return true; - }, - - _startEditingTagName: function(tagNameElement) - { - if (!tagNameElement) { - tagNameElement = this.listItemElement.getElementsByClassName("html-tag-name")[0]; - if (!tagNameElement) - return false; - } - - var tagName = tagNameElement.textContent; - if (WebInspector.DOMTreeElement.EditTagBlacklist[tagName.toLowerCase()]) - return false; - - if (WebInspector.isBeingEdited(tagNameElement)) - return true; - - var closingTagElement = this._distinctClosingTagElement(); - - function keyupListener(event) - { - if (closingTagElement) - closingTagElement.textContent = ""; - } - - function editingComitted(element, newTagName) - { - tagNameElement.removeEventListener('keyup', keyupListener, false); - this._tagNameEditingCommitted.apply(this, arguments); - } - - function editingCancelled() - { - tagNameElement.removeEventListener('keyup', keyupListener, false); - this._editingCancelled.apply(this, arguments); - } - - tagNameElement.addEventListener('keyup', keyupListener, false); - - var config = new WebInspector.EditingConfig(editingComitted.bind(this), editingCancelled.bind(this), tagName); - this._editing = WebInspector.startEditing(tagNameElement, config); - window.getSelection().setBaseAndExtent(tagNameElement, 0, tagNameElement, 1); - return true; - }, - - _startEditingAsHTML: function(commitCallback, error, initialValue) - { - if (error) - return; - if (this._htmlEditElement && WebInspector.isBeingEdited(this._htmlEditElement)) - return; - - this._htmlEditElement = document.createElement("div"); - this._htmlEditElement.className = "source-code elements-tree-editor"; - this._htmlEditElement.textContent = initialValue; - - // Hide header items. - var child = this.listItemElement.firstChild; - while (child) { - child.style.display = "none"; - child = child.nextSibling; - } - // Hide children item. - if (this._childrenListNode) - this._childrenListNode.style.display = "none"; - // Append editor. - this.listItemElement.appendChild(this._htmlEditElement); - - this.updateSelection(); - - function commit() - { - commitCallback(this._htmlEditElement.textContent); - dispose.call(this); - } - - function dispose() - { - this._editing = false; - - // Remove editor. - this.listItemElement.removeChild(this._htmlEditElement); - delete this._htmlEditElement; - // Unhide children item. - if (this._childrenListNode) - this._childrenListNode.style.removeProperty("display"); - // Unhide header items. - var child = this.listItemElement.firstChild; - while (child) { - child.style.removeProperty("display"); - child = child.nextSibling; - } - - this.updateSelection(); - } - - var config = new WebInspector.EditingConfig(commit.bind(this), dispose.bind(this)); - config.setMultiline(true); - this._editing = WebInspector.startEditing(this._htmlEditElement, config); - }, - - _attributeEditingCommitted: function(element, newText, oldText, attributeName, moveDirection) - { - this._editing = false; - - var treeOutline = this.treeOutline; - function moveToNextAttributeIfNeeded(error) - { - if (error) - this._editingCancelled(element, attributeName); - - if (!moveDirection) - return; - - treeOutline._updateModifiedNodes(); - - // Search for the attribute's position, and then decide where to move to. - var attributes = this.representedObject.attributes(); - for (var i = 0; i < attributes.length; ++i) { - if (attributes[i].name !== attributeName) - continue; - - if (moveDirection === "backward") { - if (i === 0) - this._startEditingTagName(); - else - this._triggerEditAttribute(attributes[i - 1].name); - } else { - if (i === attributes.length - 1) - this._addNewAttribute(); - else - this._triggerEditAttribute(attributes[i + 1].name); - } - return; - } - - // Moving From the "New Attribute" position. - if (moveDirection === "backward") { - if (newText === " ") { - // Moving from "New Attribute" that was not edited - if (attributes.length) - this._triggerEditAttribute(attributes.lastValue.name); - } else { - // Moving from "New Attribute" that holds new value - if (attributes.length > 1) - this._triggerEditAttribute(attributes[attributes.length - 2].name); - } - } else if (moveDirection === "forward") { - if (!/^\s*$/.test(newText)) - this._addNewAttribute(); - else - this._startEditingTagName(); - } - } - - this.representedObject.setAttribute(attributeName, newText, moveToNextAttributeIfNeeded.bind(this)); - }, - - _tagNameEditingCommitted: function(element, newText, oldText, tagName, moveDirection) - { - this._editing = false; - var self = this; - - function cancel() - { - var closingTagElement = self._distinctClosingTagElement(); - if (closingTagElement) - closingTagElement.textContent = ""; - - self._editingCancelled(element, tagName); - moveToNextAttributeIfNeeded.call(self); - } - - function moveToNextAttributeIfNeeded() - { - if (moveDirection !== "forward") { - this._addNewAttribute(); - return; - } - - var attributes = this.representedObject.attributes(); - if (attributes.length > 0) - this._triggerEditAttribute(attributes[0].name); - else - this._addNewAttribute(); - } - - newText = newText.trim(); - if (newText === oldText) { - cancel(); - return; - } - - var treeOutline = this.treeOutline; - var wasExpanded = this.expanded; - - function changeTagNameCallback(error, nodeId) - { - if (error || !nodeId) { - cancel(); - return; - } - - var node = WebInspector.domTreeManager.nodeForId(nodeId); - - // Select it and expand if necessary. We force tree update so that it processes dom events and is up to date. - treeOutline._updateModifiedNodes(); - treeOutline.selectDOMNode(node, true); - - var newTreeItem = treeOutline.findTreeElement(node); - if (wasExpanded) - newTreeItem.expand(); - - moveToNextAttributeIfNeeded.call(newTreeItem); - } - - this.representedObject.setNodeName(newText, changeTagNameCallback); - }, - - _textNodeEditingCommitted: function(element, newText) - { - this._editing = false; - - var textNode; - if (this.representedObject.nodeType() === Node.ELEMENT_NODE) { - // We only show text nodes inline in elements if the element only - // has a single child, and that child is a text node. - textNode = this.representedObject.firstChild; - } else if (this.representedObject.nodeType() == Node.TEXT_NODE) - textNode = this.representedObject; - - textNode.setNodeValue(newText, this.updateTitle.bind(this)); - }, - - _editingCancelled: function(element, context) - { - this._editing = false; - - // Need to restore attributes structure. - this.updateTitle(); - }, - - _distinctClosingTagElement: function() - { - // FIXME: Improve the Tree Element / Outline Abstraction to prevent crawling the DOM - - // For an expanded element, it will be the last element with class "close" - // in the child element list. - if (this.expanded) { - var closers = this._childrenListNode.querySelectorAll(".close"); - return closers[closers.length-1]; - } - - // Remaining cases are single line non-expanded elements with a closing - // tag, or HTML elements without a closing tag (such as
). Return - // null in the case where there isn't a closing tag. - var tags = this.listItemElement.getElementsByClassName("html-tag"); - return (tags.length === 1 ? null : tags[tags.length-1]); - }, - - /** - * @param {boolean=} onlySearchQueryChanged - */ - updateTitle: function(onlySearchQueryChanged) - { - // If we are editing, return early to prevent canceling the edit. - // After editing is committed updateTitle will be called. - if (this._editing) - return; - - if (onlySearchQueryChanged) { - if (this._highlightResult) - this._updateSearchHighlight(false); - } else { - var highlightElement = document.createElement("span"); - highlightElement.className = "highlight"; - highlightElement.appendChild(this._nodeTitleInfo().titleDOM); - this.title = highlightElement; - delete this._highlightResult; - } - - delete this.selectionElement; - this.updateSelection(); - this._highlightSearchResults(); - }, - - /** - * @param {WebInspector.DOMNode=} node - */ - _buildAttributeDOM: function(parentElement, name, value, node) - { - var hasText = (value.length > 0); - var attrSpanElement = parentElement.createChild("span", "html-attribute"); - var attrNameElement = attrSpanElement.createChild("span", "html-attribute-name"); - attrNameElement.textContent = name; - - if (hasText) - attrSpanElement.appendChild(document.createTextNode("=\u200B\"")); - - if (name === "src" || name === "href") { - var baseURL = node.ownerDocument ? node.ownerDocument.documentURL : null; - var rewrittenURL = absoluteURL(value, baseURL); - - value = value.insertWordBreakCharacters(); - - if (!rewrittenURL) { - var attrValueElement = attrSpanElement.createChild("span", "html-attribute-value"); - attrValueElement.textContent = value; - } else { - if (value.startsWith("data:")) - value = value.trimMiddle(60); - - var linkElement = document.createElement("a"); - linkElement.href = rewrittenURL; - linkElement.textContent = value; - - attrSpanElement.appendChild(linkElement); - } - } else { - value = value.insertWordBreakCharacters(); - var attrValueElement = attrSpanElement.createChild("span", "html-attribute-value"); - attrValueElement.textContent = value; - } - - if (hasText) - attrSpanElement.appendChild(document.createTextNode("\"")); - }, - - _buildTagDOM: function(parentElement, tagName, isClosingTag, isDistinctTreeElement) - { - var node = /** @type WebInspector.DOMNode */ this.representedObject; - var classes = [ "html-tag" ]; - if (isClosingTag && isDistinctTreeElement) - classes.push("close"); - if (node.isInShadowTree()) - classes.push("shadow"); - var tagElement = parentElement.createChild("span", classes.join(" ")); - tagElement.appendChild(document.createTextNode("<")); - var tagNameElement = tagElement.createChild("span", isClosingTag ? "" : "html-tag-name"); - tagNameElement.textContent = (isClosingTag ? "/" : "") + tagName; - if (!isClosingTag && node.hasAttributes()) { - var attributes = node.attributes(); - for (var i = 0; i < attributes.length; ++i) { - var attr = attributes[i]; - tagElement.appendChild(document.createTextNode(" ")); - this._buildAttributeDOM(tagElement, attr.name, attr.value, node); - } - } - tagElement.appendChild(document.createTextNode(">")); - parentElement.appendChild(document.createTextNode("\u200B")); - }, - - _nodeTitleInfo: function() - { - var node = this.representedObject; - var info = {titleDOM: document.createDocumentFragment(), hasChildren: this.hasChildren}; - - switch (node.nodeType()) { - case Node.DOCUMENT_FRAGMENT_NODE: - var fragmentElement = info.titleDOM.createChild("span", "webkit-html-fragment"); - if (node.isInShadowTree()) { - fragmentElement.textContent = WebInspector.UIString("Shadow Content"); - fragmentElement.classList.add("shadow"); - } else - fragmentElement.textContent = WebInspector.UIString("Document Fragment"); - break; - - case Node.ATTRIBUTE_NODE: - var value = node.value || "\u200B"; // Zero width space to force showing an empty value. - this._buildAttributeDOM(info.titleDOM, node.name, value); - break; - - case Node.ELEMENT_NODE: - var tagName = node.nodeNameInCorrectCase(); - if (this._elementCloseTag) { - this._buildTagDOM(info.titleDOM, tagName, true, true); - info.hasChildren = false; - break; - } - - this._buildTagDOM(info.titleDOM, tagName, false, false); - - var textChild = this._singleTextChild(node); - var showInlineText = textChild && textChild.nodeValue().length < WebInspector.DOMTreeElement.MaximumInlineTextChildLength; - - if (!this.expanded && (!showInlineText && (this.treeOutline.isXMLMimeType || !WebInspector.DOMTreeElement.ForbiddenClosingTagElements[tagName]))) { - if (this.hasChildren) { - var textNodeElement = info.titleDOM.createChild("span", "html-text-node"); - textNodeElement.textContent = "\u2026"; - info.titleDOM.appendChild(document.createTextNode("\u200B")); - } - this._buildTagDOM(info.titleDOM, tagName, true, false); - } - - // If this element only has a single child that is a text node, - // just show that text and the closing tag inline rather than - // create a subtree for them - if (showInlineText) { - var textNodeElement = info.titleDOM.createChild("span", "html-text-node"); - var nodeNameLowerCase = node.nodeName().toLowerCase(); - - if (nodeNameLowerCase === "script") - textNodeElement.appendChild(WebInspector.syntaxHighlightStringAsDocumentFragment(textChild.nodeValue().trim(), "text/javascript")); - else if (nodeNameLowerCase === "style") - textNodeElement.appendChild(WebInspector.syntaxHighlightStringAsDocumentFragment(textChild.nodeValue().trim(), "text/css")); - else - textNodeElement.textContent = textChild.nodeValue(); - - info.titleDOM.appendChild(document.createTextNode("\u200B")); - - this._buildTagDOM(info.titleDOM, tagName, true, false); - info.hasChildren = false; - } - break; - - case Node.TEXT_NODE: - function trimedNodeValue() - { - // Trim empty lines from the beginning and extra space at the end since most style and script tags begin with a newline - // and end with a newline and indentation for the end tag. - return node.nodeValue().replace(/^[\n\r]*/, "").replace(/\s*$/, ""); - } - - if (node.parentNode && node.parentNode.nodeName().toLowerCase() === "script") { - var newNode = info.titleDOM.createChild("span", "html-text-node large"); - newNode.appendChild(WebInspector.syntaxHighlightStringAsDocumentFragment(trimedNodeValue(), "text/javascript")); - } else if (node.parentNode && node.parentNode.nodeName().toLowerCase() === "style") { - var newNode = info.titleDOM.createChild("span", "html-text-node large"); - newNode.appendChild(WebInspector.syntaxHighlightStringAsDocumentFragment(trimedNodeValue(), "text/css")); - } else { - info.titleDOM.appendChild(document.createTextNode("\"")); - var textNodeElement = info.titleDOM.createChild("span", "html-text-node"); - textNodeElement.textContent = node.nodeValue(); - info.titleDOM.appendChild(document.createTextNode("\"")); - } - break; - - case Node.COMMENT_NODE: - var commentElement = info.titleDOM.createChild("span", "html-comment"); - commentElement.appendChild(document.createTextNode("")); - break; - - case Node.DOCUMENT_TYPE_NODE: - var docTypeElement = info.titleDOM.createChild("span", "html-doctype"); - docTypeElement.appendChild(document.createTextNode("")); - break; - - case Node.CDATA_SECTION_NODE: - var cdataElement = info.titleDOM.createChild("span", "html-text-node"); - cdataElement.appendChild(document.createTextNode("")); - break; - default: - var defaultElement = info.titleDOM.appendChild(document.createTextNode(node.nodeNameInCorrectCase().collapseWhitespace())); - } - - return info; - }, - - _singleTextChild: function(node) - { - if (!node) - return null; - - var firstChild = node.firstChild; - if (!firstChild || firstChild.nodeType() !== Node.TEXT_NODE) - return null; - - if (node.hasShadowRoots()) - return null; - - var sibling = firstChild.nextSibling; - return sibling ? null : firstChild; - }, - - _showInlineText: function(node) - { - if (node.nodeType() === Node.ELEMENT_NODE) { - var textChild = this._singleTextChild(node); - if (textChild && textChild.nodeValue().length < WebInspector.DOMTreeElement.MaximumInlineTextChildLength) - return true; - } - return false; - }, - - remove: function() - { - var parentElement = this.parent; - if (!parentElement) - return; - - var self = this; - function removeNodeCallback(error, removedNodeId) - { - if (error) - return; - - if (!self.parent) - return; - - parentElement.removeChild(self); - parentElement.adjustCollapsedRange(); - } - - this.representedObject.removeNode(removeNodeCallback); - }, - - _editAsHTML: function() - { - var treeOutline = this.treeOutline; - var node = this.representedObject; - var parentNode = node.parentNode; - var index = node.index; - var wasExpanded = this.expanded; - - function selectNode(error, nodeId) - { - if (error) - return; - - // Select it and expand if necessary. We force tree update so that it processes dom events and is up to date. - treeOutline._updateModifiedNodes(); - - var newNode = parentNode ? parentNode.children[index] || parentNode : null; - if (!newNode) - return; - - treeOutline.selectDOMNode(newNode, true); - - if (wasExpanded) { - var newTreeItem = treeOutline.findTreeElement(newNode); - if (newTreeItem) - newTreeItem.expand(); - } - } - - function commitChange(value) - { - node.setOuterHTML(value, selectNode); - } - - node.getOuterHTML(this._startEditingAsHTML.bind(this, commitChange)); - }, - - _copyHTML: function() - { - this.representedObject.copyNode(); - }, - - _highlightSearchResults: function() - { - if (!this._searchQuery || !this._searchHighlightsVisible) - return; - if (this._highlightResult) { - this._updateSearchHighlight(true); - return; - } - - var text = this.listItemElement.textContent; - var regexObject = createPlainTextSearchRegex(this._searchQuery, "gi"); - - var offset = 0; - var match = regexObject.exec(text); - var matchRanges = []; - while (match) { - matchRanges.push({ offset: match.index, length: match[0].length }); - match = regexObject.exec(text); - } - - // Fall back for XPath, etc. matches. - if (!matchRanges.length) - matchRanges.push({ offset: 0, length: text.length }); - - this._highlightResult = []; - highlightSearchResults(this.listItemElement, matchRanges, this._highlightResult); - }, - - handleEvent: function(event) - { - if (event.type === "dragstart" && this._editing) - event.preventDefault(); - } -} - -WebInspector.DOMTreeElement.prototype.__proto__ = TreeElement.prototype; diff --git a/Source/WebInspectorUI/UserInterface/DOMTreeElementPathComponent.js b/Source/WebInspectorUI/UserInterface/DOMTreeElementPathComponent.js deleted file mode 100644 index 30d51da48..000000000 --- a/Source/WebInspectorUI/UserInterface/DOMTreeElementPathComponent.js +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.DOMTreeElementPathComponent = function(domTreeElement, representedObject) { - var node = domTreeElement.representedObject; - - var title = null; - var className = null; - - switch (node.nodeType()) { - case Node.ELEMENT_NODE: - className = WebInspector.DOMTreeElementPathComponent.DOMElementIconStyleClassName; - title = WebInspector.displayNameForNode(node); - break; - - case Node.TEXT_NODE: - className = WebInspector.DOMTreeElementPathComponent.DOMTextNodeIconStyleClassName; - title = "\"" + node.nodeValue().trimEnd(32) + "\""; - break; - - case Node.COMMENT_NODE: - className = WebInspector.DOMTreeElementPathComponent.DOMCommentIconStyleClassName; - title = ""; - break; - - case Node.DOCUMENT_TYPE_NODE: - className = WebInspector.DOMTreeElementPathComponent.DOMDocumentTypeIconStyleClassName; - title = ""; - break; - - case Node.DOCUMENT_NODE: - className = WebInspector.DOMTreeElementPathComponent.DOMDocumentIconStyleClassName; - title = node.nodeNameInCorrectCase(); - break; - - case Node.CDATA_SECTION_NODE: - className = WebInspector.DOMTreeElementPathComponent.DOMCharacterDataIconStyleClassName; - title = ""; - break; - - case Node.DOCUMENT_FRAGMENT_NODE: - // FIXME: At some point we might want a different icon for this. - // Need icon for DOCUMENT_FRAGMENT_NODE - className = WebInspector.DOMTreeElementPathComponent.DOMDocumentTypeIconStyleClassName; - if (node.isInShadowTree()) - title = WebInspector.UIString("Shadow Content"); - else - title = WebInspector.displayNameForNode(node); - break; - - default: - console.error("Unknown DOM node type: ", node.nodeType()); - className = WebInspector.DOMTreeElementPathComponent.DOMNodeIconStyleClassName; - title = node.nodeNameInCorrectCase(); - } - - WebInspector.HierarchicalPathComponent.call(this, title, className, representedObject || domTreeElement.representedObject); - - this._domTreeElement = domTreeElement; -}; - -WebInspector.DOMTreeElementPathComponent.DOMElementIconStyleClassName = "dom-element-icon"; -WebInspector.DOMTreeElementPathComponent.DOMTextNodeIconStyleClassName = "dom-text-node-icon"; -WebInspector.DOMTreeElementPathComponent.DOMCommentIconStyleClassName = "dom-comment-icon"; -WebInspector.DOMTreeElementPathComponent.DOMDocumentTypeIconStyleClassName = "dom-document-type-icon"; -WebInspector.DOMTreeElementPathComponent.DOMDocumentIconStyleClassName = "dom-document-icon"; -WebInspector.DOMTreeElementPathComponent.DOMCharacterDataIconStyleClassName = "dom-character-data-icon"; -WebInspector.DOMTreeElementPathComponent.DOMNodeIconStyleClassName = "dom-node-icon"; - -WebInspector.DOMTreeElementPathComponent.prototype = { - constructor: WebInspector.DOMTreeElementPathComponent, - - // Public - - get domTreeElement() - { - return this._domTreeElement; - }, - - get previousSibling() - { - if (!this._domTreeElement.previousSibling) - return null; - return new WebInspector.DOMTreeElementPathComponent(this._domTreeElement.previousSibling); - }, - - get nextSibling() - { - if (!this._domTreeElement.nextSibling) - return null; - if (this._domTreeElement.nextSibling.isCloseTag()) - return null; - return new WebInspector.DOMTreeElementPathComponent(this._domTreeElement.nextSibling); - }, - - // Protected - - mouseOver: function() - { - var nodeId = this._domTreeElement.representedObject.id; - WebInspector.domTreeManager.highlightDOMNode(nodeId); - }, - - mouseOut: function() - { - WebInspector.domTreeManager.hideDOMNodeHighlight(); - } -}; - -WebInspector.DOMTreeElementPathComponent.prototype.__proto__ = WebInspector.HierarchicalPathComponent.prototype; diff --git a/Source/WebInspectorUI/UserInterface/DOMTreeManager.js b/Source/WebInspectorUI/UserInterface/DOMTreeManager.js deleted file mode 100644 index 3f3e06db0..000000000 --- a/Source/WebInspectorUI/UserInterface/DOMTreeManager.js +++ /dev/null @@ -1,833 +0,0 @@ -/* - * Copyright (C) 2009, 2010 Google Inc. All rights reserved. - * Copyright (C) 2009 Joseph Pecoraro - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/** - * @extends {WebInspector.Object} - * @constructor - */ -WebInspector.DOMTreeManager = function() { - /** @type {Object|undefined} */ - this._idToDOMNode = {}; - this._document = null; - this._attributeLoadNodeIds = {}; - this._flows = new Map; - this._contentNodesToFlowsMap = new Map; -} - -WebInspector.Object.addConstructorFunctions(WebInspector.DOMTreeManager); - -WebInspector.DOMTreeManager.Event = { - AttributeModified: "dom-tree-manager-attribute-modified", - AttributeRemoved: "dom-tree-manager-attribute-removed", - CharacterDataModified: "dom-tree-manager-character-data-modified", - NodeInserted: "dom-tree-manager-node-inserted", - NodeRemoved: "dom-tree-manager-node-removed", - DocumentUpdated: "dom-tree-manager-document-updated", - ChildNodeCountUpdated: "dom-tree-manager-child-node-count-updated", - DOMNodeWasInspected: "dom-tree-manager-dom-node-was-inspected", - InspectModeStateChanged: "dom-tree-manager-inspect-mode-state-changed", - ContentFlowListWasUpdated: "dom-tree-manager-content-flow-list-was-updated", - ContentFlowWasAdded: "dom-tree-manager-content-flow-was-added", - ContentFlowWasRemoved: "dom-tree-manager-content-flow-was-removed", - RegionLayoutUpdated: "dom-tree-manager-region-layout-updated", - RegionOversetChanged: "dom-tree-manager-region-overset-changed" -}; - -WebInspector.DOMTreeManager._flowPayloadHashKey = function(flowPayload) -{ - // Use the flow node id, to avoid collisions when we change main document id. - return flowPayload.documentNodeId + ":" + flowPayload.name; -}; - -WebInspector.DOMTreeManager.prototype = { - /** - * @param {function(WebInspector.DOMDocument)=} callback - */ - requestDocument: function(callback) - { - if (this._document) { - if (callback) - callback(this._document); - return; - } - - if (this._pendingDocumentRequestCallbacks) { - this._pendingDocumentRequestCallbacks.push(callback); - return; - } - - this._pendingDocumentRequestCallbacks = [callback]; - - /** - * @this {WebInspector.DOMTreeManager} - * @param {?Protocol.Error} error - * @param {DOMAgent.Node} root - */ - 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; - } - - DOMAgent.getDocument(onDocumentAvailable.bind(this)); - }, - - /** - * @param {RuntimeAgent.RemoteObjectId} objectId - * @param {function()=} callback - */ - pushNodeToFrontend: function(objectId, callback) - { - this._dispatchWhenDocumentAvailable(DOMAgent.requestNode.bind(DOMAgent, objectId), callback); - }, - - /** - * @param {string} path - * @param {function(?WebInspector.DOMNode)=} callback - */ - pushNodeByPathToFrontend: function(path, callback) - { - var callbackCast = /** @type {function(*)} */ callback; - this._dispatchWhenDocumentAvailable(DOMAgent.pushNodeByPathToFrontend.bind(DOMAgent, path), callbackCast); - }, - - /** - * @param {function(*)=} callback - * @return {function(?Protocol.Error,*=)|undefined} - */ - _wrapClientCallback: function(callback) - { - if (!callback) - return; - return function(error, result) { - if (error) - console.error("Error during DOMAgent operation: " + error); - callback(error ? null : result); - }; - }, - - /** - * @param {function(function()=)} func - * @param {function(*)=} callback - */ - _dispatchWhenDocumentAvailable: function(func, callback) - { - var callbackWrapper = /** @type {function(?Protocol.Error, *=)} */ this._wrapClientCallback(callback); - - function onDocumentAvailable() - { - if (this._document) - func(callbackWrapper); - else { - if (callbackWrapper) - callbackWrapper("No document"); - } - } - this.requestDocument(onDocumentAvailable.bind(this)); - }, - - /** - * @param {DOMAgent.NodeId} nodeId - * @param {string} name - * @param {string} value - */ - _attributeModified: function(nodeId, name, value) - { - var node = this._idToDOMNode[nodeId]; - if (!node) - return; - node._setAttribute(name, value); - this.dispatchEventToListeners(WebInspector.DOMTreeManager.Event.AttributeModified, { node: node, name: name }); - node.dispatchEventToListeners(WebInspector.DOMNode.Event.AttributeModified, {name: name}); - }, - - /** - * @param {DOMAgent.NodeId} nodeId - * @param {string} name - */ - _attributeRemoved: function(nodeId, name) - { - var node = this._idToDOMNode[nodeId]; - if (!node) - return; - node._removeAttribute(name); - this.dispatchEventToListeners(WebInspector.DOMTreeManager.Event.AttributeRemoved, { node: node, name: name }); - node.dispatchEventToListeners(WebInspector.DOMNode.Event.AttributeRemoved, {name: name}); - }, - - /** - * @param {Array.} nodeIds - */ - _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), 0); - }, - - _loadNodeAttributes: function() - { - /** - * @this {WebInspector.DOMTreeManager} - * @param {DOMAgent.NodeId} nodeId - * @param {?Protocol.Error} error - * @param {Array.} attributes - */ - function callback(nodeId, error, attributes) - { - if (error) { - console.error("Error during DOMAgent operation: " + error); - return; - } - var node = this._idToDOMNode[nodeId]; - if (node) { - node._setAttributesPayload(attributes); - this.dispatchEventToListeners(WebInspector.DOMTreeManager.Event.AttributeModified, { node: node, name: "style" }); - node.dispatchEventToListeners(WebInspector.DOMNode.Event.AttributeModified, {name: "style"}); - } - } - - delete this._loadNodeAttributesTimeout; - - for (var nodeId in this._attributeLoadNodeIds) { - var nodeIdAsNumber = parseInt(nodeId, 10); - DOMAgent.getAttributes(nodeIdAsNumber, callback.bind(this, nodeIdAsNumber)); - } - this._attributeLoadNodeIds = {}; - }, - - /** - * @param {DOMAgent.NodeId} nodeId - * @param {string} newValue - */ - _characterDataModified: function(nodeId, newValue) - { - var node = this._idToDOMNode[nodeId]; - node._nodeValue = newValue; - this.dispatchEventToListeners(WebInspector.DOMTreeManager.Event.CharacterDataModified, {node: node}); - }, - - /** - * @param {DOMAgent.NodeId} nodeId - * @return {WebInspector.DOMNode|undefined} - */ - nodeForId: function(nodeId) - { - return this._idToDOMNode[nodeId]; - }, - - _documentUpdated: function() - { - this._setDocument(null); - }, - - /** - * @param {DOMAgent.Node} payload - */ - _setDocument: function(payload) - { - this._idToDOMNode = {}; - if (payload && "nodeId" in payload) - this._document = new WebInspector.DOMNode(this, null, false, payload); - else - this._document = null; - this.dispatchEventToListeners(WebInspector.DOMTreeManager.Event.DocumentUpdated, this._document); - }, - - /** - * @param {DOMAgent.Node} payload - */ - _setDetachedRoot: function(payload) - { - new WebInspector.DOMNode(this, null, false, payload); - }, - - /** - * @param {DOMAgent.NodeId} parentId - * @param {Array.} payloads - */ - _setChildNodes: function(parentId, payloads) - { - if (!parentId && payloads.length) { - this._setDetachedRoot(payloads[0]); - return; - } - - var parent = this._idToDOMNode[parentId]; - parent._setChildrenPayload(payloads); - }, - - /** - * @param {DOMAgent.NodeId} nodeId - * @param {number} newValue - */ - _childNodeCountUpdated: function(nodeId, newValue) - { - var node = this._idToDOMNode[nodeId]; - node.childNodeCount = newValue; - this.dispatchEventToListeners(WebInspector.DOMTreeManager.Event.ChildNodeCountUpdated, node); - }, - - /** - * @param {DOMAgent.NodeId} parentId - * @param {DOMAgent.NodeId} prevId - * @param {DOMAgent.Node} payload - */ - _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.DOMTreeManager.Event.NodeInserted, {node: node, parent: parent}); - }, - - /** - * @param {DOMAgent.NodeId} parentId - * @param {DOMAgent.NodeId} nodeId - */ - _childNodeRemoved: function(parentId, nodeId) - { - var parent = this._idToDOMNode[parentId]; - var node = this._idToDOMNode[nodeId]; - parent._removeChild(node); - this._unbind(node); - this.dispatchEventToListeners(WebInspector.DOMTreeManager.Event.NodeRemoved, {node:node, parent: parent}); - }, - - /** - * @param {DOMAgent.Node} node - */ - _unbind: function(node) - { - this._removeContentNodeFromFlowIfNeeded(node); - - delete this._idToDOMNode[node.id]; - for (var i = 0; node.children && i < node.children.length; ++i) - this._unbind(node.children[i]); - }, - - /** - * @param {number} nodeId - */ - inspectElement: function(nodeId) - { - var node = this._idToDOMNode[nodeId]; - if (node) - this.dispatchEventToListeners(WebInspector.DOMTreeManager.Event.DOMNodeWasInspected, {node: node}); - - this._inspectModeEnabled = false; - this.dispatchEventToListeners(WebInspector.DOMTreeManager.Event.InspectModeStateChanged); - }, - - inspectNodeObject: function(remoteObject) - { - function nodeAvailable(nodeId) - { - remoteObject.release(); - - console.assert(nodeId); - if (!nodeId) - return; - - this.inspectElement(nodeId); - } - - remoteObject.pushNodeToFrontend(nodeAvailable.bind(this)); - }, - - /** - * @param {string} query - * @param {function(number)} searchCallback - */ - performSearch: function(query, searchCallback) - { - this.cancelSearch(); - - /** - * @param {?Protocol.Error} error - * @param {string} searchId - * @param {number} resultsCount - */ - function callback(error, searchId, resultsCount) - { - this._searchId = searchId; - searchCallback(resultsCount); - } - DOMAgent.performSearch(query, callback.bind(this)); - }, - - /** - * @param {number} index - * @param {?function(DOMAgent.Node)} callback - */ - searchResult: function(index, callback) - { - if (this._searchId) { - /** - * @param {?Protocol.Error} error - * @param {Array.} nodeIds - */ - function mycallback(error, nodeIds) - { - if (error) { - console.error(error); - callback(null); - return; - } - if (nodeIds.length != 1) - return; - - callback(this._idToDOMNode[nodeIds[0]]); - } - DOMAgent.getSearchResults(this._searchId, index, index + 1, mycallback.bind(this)); - } else - callback(null); - }, - - cancelSearch: function() - { - if (this._searchId) { - DOMAgent.discardSearchResults(this._searchId); - delete this._searchId; - } - }, - - /** - * @param {DOMAgent.NodeId} nodeId - * @param {string} selectors - * @param {function(?DOMAgent.NodeId)=} callback - */ - querySelector: function(nodeId, selectors, callback) - { - var callbackCast = /** @type {function(*)|undefined} */callback; - DOMAgent.querySelector(nodeId, selectors, this._wrapClientCallback(callbackCast)); - }, - - /** - * @param {DOMAgent.NodeId} nodeId - * @param {string} selectors - * @param {function(?Array.)=} callback - */ - querySelectorAll: function(nodeId, selectors, callback) - { - var callbackCast = /** @type {function(*)|undefined} */callback; - DOMAgent.querySelectorAll(nodeId, selectors, this._wrapClientCallback(callbackCast)); - }, - - /** - * @param {?number} nodeId - * @param {string=} mode - */ - highlightDOMNode: function(nodeId, mode) - { - if (this._hideDOMNodeHighlightTimeout) { - clearTimeout(this._hideDOMNodeHighlightTimeout); - delete this._hideDOMNodeHighlightTimeout; - } - - this._highlightedDOMNodeId = nodeId; - if (nodeId) - DOMAgent.highlightNode.invoke({nodeId: nodeId, highlightConfig: this._buildHighlightConfig(mode)}); - else - DOMAgent.hideHighlight(); - }, - - highlightRect: function(rect, usePageCoordinates) - { - DOMAgent.highlightRect.invoke({ - x: rect.x, - y: rect.y, - width: rect.width, - height: rect.height, - color: {r: 111, g: 168, b: 220, a: 0.66}, - outlineColor: {r: 255, g: 229, b: 153, a: 0.66}, - usePageCoordinates: usePageCoordinates - }); - }, - - hideDOMNodeHighlight: function() - { - this.highlightDOMNode(0); - }, - - /** - * @param {?DOMAgent.NodeId} nodeId - */ - highlightDOMNodeForTwoSeconds: function(nodeId) - { - this.highlightDOMNode(nodeId); - this._hideDOMNodeHighlightTimeout = setTimeout(this.hideDOMNodeHighlight.bind(this), 2000); - }, - - get inspectModeEnabled() - { - return this._inspectModeEnabled; - }, - - set inspectModeEnabled(enabled) - { - function callback(error) - { - this._inspectModeEnabled = error ? false : enabled; - this.dispatchEventToListeners(WebInspector.DOMTreeManager.Event.InspectModeStateChanged); - } - - DOMAgent.setInspectModeEnabled(enabled, this._buildHighlightConfig(), callback.bind(this)); - }, - - /** - * @param {string=} mode - */ - _buildHighlightConfig: function(mode) - { - mode = mode || "all"; - var highlightConfig = { showInfo: mode === "all" }; - if (mode === "all" || mode === "content") - highlightConfig.contentColor = {r: 111, g: 168, b: 220, a: 0.66}; - - if (mode === "all" || mode === "padding") - highlightConfig.paddingColor = {r: 147, g: 196, b: 125, a: 0.66}; - - if (mode === "all" || mode === "border") - highlightConfig.borderColor = {r: 255, g: 229, b: 153, a: 0.66}; - - if (mode === "all" || mode === "margin") - highlightConfig.marginColor = {r: 246, g: 178, b: 107, a: 0.66}; - - return highlightConfig; - }, - - _createContentFlowFromPayload: function(flowPayload) - { - // FIXME: Collect the regions from the payload. - var flow = new WebInspector.ContentFlow(flowPayload.documentNodeId, flowPayload.name, flowPayload.overset, flowPayload.content.map(this.nodeForId.bind(this))); - - for (var contentNode of flow.contentNodes) { - console.assert(!this._contentNodesToFlowsMap.has(contentNode.id)); - this._contentNodesToFlowsMap.set(contentNode.id, flow); - } - - return flow; - }, - - _updateContentFlowFromPayload: function(contentFlow, flowPayload) - { - console.assert(contentFlow.contentNodes.length === flowPayload.content.length); - for (var i = 0; i < contentFlow.contentNodes.length; ++i) - console.assert(contentFlow.contentNodes[i].id === flowPayload.content[i]); - - // FIXME: Collect the regions from the payload. - contentFlow.overset = flowPayload.overset; - }, - - getNamedFlowCollection: function(documentNodeIdentifier) - { - function onNamedFlowCollectionAvailable(error, flows) - { - if (error) { - console.error("Error while getting the named flows for document " + documentNodeIdentifier + ": " + error); - return; - } - this._contentNodesToFlowsMap.clear(); - var contentFlows = []; - for (var i = 0; i < flows.length; ++i) { - var flowPayload = flows[i]; - var flowKey = WebInspector.DOMTreeManager._flowPayloadHashKey(flowPayload); - var contentFlow = this._flows.get(flowKey); - if (contentFlow) - this._updateContentFlowFromPayload(contentFlow, flowPayload); - else { - contentFlow = this._createContentFlowFromPayload(flowPayload); - this._flows.set(flowKey, contentFlow); - } - contentFlows.push(contentFlow); - } - this.dispatchEventToListeners(WebInspector.DOMTreeManager.Event.ContentFlowListWasUpdated, {documentNodeIdentifier: documentNodeIdentifier, flows: contentFlows}); - } - CSSAgent.getNamedFlowCollection(documentNodeIdentifier, onNamedFlowCollectionAvailable.bind(this)); - }, - - namedFlowCreated: function(flowPayload) - { - var flowKey = WebInspector.DOMTreeManager._flowPayloadHashKey(flowPayload); - console.assert(!this._flows.has(flowKey)); - var contentFlow = this._createContentFlowFromPayload(flowPayload); - this._flows.set(flowKey, contentFlow); - this.dispatchEventToListeners(WebInspector.DOMTreeManager.Event.ContentFlowWasAdded, {flow: contentFlow}); - }, - - namedFlowRemoved: function(documentNodeIdentifier, flowName) - { - var flowKey = WebInspector.DOMTreeManager._flowPayloadHashKey({documentNodeId: documentNodeIdentifier, name: flowName}); - var contentFlow = this._flows.get(flowKey); - console.assert(contentFlow); - this._flows.delete(flowKey); - - // Remove any back links to this flow from the content nodes. - for (var contentNode of contentFlow.contentNodes) - this._contentNodesToFlowsMap.delete(contentNode.id); - - this.dispatchEventToListeners(WebInspector.DOMTreeManager.Event.ContentFlowWasRemoved, {flow: contentFlow}); - }, - - _sendNamedFlowUpdateEvents: function(flowPayload) - { - var flowKey = WebInspector.DOMTreeManager._flowPayloadHashKey(flowPayload); - console.assert(this._flows.has(flowKey)); - this._updateContentFlowFromPayload(this._flows.get(flowKey), flowPayload); - }, - - regionLayoutUpdated: function(flowPayload) - { - this._sendNamedFlowUpdateEvents(flowPayload); - }, - - regionOversetChanged: function(flowPayload) - { - this._sendNamedFlowUpdateEvents(flowPayload); - }, - - registeredNamedFlowContentElement: function(documentNodeIdentifier, flowName, contentNodeId, nextContentElementNodeId) - { - var flowKey = WebInspector.DOMTreeManager._flowPayloadHashKey({documentNodeId: documentNodeIdentifier, name: flowName}); - console.assert(this._flows.has(flowKey)); - console.assert(!this._contentNodesToFlowsMap.has(contentNodeId)); - - var flow = this._flows.get(flowKey); - var contentNode = this.nodeForId(contentNodeId); - - this._contentNodesToFlowsMap.set(contentNode.id, flow); - - if (nextContentElementNodeId) - flow.insertContentNodeBefore(contentNode, this.nodeForId(nextContentElementNodeId)); - else - flow.appendContentNode(contentNode); - }, - - _removeContentNodeFromFlowIfNeeded: function(node) - { - if (!this._contentNodesToFlowsMap.has(node.id)) - return; - var flow = this._contentNodesToFlowsMap.get(node.id); - this._contentNodesToFlowsMap.delete(node.id); - flow.removeContentNode(node); - }, - - unregisteredNamedFlowContentElement: function(documentNodeIdentifier, flowName, contentNodeId) - { - console.assert(this._contentNodesToFlowsMap.has(contentNodeId)); - - var flow = this._contentNodesToFlowsMap.get(contentNodeId); - console.assert(flow.id === WebInspector.DOMTreeManager._flowPayloadHashKey({documentNodeId: documentNodeIdentifier, name: flowName})); - - this._contentNodesToFlowsMap.delete(contentNodeId); - flow.removeContentNode(this.nodeForId(contentNodeId)); - }, - - _coerceRemoteArrayOfDOMNodes: function(objectId, callback) - { - var length, nodes, received = 0, lastError = null, domTreeManager = this; - - function nodeRequested(index, error, nodeId) - { - if (error) - lastError = error; - else - nodes[index] = domTreeManager._idToDOMNode[nodeId]; - if (++received === length) - callback(lastError, nodes); - } - - WebInspector.runtimeManager.getPropertiesForRemoteObject(objectId, function(error, properties) { - if (error) { - callback(error); - return; - } - - var lengthProperty = properties.get("length"); - if (!lengthProperty || lengthProperty.value.type !== "number") { - callback(null); - return; - } - - length = lengthProperty.value.value; - if (!length) { - callback(null, []); - return; - } - - nodes = new Array(length); - for (var i = 0; i < length; ++i) { - var nodeProperty = properties.get(String(i)); - console.assert(nodeProperty.value.type === "object"); - DOMAgent.requestNode(nodeProperty.value.objectId, nodeRequested.bind(null, i)); - } - }); - }, - - getNodeContentFlowInfo: function(domNode, resultReadyCallback) - { - DOMAgent.resolveNode(domNode.id, domNodeResolved.bind(this)); - - function domNodeResolved(error, remoteObject) - { - if (error) { - resultReadyCallback(error); - return; - } - // Serialize "backendFunction" and execute it in the context of the page - // passing the DOMNode as the "this" reference. - var evalParameters = { - objectId: remoteObject.objectId, - functionDeclaration: backendFunction.toString(), - doNotPauseOnExceptionsAndMuteConsole: true, - returnByValue: false, - generatePreview: false - }; - RuntimeAgent.callFunctionOn.invoke(evalParameters, regionNodesAvailable.bind(this)); - } - - function regionNodesAvailable(error, remoteObject, wasThrown) - { - if (error) { - resultReadyCallback(error); - return; - } - - if (wasThrown) { - // We should never get here, but having the error is useful for debugging. - console.error("Error while executing backend function:", JSON.stringify(remoteObject)); - resultReadyCallback(null); - return; - } - - // The backend function can never return null. - console.assert(remoteObject.type === "object"); - console.assert(remoteObject.objectId); - WebInspector.runtimeManager.getPropertiesForRemoteObject(remoteObject.objectId, remoteObjectPropertiesAvailable.bind(this)); - } - - function remoteObjectPropertiesAvailable(error, properties) { - if (error) { - resultReadyCallback(error); - return; - } - - var result = { - regionFlow: null, - contentFlow: null, - regions: null - }; - - var regionFlowNameProperty = properties.get("regionFlowName"); - if (regionFlowNameProperty && regionFlowNameProperty.value && regionFlowNameProperty.value.value) { - console.assert(regionFlowNameProperty.value.type === "string"); - var regionFlowKey = WebInspector.DOMTreeManager._flowPayloadHashKey({documentNodeId: domNode.ownerDocument.id, name: regionFlowNameProperty.value.value}); - result.regionFlow = this._flows.get(regionFlowKey); - } - - var contentFlowNameProperty = properties.get("contentFlowName"); - if (contentFlowNameProperty && contentFlowNameProperty.value && contentFlowNameProperty.value.value) { - console.assert(contentFlowNameProperty.value.type === "string"); - var contentFlowKey = WebInspector.DOMTreeManager._flowPayloadHashKey({documentNodeId: domNode.ownerDocument.id, name: contentFlowNameProperty.value.value}); - result.contentFlow = this._flows.get(contentFlowKey); - } - - var regionsProperty = properties.get("regions"); - if (!regionsProperty || !regionsProperty.value.objectId) { - // The list of regions is null. - resultReadyCallback(null, result); - return; - } - - console.assert(regionsProperty.value.type === "object"); - console.assert(regionsProperty.value.subtype === "array"); - this._coerceRemoteArrayOfDOMNodes(regionsProperty.value.objectId, function(error, nodes) { - result.regions = nodes; - resultReadyCallback(error, result); - }); - } - - // Note that "backendFunction" is serialized and executed in the context of the page. - function backendFunction() - { - function getComputedProperty(node, propertyName) - { - if (!node.ownerDocument || !node.ownerDocument.defaultView) - return null; - var computedStyle = node.ownerDocument.defaultView.getComputedStyle(node); - return computedStyle ? computedStyle[propertyName] : null; - } - - function getContentFlowName(node) - { - for (; node; node = node.parentNode) { - var flowName = getComputedProperty(node, "webkitFlowInto"); - if (flowName && flowName !== "none") - return flowName; - } - return null; - } - - var node = this; - - // Even detached nodes have an ownerDocument. - console.assert(node.ownerDocument); - - var result = { - regionFlowName: getComputedProperty(node, "webkitFlowFrom"), - contentFlowName: getContentFlowName(node), - regions: null - }; - - if (result.contentFlowName) { - var flowThread = node.ownerDocument.webkitGetNamedFlows().namedItem(result.contentFlowName); - if (flowThread) - result.regions = flowThread.getRegionsByContent(node); - } - - return result; - } - } -} - -WebInspector.DOMTreeManager.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/DOMTreeOutline.css b/Source/WebInspectorUI/UserInterface/DOMTreeOutline.css deleted file mode 100644 index 3194b59dc..000000000 --- a/Source/WebInspectorUI/UserInterface/DOMTreeOutline.css +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.dom-tree-outline { - position: relative; - - padding: 0 6px; - margin: 0; - min-width: 100%; - - outline: none; - - list-style-type: none; - - /* Needed to make the negative z-index on .selection works. Otherwise the background-color from .syntax-highlighted hides the selection. */ - background-color: transparent !important; - color: black; -} - -.dom-tree-outline li.hovered:not(.selected) .selection { - display: block; - left: 3px; - right: 3px; - - background-color: rgba(56, 121, 217, 0.1); - border-radius: 5px; -} - -.dom-tree-outline li .selection { - display: none; - position: absolute; - left: 0; - right: 0; - height: 15px; - z-index: -1; -} - -.dom-tree-outline li.selected .selection { - display: block; - background-color: rgb(212, 212, 212); -} - -.dom-tree-outline li.elements-drag-over .selection { - display: block; - margin-top: -2px; - border-top: 2px solid rgb(56, 121, 217); -} - -.dom-tree-outline:focus li.selected .selection { - background-color: rgb(56, 121, 217); -} - -.dom-tree-outline ol { - list-style-type: none; - padding-left: 14px; - margin: 0; -} - -.dom-tree-outline ol.children { - display: none; -} - -.dom-tree-outline ol.children.expanded { - display: block; -} - -.dom-tree-outline li { - padding: 0 0 0 12px; - word-wrap: break-word; -} - -.dom-tree-outline:focus li.selected { - color: white; -} - -.dom-tree-outline:focus li.selected * { - color: inherit; -} - -.dom-tree-outline li.parent { - margin-left: -10px; -} - -.dom-tree-outline li .html-tag.close { - margin-left: -14px; -} - -.dom-tree-outline li.parent::before { - float: left; - - content: ""; - - background-image: -webkit-canvas(disclosure-triangle-tiny-closed-normal); - background-size: 8px 8px; - background-repeat: no-repeat; - - width: 8px; - height: 8px; - - margin-top: 2px; - padding-right: 2px; -} - -.dom-tree-outline:focus li.parent.selected::before { - background-image: -webkit-canvas(disclosure-triangle-tiny-closed-selected); -} - -.dom-tree-outline li.parent.expanded::before { - background-image: -webkit-canvas(disclosure-triangle-tiny-open-normal); -} - -.dom-tree-outline:focus li.parent.expanded.selected::before { - background-image: -webkit-canvas(disclosure-triangle-tiny-open-selected); -} - -.dom-tree-outline .add-attribute { - margin-left: 1px; - margin-right: 1px; - white-space: nowrap; -} - -.dom-tree-outline .html-text-node.large { - display: inline-block; - min-width: 100%; - white-space: pre-wrap; -} diff --git a/Source/WebInspectorUI/UserInterface/DOMTreeOutline.js b/Source/WebInspectorUI/UserInterface/DOMTreeOutline.js deleted file mode 100644 index 17fa5f3cc..000000000 --- a/Source/WebInspectorUI/UserInterface/DOMTreeOutline.js +++ /dev/null @@ -1,588 +0,0 @@ -/* - * Copyright (C) 2007, 2008, 2013 Apple Inc. All rights reserved. - * Copyright (C) 2008 Matt Lilek - * Copyright (C) 2009 Joseph Pecoraro - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/** - * @constructor - * @extends {TreeOutline} - * @param {boolean=} omitRootDOMNode - * @param {boolean=} selectEnabled - */ -WebInspector.DOMTreeOutline = function(omitRootDOMNode, selectEnabled, showInElementsPanelEnabled) -{ - this.element = document.createElement("ol"); - this.element.addEventListener("mousedown", this._onmousedown.bind(this), false); - this.element.addEventListener("mousemove", this._onmousemove.bind(this), false); - this.element.addEventListener("mouseout", this._onmouseout.bind(this), false); - this.element.addEventListener("dragstart", this._ondragstart.bind(this), false); - this.element.addEventListener("dragover", this._ondragover.bind(this), false); - this.element.addEventListener("dragleave", this._ondragleave.bind(this), false); - this.element.addEventListener("drop", this._ondrop.bind(this), false); - this.element.addEventListener("dragend", this._ondragend.bind(this), false); - - this.element.classList.add(WebInspector.DOMTreeOutline.StyleClassName); - this.element.classList.add(WebInspector.SyntaxHighlightedStyleClassName); - - TreeOutline.call(this, this.element); - - this._includeRootDOMNode = !omitRootDOMNode; - this._selectEnabled = selectEnabled; - this._showInElementsPanelEnabled = showInElementsPanelEnabled; - this._rootDOMNode = null; - this._selectedDOMNode = null; - this._eventSupport = new WebInspector.Object(); - this._editing = false; - - this._visible = false; - - this.element.addEventListener("contextmenu", this._contextMenuEventFired.bind(this), true); - - this._hideElementKeyboardShortcut = new WebInspector.KeyboardShortcut(null, "H", this._hideElement.bind(this), this.element); - this._hideElementKeyboardShortcut.implicitlyPreventsDefault = false; - - WebInspector.showShadowDOMSetting.addEventListener(WebInspector.Setting.Event.Changed, this._showShadowDOMSettingChanged, this); -} - -WebInspector.Object.addConstructorFunctions(WebInspector.DOMTreeOutline); - -WebInspector.DOMTreeOutline.StyleClassName = "dom-tree-outline"; - -WebInspector.DOMTreeOutline.Event = { - SelectedNodeChanged: "dom-tree-outline-selected-node-changed" -} - -WebInspector.DOMTreeOutline.prototype = { - constructor: WebInspector.DOMTreeOutline, - - wireToDomAgent: function() - { - this._elementsTreeUpdater = new WebInspector.DOMTreeUpdater(this); - }, - - close: function() - { - if (this._elementsTreeUpdater) { - this._elementsTreeUpdater.close(); - this._elementsTreeUpdater = null; - } - }, - - setVisible: function(visible, omitFocus) - { - this._visible = visible; - if (!this._visible) - return; - - this._updateModifiedNodes(); - if (this._selectedDOMNode) - this._revealAndSelectNode(this._selectedDOMNode, omitFocus); - }, - - addEventListener: function(eventType, listener, thisObject) - { - this._eventSupport.addEventListener(eventType, listener, thisObject); - }, - - removeEventListener: function(eventType, listener, thisObject) - { - this._eventSupport.removeEventListener(eventType, listener, thisObject); - }, - - get rootDOMNode() - { - return this._rootDOMNode; - }, - - set rootDOMNode(x) - { - if (this._rootDOMNode === x) - return; - - this._rootDOMNode = x; - - this._isXMLMimeType = x && x.isXMLNode(); - - this.update(); - }, - - get isXMLMimeType() - { - return this._isXMLMimeType; - }, - - selectedDOMNode: function() - { - return this._selectedDOMNode; - }, - - selectDOMNode: function(node, focus) - { - if (this._selectedDOMNode === node) { - this._revealAndSelectNode(node, !focus); - return; - } - - this._selectedDOMNode = node; - this._revealAndSelectNode(node, !focus); - - // The _revealAndSelectNode() method might find a different element if there is inlined text, - // and the select() call would change the selectedDOMNode and reenter this setter. So to - // avoid calling _selectedNodeChanged() twice, first check if _selectedDOMNode is the same - // node as the one passed in. - // Note that _revealAndSelectNode will not do anything for a null node. - if (!node || this._selectedDOMNode === node) - this._selectedNodeChanged(); - }, - - get editing() - { - return this._editing; - }, - - update: function() - { - var selectedNode = this.selectedTreeElement ? this.selectedTreeElement.representedObject : null; - - this.removeChildren(); - - if (!this.rootDOMNode) - return; - - var treeElement; - if (this._includeRootDOMNode) { - treeElement = new WebInspector.DOMTreeElement(this.rootDOMNode); - treeElement.selectable = this._selectEnabled; - this.appendChild(treeElement); - } else { - // FIXME: this could use findTreeElement to reuse a tree element if it already exists - var node = this.rootDOMNode.firstChild; - while (node) { - treeElement = new WebInspector.DOMTreeElement(node); - treeElement.selectable = this._selectEnabled; - this.appendChild(treeElement); - node = node.nextSibling; - } - } - - if (selectedNode) - this._revealAndSelectNode(selectedNode, true); - }, - - updateSelection: function() - { - if (!this.selectedTreeElement) - return; - var element = this.treeOutline.selectedTreeElement; - element.updateSelection(); - }, - - _selectedNodeChanged: function() - { - this._eventSupport.dispatchEventToListeners(WebInspector.DOMTreeOutline.Event.SelectedNodeChanged); - }, - - findTreeElement: function(node) - { - function isAncestorNode(ancestor, node) - { - return ancestor.isAncestor(node); - } - - function parentNode(node) - { - return node.parentNode; - } - - var treeElement = TreeOutline.prototype.findTreeElement.call(this, node, isAncestorNode, parentNode); - if (!treeElement && node.nodeType() === Node.TEXT_NODE) { - // The text node might have been inlined if it was short, so try to find the parent element. - treeElement = TreeOutline.prototype.findTreeElement.call(this, node.parentNode, isAncestorNode, parentNode); - } - - return treeElement; - }, - - createTreeElementFor: function(node) - { - var treeElement = this.findTreeElement(node); - if (treeElement) - return treeElement; - if (!node.parentNode) - return null; - - treeElement = this.createTreeElementFor(node.parentNode); - if (treeElement && treeElement.showChild(node.index)) - return treeElement.children[node.index]; - - return null; - }, - - set suppressRevealAndSelect(x) - { - if (this._suppressRevealAndSelect === x) - return; - this._suppressRevealAndSelect = x; - }, - - _revealAndSelectNode: function(node, omitFocus) - { - if (!node || this._suppressRevealAndSelect) - return; - - var treeElement = this.createTreeElementFor(node); - if (!treeElement) - return; - - treeElement.revealAndSelect(omitFocus); - }, - - _treeElementFromEvent: function(event) - { - var scrollContainer = this.element.parentElement; - - // We choose this X coordinate based on the knowledge that our list - // items extend at least to the right edge of the outer
    container. - // In the no-word-wrap mode the outer
      may be wider than the tree container - // (and partially hidden), in which case we are left to use only its right boundary. - var x = scrollContainer.totalOffsetLeft + scrollContainer.offsetWidth - 36; - - var y = event.pageY; - - // Our list items have 1-pixel cracks between them vertically. We avoid - // the cracks by checking slightly above and slightly below the mouse - // and seeing if we hit the same element each time. - var elementUnderMouse = this.treeElementFromPoint(x, y); - var elementAboveMouse = this.treeElementFromPoint(x, y - 2); - var element; - if (elementUnderMouse === elementAboveMouse) - element = elementUnderMouse; - else - element = this.treeElementFromPoint(x, y + 2); - - return element; - }, - - _onmousedown: function(event) - { - var element = this._treeElementFromEvent(event); - if (!element || element.isEventWithinDisclosureTriangle(event)) { - event.preventDefault(); - return; - } - - element.select(); - }, - - _onmousemove: function(event) - { - var element = this._treeElementFromEvent(event); - if (element && this._previousHoveredElement === element) - return; - - if (this._previousHoveredElement) { - this._previousHoveredElement.hovered = false; - delete this._previousHoveredElement; - } - - if (element) { - element.hovered = true; - this._previousHoveredElement = element; - - // Lazily compute tag-specific tooltips. - if (element.representedObject && !element.tooltip) - element._createTooltipForNode(); - } - - WebInspector.domTreeManager.highlightDOMNode(element ? element.representedObject.id : 0); - }, - - _onmouseout: function(event) - { - var nodeUnderMouse = document.elementFromPoint(event.pageX, event.pageY); - if (nodeUnderMouse && nodeUnderMouse.isDescendant(this.element)) - return; - - if (this._previousHoveredElement) { - this._previousHoveredElement.hovered = false; - delete this._previousHoveredElement; - } - - WebInspector.domTreeManager.hideDOMNodeHighlight(); - }, - - _ondragstart: function(event) - { - var treeElement = this._treeElementFromEvent(event); - if (!treeElement) - return false; - - if (!this._isValidDragSourceOrTarget(treeElement)) - return false; - - if (treeElement.representedObject.nodeName() === "BODY" || treeElement.representedObject.nodeName() === "HEAD") - return false; - - event.dataTransfer.setData("text/plain", treeElement.listItemElement.textContent); - event.dataTransfer.effectAllowed = "copyMove"; - this._nodeBeingDragged = treeElement.representedObject; - - WebInspector.domTreeManager.hideDOMNodeHighlight(); - - return true; - }, - - _ondragover: function(event) - { - if (!this._nodeBeingDragged) - return false; - - var treeElement = this._treeElementFromEvent(event); - if (!this._isValidDragSourceOrTarget(treeElement)) - return false; - - var node = treeElement.representedObject; - while (node) { - if (node === this._nodeBeingDragged) - return false; - node = node.parentNode; - } - - treeElement.updateSelection(); - treeElement.listItemElement.classList.add("elements-drag-over"); - this._dragOverTreeElement = treeElement; - event.preventDefault(); - event.dataTransfer.dropEffect = 'move'; - return false; - }, - - _ondragleave: function(event) - { - this._clearDragOverTreeElementMarker(); - event.preventDefault(); - return false; - }, - - _isValidDragSourceOrTarget: function(treeElement) - { - if (!treeElement) - return false; - - var node = treeElement.representedObject; - if (!(node instanceof WebInspector.DOMNode)) - return false; - - if (!node.parentNode || node.parentNode.nodeType() !== Node.ELEMENT_NODE) - return false; - - return true; - }, - - _ondrop: function(event) - { - event.preventDefault(); - var treeElement = this._treeElementFromEvent(event); - if (this._nodeBeingDragged && treeElement) { - var parentNode; - var anchorNode; - - if (treeElement._elementCloseTag) { - // Drop onto closing tag -> insert as last child. - parentNode = treeElement.representedObject; - } else { - var dragTargetNode = treeElement.representedObject; - parentNode = dragTargetNode.parentNode; - anchorNode = dragTargetNode; - } - - function callback(error, newNodeId) - { - if (error) - return; - - this._updateModifiedNodes(); - var newNode = WebInspector.domTreeManager.nodeForId(newNodeId); - if (newNode) - this.selectDOMNode(newNode, true); - } - this._nodeBeingDragged.moveTo(parentNode, anchorNode, callback.bind(this)); - } - - delete this._nodeBeingDragged; - }, - - _ondragend: function(event) - { - event.preventDefault(); - this._clearDragOverTreeElementMarker(); - delete this._nodeBeingDragged; - }, - - _clearDragOverTreeElementMarker: function() - { - if (this._dragOverTreeElement) { - this._dragOverTreeElement.updateSelection(); - this._dragOverTreeElement.listItemElement.classList.remove("elements-drag-over"); - delete this._dragOverTreeElement; - } - }, - - _contextMenuEventFired: function(event) - { - var treeElement = this._treeElementFromEvent(event); - if (!treeElement) - return; - - var contextMenu = new WebInspector.ContextMenu(event); - this.populateContextMenu(contextMenu, event); - contextMenu.show(); - }, - - populateContextMenu: function(contextMenu, event) - { - var treeElement = this._treeElementFromEvent(event); - if (!treeElement) - return false; - - var tag = event.target.enclosingNodeOrSelfWithClass("html-tag"); - var textNode = event.target.enclosingNodeOrSelfWithClass("html-text-node"); - var commentNode = event.target.enclosingNodeOrSelfWithClass("html-comment"); - var populated = false; - if (tag && treeElement._populateTagContextMenu) { - if (populated) - contextMenu.appendSeparator(); - treeElement._populateTagContextMenu(contextMenu, event); - populated = true; - } else if (textNode && treeElement._populateTextContextMenu) { - if (populated) - contextMenu.appendSeparator(); - treeElement._populateTextContextMenu(contextMenu, textNode); - populated = true; - } else if (commentNode && treeElement._populateNodeContextMenu) { - if (populated) - contextMenu.appendSeparator(); - treeElement._populateNodeContextMenu(contextMenu, textNode); - populated = true; - } - - return populated; - }, - - adjustCollapsedRange: function() - { - }, - - _updateModifiedNodes: function() - { - if (this._elementsTreeUpdater) - this._elementsTreeUpdater._updateModifiedNodes(); - }, - - _populateContextMenu: function(contextMenu, domNode) - { - if (!this._showInElementsPanelEnabled) - return; - - function revealElement() - { - WebInspector.domTreeManager.inspectElement(domNode.id); - } - - contextMenu.appendSeparator(); - contextMenu.appendItem(WebInspector.UIString("Reveal in DOM Tree"), revealElement); - }, - - _showShadowDOMSettingChanged: function(event) - { - var nodeToSelect = this.selectedTreeElement ? this.selectedTreeElement.representedObject : null; - while (nodeToSelect) { - if (!nodeToSelect.isInShadowTree()) - break; - nodeToSelect = nodeToSelect.parentNode; - } - - this.children.forEach(function(child) { - child.updateChildren(true); - }); - - if (nodeToSelect) - this.selectDOMNode(nodeToSelect); - }, - - _hideElement: function(event, keyboardShortcut) - { - if (!this.selectedTreeElement || WebInspector.isEditingAnyField()) - return; - - event.preventDefault(); - - var selectedNode = this.selectedTreeElement.representedObject; - console.assert(selectedNode); - if (!selectedNode) - return; - - if (selectedNode.nodeType() !== Node.ELEMENT_NODE) - return; - - if (this._togglePending) - return; - this._togglePending = true; - - function toggleProperties() - { - nodeStyles.removeEventListener(WebInspector.DOMNodeStyles.Event.Refreshed, toggleProperties, this); - - var opacityProperty = nodeStyles.inlineStyle.propertyForName("opacity"); - opacityProperty.value = "0"; - opacityProperty.important = true; - - var pointerEventsProperty = nodeStyles.inlineStyle.propertyForName("pointer-events"); - pointerEventsProperty.value = "none"; - pointerEventsProperty.important = true; - - if (opacityProperty.enabled && pointerEventsProperty.enabled) { - opacityProperty.remove(); - pointerEventsProperty.remove(); - } else { - opacityProperty.add(); - pointerEventsProperty.add(); - } - - delete this._togglePending; - } - - var nodeStyles = WebInspector.cssStyleManager.stylesForNode(selectedNode); - if (nodeStyles.needsRefresh) { - nodeStyles.addEventListener(WebInspector.DOMNodeStyles.Event.Refreshed, toggleProperties, this); - nodeStyles.refresh(); - } else - toggleProperties.call(this); - } -} - -WebInspector.DOMTreeOutline.prototype.__proto__ = TreeOutline.prototype; diff --git a/Source/WebInspectorUI/UserInterface/DOMTreeUpdater.js b/Source/WebInspectorUI/UserInterface/DOMTreeUpdater.js deleted file mode 100644 index 094e530fe..000000000 --- a/Source/WebInspectorUI/UserInterface/DOMTreeUpdater.js +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright (C) 2007, 2008, 2013 Apple Inc. All rights reserved. - * Copyright (C) 2008 Matt Lilek - * Copyright (C) 2009 Joseph Pecoraro - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/** - * @constructor - */ -WebInspector.DOMTreeUpdater = function(treeOutline) -{ - WebInspector.domTreeManager.addEventListener(WebInspector.DOMTreeManager.Event.NodeInserted, this._nodeInserted, this); - WebInspector.domTreeManager.addEventListener(WebInspector.DOMTreeManager.Event.NodeRemoved, this._nodeRemoved, this); - WebInspector.domTreeManager.addEventListener(WebInspector.DOMTreeManager.Event.AttributeModified, this._attributesUpdated, this); - WebInspector.domTreeManager.addEventListener(WebInspector.DOMTreeManager.Event.AttributeRemoved, this._attributesUpdated, this); - WebInspector.domTreeManager.addEventListener(WebInspector.DOMTreeManager.Event.CharacterDataModified, this._characterDataModified, this); - WebInspector.domTreeManager.addEventListener(WebInspector.DOMTreeManager.Event.DocumentUpdated, this._documentUpdated, this); - WebInspector.domTreeManager.addEventListener(WebInspector.DOMTreeManager.Event.ChildNodeCountUpdated, this._childNodeCountUpdated, this); - - this._treeOutline = treeOutline; - this._recentlyModifiedNodes = []; -} - -WebInspector.DOMTreeUpdater.prototype = { - close: function() - { - WebInspector.domTreeManager.removeEventListener(null, null, this); - }, - - _documentUpdated: function(event) - { - this._reset(); - }, - - _attributesUpdated: function(event) - { - this._recentlyModifiedNodes.push({node: event.data.node, updated: true}); - if (this._treeOutline._visible) - this._updateModifiedNodesSoon(); - }, - - _characterDataModified: function(event) - { - this._recentlyModifiedNodes.push({node: event.data.node, updated: true}); - if (this._treeOutline._visible) - this._updateModifiedNodesSoon(); - }, - - _nodeInserted: function(event) - { - this._recentlyModifiedNodes.push({node: event.data.node, parent: event.data.parent, inserted: true}); - if (this._treeOutline._visible) - this._updateModifiedNodesSoon(); - }, - - _nodeRemoved: function(event) - { - this._recentlyModifiedNodes.push({node: event.data.node, parent: event.data.parent, removed: true}); - if (this._treeOutline._visible) - this._updateModifiedNodesSoon(); - }, - - _childNodeCountUpdated: function(event) - { - var treeElement = this._treeOutline.findTreeElement(event.data); - if (treeElement) - treeElement.hasChildren = event.data.hasChildNodes(); - }, - - _updateModifiedNodesSoon: function() - { - if (this._updateModifiedNodesTimeout) - return; - this._updateModifiedNodesTimeout = setTimeout(this._updateModifiedNodes.bind(this), 0); - }, - - _updateModifiedNodes: function() - { - if (this._updateModifiedNodesTimeout) { - clearTimeout(this._updateModifiedNodesTimeout); - delete this._updateModifiedNodesTimeout; - } - - var updatedParentTreeElements = []; - - for (var i = 0; i < this._recentlyModifiedNodes.length; ++i) { - var parent = this._recentlyModifiedNodes[i].parent; - var node = this._recentlyModifiedNodes[i].node; - - if (this._recentlyModifiedNodes[i].updated) { - var nodeItem = this._treeOutline.findTreeElement(node); - if (nodeItem) - nodeItem.updateTitle(); - continue; - } - - if (!parent) - continue; - - var parentNodeItem = this._treeOutline.findTreeElement(parent); - if (parentNodeItem && !parentNodeItem.alreadyUpdatedChildren) { - parentNodeItem.updateChildren(); - parentNodeItem.alreadyUpdatedChildren = true; - updatedParentTreeElements.push(parentNodeItem); - } - } - - for (var i = 0; i < updatedParentTreeElements.length; ++i) - delete updatedParentTreeElements[i].alreadyUpdatedChildren; - - this._recentlyModifiedNodes = []; - }, - - _reset: function() - { - WebInspector.domTreeManager.hideDOMNodeHighlight(); - this._recentlyModifiedNodes = []; - } -} diff --git a/Source/WebInspectorUI/UserInterface/DOMUtilities.js b/Source/WebInspectorUI/UserInterface/DOMUtilities.js deleted file mode 100644 index 971e900e6..000000000 --- a/Source/WebInspectorUI/UserInterface/DOMUtilities.js +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (C) 2011 Google Inc. All rights reserved. - * Copyright (C) 2007, 2008, 2013 Apple Inc. All rights reserved. - * Copyright (C) 2008 Matt Lilek - * Copyright (C) 2009 Joseph Pecoraro - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.displayNameForNode = function(node) -{ - var title = node.nodeNameInCorrectCase(); - - var idAttribute = node.getAttribute("id"); - if (idAttribute) { - if (/[\s'"]/.test(idAttribute)) { - idAttribute = idAttribute.replace(/\\/g, "\\\\").replace(/\"/g, "\\\""); - title += "[id=\"" + idAttribute + "\"]"; - } else - title += "#" + idAttribute; - } - - var classAttribute = node.getAttribute("class"); - if (classAttribute) { - var classes = classAttribute.trim().split(/\s+/); - var foundClasses = {}; - - for (var i = 0; i < classes.length; ++i) { - var className = classes[i]; - if (className && !(className in foundClasses)) { - title += "." + className; - foundClasses[className] = true; - } - } - } - - return title; -} - -WebInspector.linkifyNodeReference = function(node) -{ - var displayName = WebInspector.displayNameForNode(node); - - var link = document.createElement("span"); - link.appendChild(document.createTextNode(displayName)); - link.className = "node-link"; - link.title = displayName; - - link.addEventListener("click", WebInspector.domTreeManager.inspectElement.bind(WebInspector.domTreeManager, node.id)); - link.addEventListener("mouseover", WebInspector.domTreeManager.highlightDOMNode.bind(WebInspector.domTreeManager, node.id, "")); - link.addEventListener("mouseout", WebInspector.domTreeManager.hideDOMNodeHighlight.bind(WebInspector.domTreeManager)); - - return link; -} diff --git a/Source/WebInspectorUI/UserInterface/DashboardManager.js b/Source/WebInspectorUI/UserInterface/DashboardManager.js deleted file mode 100644 index fad8b3d0d..000000000 --- a/Source/WebInspectorUI/UserInterface/DashboardManager.js +++ /dev/null @@ -1,187 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.DashboardManager = function() { - WebInspector.Object.call(this); - - this.toolbarItem = new WebInspector.NavigationItem("dashboard", "group", WebInspector.UIString("Activity Viewer")); - this._view = new WebInspector.DashboardView(this.toolbarItem.element); - - this._waitingForFirstMainResourceToStartTrackingSize = true; - - // Necessary event required to track page load time and resource sizes. - WebInspector.Frame.addEventListener(WebInspector.Frame.Event.MainResourceDidChange, this._mainResourceDidChange, this); - WebInspector.timelineManager.addEventListener(WebInspector.TimelineManager.Event.RecordingStopped, this._recordingStopped, this); - - // Necessary events required to track load of resources. - WebInspector.Frame.addEventListener(WebInspector.Frame.Event.ResourceWasAdded, this._resourceWasAdded, this); - WebInspector.frameResourceManager.addEventListener(WebInspector.FrameResourceManager.Event.FrameWasAdded, this._frameWasAdded, this); - - // Necessary events required to track console messages. - var logManager = WebInspector.logManager; - logManager.addEventListener(WebInspector.LogManager.Event.Cleared, this._consoleWasCleared, this); - logManager.addEventListener(WebInspector.LogManager.Event.ActiveLogCleared, this._consoleWasCleared, this); - logManager.addEventListener(WebInspector.LogManager.Event.MessageAdded, this._consoleMessageAdded, this); - logManager.addEventListener(WebInspector.LogManager.Event.PreviousMessageRepeatCountUpdated, this._consoleMessageWasRepeated, this); -}; - -WebInspector.DashboardManager.prototype = { - constructor: WebInspector.DashboardManager, - - _mainResourceDidChange: function(event) - { - console.assert(event.target instanceof WebInspector.Frame); - - if (!event.target.isMainFrame()) - return; - - this._view.resourcesCount = 1; - this._view.resourcesSize = WebInspector.frameResourceManager.mainFrame.mainResource.size || 0; - - // Only update the time if we are recording the timeline. - if (!WebInspector.timelineManager.recordingEnabled) { - this._view.time = 0; - return; - } - - // We should only track resource sizes on fresh loads. - if (this._waitingForFirstMainResourceToStartTrackingSize) { - delete this._waitingForFirstMainResourceToStartTrackingSize; - WebInspector.Resource.addEventListener(WebInspector.Resource.Event.SizeDidChange, this._resourceSizeDidChange, this); - } - - this._startUpdatingTime(); - }, - - _recordingStopped: function(event) - { - // If recording stops, we should stop the timer if it hasn't stopped already. - this._stopUpdatingTime(); - }, - - _resourceWasAdded: function(event) - { - ++this._view.resourcesCount; - }, - - _frameWasAdded: function(event) - { - ++this._view.resourcesCount; - }, - - _resourceSizeDidChange: function(event) - { - this._view.resourcesSize += event.target.size - event.data.previousSize; - }, - - _startUpdatingTime: function() - { - this._stopUpdatingTime(); - - this._view.time = 0; - - this._timelineBaseTime = Date.now(); - this._timeIntervalDelay = 50; - this._timeIntervalIdentifier = setInterval(this._updateTime.bind(this), this._timeIntervalDelay); - }, - - _stopUpdatingTime: function() - { - if (!this._timeIntervalIdentifier) - return; - - clearInterval(this._timeIntervalIdentifier); - delete this._timeIntervalIdentifier; - }, - - _updateTime: function() - { - var duration = Date.now() - this._timelineBaseTime; - - var timeIntervalDelay = this._timeIntervalDelay; - if (duration >= 1000) // 1 second - timeIntervalDelay = 100; - else if (duration >= 60000) // 60 seconds - timeIntervalDelay = 1000; - else if (duration >= 3600000) // 1 minute - timeIntervalDelay = 10000; - - if (timeIntervalDelay !== this._timeIntervalDelay) { - this._timeIntervalDelay = timeIntervalDelay; - - clearInterval(this._timeIntervalIdentifier); - this._timeIntervalIdentifier = setInterval(this._updateTime.bind(this), this._timeIntervalDelay); - } - - var mainFrame = WebInspector.frameResourceManager.mainFrame; - var mainFrameStartTime = mainFrame.mainResource.firstTimestamp; - var mainFrameLoadEventTime = mainFrame.loadEventTimestamp; - - if (isNaN(mainFrameStartTime) || isNaN(mainFrameLoadEventTime)) { - this._view.time = duration / 1000; - return; - } - - this._view.time = mainFrameLoadEventTime - mainFrameStartTime; - - this._stopUpdatingTime(); - }, - - _consoleMessageAdded: function(event) - { - var message = event.data.message; - this._lastConsoleMessageType = message.level; - this._incrementConsoleMessageType(message.level, message.totalRepeatCount); - }, - - _consoleMessageWasRepeated: function(event) - { - this._incrementConsoleMessageType(this._lastConsoleMessageType, 1); - }, - - _incrementConsoleMessageType: function(type, increment) - { - switch (type) { - case "log": - this._view.logs += increment; - break; - case "warning": - this._view.issues += increment; - break; - case "error": - this._view.errors += increment; - break; - } - }, - - _consoleWasCleared: function(event) - { - this._view.logs = 0; - this._view.issues = 0; - this._view.errors = 0; - } -}; - -WebInspector.DashboardManager.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/DashboardView.css b/Source/WebInspectorUI/UserInterface/DashboardView.css deleted file mode 100644 index c754f3b6d..000000000 --- a/Source/WebInspectorUI/UserInterface/DashboardView.css +++ /dev/null @@ -1,243 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.toolbar .dashboard { - display: -webkit-flex; - -webkit-flex-flow: row nowrap; - - -webkit-justify-content: space-between; - - margin: 4px 10px; - padding: 0 5px; - - width: 375px; - - background-image: -webkit-linear-gradient(bottom, rgba(0, 128, 255, 0.075), rgba(0, 128, 255, 0)), - -webkit-linear-gradient(left, rgba(0, 0, 0, 0.09), transparent, rgba(0, 0, 0, 0.09)), - -webkit-linear-gradient(top, rgb(240, 244, 251), rgb(250, 253, 255)); - background-size: 100% 6px, auto, auto; - background-position: bottom, center, center; - background-repeat: no-repeat; - - border: 1px solid rgb(163, 163, 163); - border-radius: 4px; - - box-shadow: rgba(255, 255, 255, 0.45) 0 1px 0; -} - -body.window-inactive .toolbar .dashboard { - border-color: rgb(196, 196, 196); - background-image: none; - background-color: rgb(239, 239, 239); -} - -.toolbar.collapsed .dashboard, -body.javascript .toolbar .dashboard { - width: 175px; -} - -body.web .toolbar.collapsed .dashboard > .time, -body.web .toolbar.collapsed .dashboard > .resourcesSize, -body.web .toolbar.collapsed .dashboard > .logs { - display: none; -} - -body.javascript .toolbar .dashboard > .time, -body.javascript .toolbar .dashboard > .resourcesSize, -body.javascript .toolbar .dashboard > .resourcesCount { - display: none; -} - -.toolbar .dashboard > .item { - font-family: Helvetica, sans-serif; - font-weight: bold; - font-size: 11px; - line-height: 12px; - - padding: 0 5px; - - display: -webkit-flex; - - min-width: 45px; - - -webkit-justify-content: center; - -webkit-align-items: center; - - border-radius: 4px; - border: 1px solid transparent; -} - -.toolbar .dashboard > .time, -.toolbar .dashboard > .resourcesSize { - min-width: 70px; -} - -.toolbar .dashboard > .item.enabled:hover { - border: 1px solid rgba(0, 0, 0, 0.1); -} - -.toolbar .dashboard > .item.enabled:active { - border: 1px solid rgba(0, 0, 0, 0.2); -} - -.toolbar .dashboard > .item > * { - display: -webkit-flex; - -webkit-align-items: center; -} - -.toolbar .dashboard > .item > img { - opacity: 0.2; - width: 16px; - height: 16px; - pointer-events: none; -} - -.toolbar .dashboard > .item.enabled > img { - opacity: 0.5; -} - -.toolbar .dashboard > .item.enabled:hover > img { - opacity: 0.65; -} - -.toolbar .dashboard > .item > div { - display: -webkit-flex; - -webkit-flex: 1; - - color: rgba(0, 0, 0, 0.2); - padding-left: 2px; -} - -.toolbar .dashboard > .item.enabled > div { - color: rgba(0, 0, 0, 0.7); -} - -.toolbar .dashboard > .item.enabled:hover > div { - color: rgba(0, 0, 0, 0.85); -} - -.toolbar .dashboard > .resourcesCount > img { - content: url(Images/Resources.svg); -} - -.toolbar .dashboard > .time > img { - content: url(Images/Time.svg); -} - -.toolbar .dashboard > .logs > img { - content: url(Images/Logs.svg); -} - -.toolbar .dashboard > .resourcesSize > img { - content: url(Images/Weight.svg); -} - -.toolbar .dashboard > .errors > img { - content: url(Images/Errors.svg); -} - -.toolbar .dashboard > .errors.enabled > img { - content: url(Images/ErrorsEnabled.svg); - opacity: 0.9; -} - -.toolbar .dashboard > .errors.enabled:hover > img { - opacity: 1; -} - -.toolbar .dashboard > .errors.enabled > div { - color: rgba(201, 55, 57, 0.9); -} - -.toolbar .dashboard > .errors.enabled:hover > div { - color: rgb(201, 55, 57); -} - -.toolbar .dashboard > .issues > img { - content: url(Images/Issues.svg); -} - -.toolbar .dashboard > .issues.enabled > img { - content: url(Images/IssuesEnabled.svg); - opacity: 0.9; -} - -.toolbar .dashboard > .issues.enabled:hover > img { - opacity: 1; -} - -.toolbar .dashboard > .issues.enabled > div { - color: rgba(224, 164, 4, 0.9); -} - -.toolbar .dashboard > .issues.enabled:hover > div { - color: rgb(224, 164, 4); -} - -.toolbar.small-size.icon-and-label-vertical .dashboard, -.toolbar.normal-size.icon-and-label-vertical .dashboard { - margin-top: 6px; -} - -/* Styles for the extra short style, one row with quite a small y-margin */ - -.toolbar.label-only .dashboard, -.toolbar.small-size.icon-only .dashboard, -.toolbar.small-size.icon-and-label-vertical .dashboard, -.toolbar.small-size.icon-and-label-horizontal .dashboard { - height: 22px; -} - -.toolbar.label-only .dashboard > .item, -.toolbar.small-size.icon-only .dashboard > .item, -.toolbar.small-size.icon-and-label-vertical .dashboard > .item, -.toolbar.small-size.icon-and-label-horizontal .dashboard > .item { - margin: 1px 0; -} - -/* Styles for the fairly short style, one row with quite a bit of y-margin */ - -.toolbar.normal-size.icon-only .dashboard, -.toolbar.normal-size.icon-and-label-vertical .dashboard, -.toolbar.normal-size.icon-and-label-horizontal .dashboard { - height: 30px; -} - -.toolbar.normal-size.icon-only .dashboard > .item, -.toolbar.normal-size.icon-and-label-vertical .dashboard > .item, -.toolbar.normal-size.icon-and-label-horizontal .dashboard > .item { - margin: 4px 0; -} - -/* Styles for the pulsing animated state of console items */ - -.toolbar .dashboard > .item.pulsing { - -webkit-animation-name: console-item-pulse; - -webkit-animation-duration: 0.75s; -} - -@-webkit-keyframes console-item-pulse { - 50% { opacity: 0.6; } -} diff --git a/Source/WebInspectorUI/UserInterface/DashboardView.js b/Source/WebInspectorUI/UserInterface/DashboardView.js deleted file mode 100644 index 982839b21..000000000 --- a/Source/WebInspectorUI/UserInterface/DashboardView.js +++ /dev/null @@ -1,245 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.DashboardView = function(element) -{ - WebInspector.Object.call(this); - - this._element = element; - - this._items = { - resourcesCount: { - tooltip: WebInspector.UIString("Total number of resources, click to show the Resources navigation sidebar"), - handler: this._resourcesWasClicked - }, - resourcesSize: { - tooltip: WebInspector.UIString("Total size of all resources, click to show the Network Requests timeline"), - handler: this._networkItemWasClicked - }, - time: { - tooltip: WebInspector.UIString("Time until the load event fired, click to show the Network Requests timeline"), - handler: this._networkItemWasClicked - }, - logs: { - tooltip: WebInspector.UIString("Console logs, click to show the Console"), - handler: this._consoleItemWasClicked.bind(this, WebInspector.LogContentView.Scopes.Logs) - }, - errors: { - tooltip: WebInspector.UIString("Console errors, click to show the Console"), - handler: this._consoleItemWasClicked.bind(this, WebInspector.LogContentView.Scopes.Errors) - }, - issues: { - tooltip: WebInspector.UIString("Console warnings, click to show the Console"), - handler: this._consoleItemWasClicked.bind(this, WebInspector.LogContentView.Scopes.Warnings) - } - }; - - for (var name in this._items) - this._appendElementForNamedItem(name); - - this.resourcesCount = 0; - this.resourcesSize = 0; - this.time = 0; - this.logs = 0; - this.errors = 0; - this.issues = 0; -}; - -WebInspector.DashboardView.EnabledStyleClassName = "enabled"; - -WebInspector.DashboardView.prototype = { - constructor: WebInspector.DashboardView, - - // Public - - get logs() - { - return this._logs; - }, - - set logs(logs) - { - this._setConsoleItemValue("logs", logs); - }, - - get issues() - { - return this._issues; - }, - - set issues(issues) - { - this._setConsoleItemValue("issues", issues); - }, - - get errors() - { - return this._errors; - }, - - set errors(errors) - { - this._setConsoleItemValue("errors", errors); - }, - - set time(time) - { - var item = this._items.time; - item.text = time ? Number.secondsToString(time) : "\u2014"; - this._setItemEnabled(item, time > 0); - }, - - get resourcesCount() - { - return this._resourcesCount; - }, - - set resourcesCount(resourcesCount) - { - this._resourcesCount = resourcesCount; - - var item = this._items.resourcesCount; - item.text = this._formatPossibleLargeNumber(resourcesCount); - this._setItemEnabled(item, resourcesCount > 0); - }, - - get resourcesSize() - { - return this._resourcesSize; - }, - - set resourcesSize(resourcesSize) - { - this._resourcesSize = resourcesSize; - - var item = this._items.resourcesSize; - item.text = resourcesSize ? Number.bytesToString(resourcesSize, false) : "\u2014"; - this._setItemEnabled(item, resourcesSize > 0); - }, - - // Private - - _formatPossibleLargeNumber: function(number) - { - return number > 999 ? WebInspector.UIString("999+") : number; - }, - - _appendElementForNamedItem: function(name) - { - var item = this._items[name]; - - item.container = this._element.appendChild(document.createElement("div")); - item.container.className = "item " + name; - item.container.title = item.tooltip; - - item.container.appendChild(document.createElement("img")); - - item.outlet = item.container.appendChild(document.createElement("div")); - - Object.defineProperty(item, "text", - { - set: function(newText) - { - if (newText === item.outlet.textContent) - return; - item.outlet.textContent = newText; - } - }); - - item.container.addEventListener("click", function(event) { - this._itemWasClicked(name); - }.bind(this)); - }, - - _itemWasClicked: function(name) - { - var item = this._items[name]; - if (!item.container.classList.contains(WebInspector.DashboardView.EnabledStyleClassName)) - return; - - if (item.handler) - item.handler.call(this); - }, - - _resourcesWasClicked: function() - { - WebInspector.navigationSidebar.selectedSidebarPanel = WebInspector.resourceSidebarPanel; - WebInspector.navigationSidebar.collapsed = false; - }, - - _networkItemWasClicked: function() - { - WebInspector.navigationSidebar.selectedSidebarPanel = WebInspector.timelineSidebarPanel; - }, - - _consoleItemWasClicked: function(scope) - { - WebInspector.showConsoleView(scope); - }, - - _setConsoleItemValue: function(itemName, newValue) - { - var iVarName = "_" + itemName; - var previousValue = this[iVarName]; - this[iVarName] = newValue; - - var item = this._items[itemName]; - item.text = this._formatPossibleLargeNumber(newValue); - this._setItemEnabled(item, newValue > 0); - - if (newValue <= previousValue) - return; - - var container = item.container; - - function animationEnded(event) - { - if (event.target === container) { - container.classList.remove("pulsing"); - container.removeEventListener("webkitAnimationEnd", animationEnded); - } - } - - // We need to force a style invalidation in the case where we already - // were animating this item after we've removed the pulsing CSS class. - if (container.classList.contains("pulsing")) { - container.classList.remove("pulsing"); - container.recalculateStyles(); - } else - container.addEventListener("webkitAnimationEnd", animationEnded); - - container.classList.add("pulsing"); - }, - - _setItemEnabled: function(item, enabled) - { - if (enabled) - item.container.classList.add(WebInspector.DashboardView.EnabledStyleClassName); - else - item.container.classList.remove(WebInspector.DashboardView.EnabledStyleClassName); - } -}; - -WebInspector.DashboardView.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/DataGrid.css b/Source/WebInspectorUI/UserInterface/DataGrid.css deleted file mode 100644 index 0a2e21908..000000000 --- a/Source/WebInspectorUI/UserInterface/DataGrid.css +++ /dev/null @@ -1,337 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.data-grid { - position: relative; - border: 1px solid #aaa; - outline: none; -} - -.data-grid .highlight { - background-color: rgb(255, 230, 179); -} - -.data-grid tr.selected .highlight { - background-color: transparent; -} - -.data-grid table { - table-layout: fixed; - border-spacing: 0; - border-collapse: collapse; - width: 100%; - font-size: 10px; - font-family: Lucida Grande, sans-serif; -} - -.data-grid .data-container { - position: absolute; - top: 16px; - bottom: 0; - left: 0; - right: 0; - overflow-x: hidden; - overflow-y: overlay; -} - -.data-grid.inline .data-container { - position: static; -} - -.data-grid.inline { - border: 1px solid rgb(181, 181, 181); -} - -.data-grid.no-header > table.header { - display: none; -} - -.data-grid.no-header .data-container { - top: 0; -} - -.data-grid th { - text-align: left; - vertical-align: middle; - - background-image: -webkit-linear-gradient(top, rgba(0, 0, 0, 0.2), rgba(0, 0, 0, 0.2)), -webkit-linear-gradient(top, transparent, transparent), - -webkit-linear-gradient(top, white, white 25%, rgb(244, 244, 244) 50%, rgb(236, 236, 236) 50%, rgb(237, 237, 237)); - background-size: 1px 11px, 0 0, 100% 100%; - background-position: left 2px, right 2px, center; - background-repeat: no-repeat; - - box-shadow: inset rgba(255, 255, 255, 0.3) 0 -1px 0; - border-bottom: 1px solid rgb(182, 182, 182); - - height: 15px; - font-weight: normal; - padding: 0 4px; - white-space: nowrap; - overflow: hidden; -} - -.data-grid th:first-child { - background-position: -1px 2px, right 2px, center; -} - -.data-grid th:active:first-child { - background-position: -1px 2px, right top, center; -} - -.data-grid th:last-child { - background-position: left 2px, -1px 2px, center; -} - -.data-grid th:active:last-child { - background-position: left top, -1px top, center; -} - -.data-grid tr.filler { - display: table-row !important; - height: auto !important; -} - -.data-grid tr.filler td { - height: auto !important; - padding: 0 !important; -} - -.data-grid table.data { - position: absolute; - left: 0; - top: 0; - right: 0; - bottom: 0; - height: 100%; - border-top: 0 none transparent; - background-image: -webkit-linear-gradient(top, white, white 50%, rgb(243, 246, 250) 50%, rgb(243, 246, 250)); - background-size: 100% 32px; - table-layout: fixed; -} - -.data-grid.inline table.data { - position: static; -} - -.data-grid table.data tr { - display: none; -} - -.data-grid table.data tr.revealed { - display: table-row; -} - -.data-grid td { - vertical-align: top; - height: 12px; - line-height: 12px; - padding: 2px 4px; - white-space: nowrap; - overflow: hidden; -} - -.data-grid td:last-child { - padding-right: 16px; -} - -.data-grid td > div, .data-grid th > div { - white-space: nowrap; - text-overflow: ellipsis; - overflow: hidden; -} - -.data-grid .centered div { - text-align: center; -} - -.data-grid .right div { - text-align: right; -} - -.data-grid th.sortable div { - position: relative; -} - -.data-grid th.sortable:not(.mouse-over-collapser):active { - background-image: -webkit-linear-gradient(top, rgba(0, 0, 0, 0.3), rgba(0, 0, 0, 0.3)), -webkit-linear-gradient(top, rgba(0, 0, 0, 0.3), rgba(0, 0, 0, 0.3)), - -webkit-linear-gradient(top, rgb(224, 224, 224), rgb(224, 224, 224) 25%, rgb(214, 214, 214) 50%, rgb(207, 207, 207) 50%, rgb(208, 208, 208)); - background-size: 1px 15px, 1px 15px, 100% 100%; - background-position: left top, right top, center; - - box-shadow: inset rgba(255, 255, 255, 0.1) 0 -1px 0; - border-bottom: 1px solid rgb(160, 160, 160); -} - -.data-grid th.sort-ascending, .data-grid th.sort-descending { - background-image: -webkit-linear-gradient(top, rgba(0, 0, 120, 0.2), rgba(0, 0, 120, 0.2)), -webkit-linear-gradient(top, rgba(0, 0, 120, 0.2), rgba(0, 0, 120, 0.2)), - -webkit-linear-gradient(top, rgb(199, 226, 246), rgb(169, 209, 239) 25%, rgb(158, 204, 239) 50%, rgb(142, 196, 237) 50%, rgb(187, 230, 245)); - background-size: 1px 15px, 1px 15px, 100% 100%; - background-position: left top, right top, center; - - box-shadow: inset rgba(255, 255, 255, 0.1) 0 -1px 0; - border-bottom: 1px solid rgb(130, 179, 210); -} - -.data-grid th.sortable.sort-ascending:not(.mouse-over-collapser):active, .data-grid th.sortable.sort-descending:not(.mouse-over-collapser):active { - background-image: -webkit-linear-gradient(top, rgba(0, 0, 120, 0.2), rgba(0, 0, 120, 0.2)), -webkit-linear-gradient(top, rgba(0, 0, 120, 0.2), rgba(0, 0, 120, 0.2)), - -webkit-linear-gradient(top, rgb(144, 180, 227), rgb(109, 160, 220) 25%, rgb(96, 155, 221) 50%, rgb(77, 146, 219) 50%, rgb(130, 186, 227)); - background-size: 1px 15px, 1px 15px, 100% 100%; - background-position: left top, right top, center; - - border-bottom: 1px solid rgb(63, 125, 192); -} - -.data-grid th:active + th, -.data-grid th.sort-ascending + th, -.data-grid th.sort-descending + th { - background-position: -1px 2px, -1px 2px, center; -} - -.data-grid th:active + th.sort-ascending, -.data-grid th:active + th.sort-descending, -.data-grid th.sort-ascending + th:active, -.data-grid th.sort-descending + th:active { - background-position: -1px top, right top, center; -} - -.data-grid th:first-child:active, -.data-grid th.sort-ascending:first-child, -.data-grid th.sort-descending:first-child { - background-position: -1px top, right top, center !important; -} - -.data-grid th:last-child:active, -.data-grid th.sort-ascending:last-child, -.data-grid th.sort-descending:last-child { - background-position: left top, -1px top, center !important; -} - -.data-grid th.sort-ascending > div:first-child, -.data-grid th.sort-descending > div:first-child { - padding-right: 10px; -} - -.data-grid th.sort-ascending > div:first-child::after { - position: absolute; - top: 0; - bottom: 0; - right: 0; - - margin-bottom: auto; - margin-top: auto; - - width: 9px; - height: 8px; - - content: ""; - - background-image: -webkit-canvas(data-grid-sort-indicator-up-arrow); - background-size: 9px 8px; - background-repeat: no-repeat; -} - -.data-grid th.sort-descending > div:first-child::after { - position: absolute; - top: 0; - bottom: 0; - right: 0; - - margin-bottom: auto; - margin-top: auto; - - width: 9px; - height: 8px; - - content: ""; - - background-image: -webkit-canvas(data-grid-sort-indicator-down-arrow); - background-size: 9px 8px; - background-repeat: no-repeat; -} - -.data-grid button { - line-height: 19px; -} - -body.window-inactive .data-grid th.sort-ascending, -body.window-inactive .data-grid th.sort-descending { - background-image: -webkit-linear-gradient(top, white, white 25%, rgb(244, 244, 244) 50%, rgb(236, 236, 236) 50%, rgb(237, 237, 237)), - -webkit-linear-gradient(top, rgba(0, 0, 0, 0.2), rgba(0, 0, 0, 0.2)); - background-size: 100% 100%, 1px 11px; - background-position: center, right center; - background-repeat: no-repeat; - border-bottom: 1px solid rgb(182, 182, 182); -} - -.data-grid tr.parent td.disclosure::before { - float: left; - - content: ""; - - background-image: -webkit-canvas(disclosure-triangle-tiny-closed-normal); - background-size: 8px 8px; - background-repeat: no-repeat; - - width: 8px; - height: 8px; - - margin-top: 2px; - margin-right: 2px; -} - -.data-grid tr.parent.expanded td.disclosure::before { - background-image: -webkit-canvas(disclosure-triangle-tiny-open-normal); -} - -.data-grid:focus tr.parent.selected td.disclosure::before { - background-image: -webkit-canvas(disclosure-triangle-tiny-closed-selected); -} - -.data-grid:focus tr.parent.expanded.selected td.disclosure::before { - background-image: -webkit-canvas(disclosure-triangle-tiny-open-selected); -} - -.data-grid tr.selected { - background-color: rgb(212, 212, 212) !important; - color: inherit !important; -} - -.data-grid:focus tr.selected { - background-color: rgb(56, 121, 217) !important; - color: white !important; -} - -.data-grid tr:not(.parent) td.disclosure { - text-indent: 10px; -} - -.data-grid-resizer { - position: absolute; - top: 0; - bottom: 0; - width: 5px; - z-index: 500; - cursor: col-resize; -} diff --git a/Source/WebInspectorUI/UserInterface/DataGrid.js b/Source/WebInspectorUI/UserInterface/DataGrid.js deleted file mode 100644 index 52e5f09ab..000000000 --- a/Source/WebInspectorUI/UserInterface/DataGrid.js +++ /dev/null @@ -1,1872 +0,0 @@ -/* - * Copyright (C) 2008, 2013 Apple Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/** - * @constructor - * @extends {WebInspector.Object} - * @param {function(WebInspector.DataGridNode, number, string, string)=} editCallback - * @param {function(WebInspector.DataGridNode)=} deleteCallback - */ -WebInspector.DataGrid = function(columns, editCallback, deleteCallback) -{ - this.element = document.createElement("div"); - this.element.className = "data-grid"; - this.element.tabIndex = 0; - this.element.addEventListener("keydown", this._keyDown.bind(this), false); - this.element.copyHandler = this; - - this._headerTable = document.createElement("table"); - this._headerTable.className = "header"; - this._headerTableHeaders = {}; - - this._dataTable = document.createElement("table"); - this._dataTable.className = "data"; - - this._dataTable.addEventListener("mousedown", this._mouseDownInDataTable.bind(this)); - this._dataTable.addEventListener("click", this._clickInDataTable.bind(this)); - - this._dataTable.addEventListener("contextmenu", this._contextMenuInDataTable.bind(this), true); - - // FIXME: Add a createCallback which is different from editCallback and has different - // behavior when creating a new node. - if (editCallback) { - this._dataTable.addEventListener("dblclick", this._ondblclick.bind(this), false); - this._editCallback = editCallback; - } - if (deleteCallback) - this._deleteCallback = deleteCallback; - - this.aligned = {}; - this.groups = {}; - this._hiddenColumns = {}; - - this._scrollContainer = document.createElement("div"); - this._scrollContainer.className = "data-container"; - this._scrollContainer.appendChild(this._dataTable); - - this.element.appendChild(this._headerTable); - this.element.appendChild(this._scrollContainer); - - var headerRow = document.createElement("tr"); - var columnGroup = document.createElement("colgroup"); - this._columnCount = 0; - - for (var columnIdentifier in columns) { - var column = columns[columnIdentifier]; - if (column.disclosure) - this.disclosureColumnIdentifier = columnIdentifier; - - var col = document.createElement("col"); - if (column.width) - col.style.width = column.width; - column.element = col; - columnGroup.appendChild(col); - - var cell = document.createElement("th"); - cell.className = columnIdentifier + "-column"; - cell.columnIdentifier = columnIdentifier; - if (column.aligned) - cell.classList.add(column.aligned); - this._headerTableHeaders[columnIdentifier] = cell; - - var div = document.createElement("div"); - if (column.titleDOMFragment) - div.appendChild(column.titleDOMFragment); - else - div.textContent = column.title || ""; - cell.appendChild(div); - - if (column.sort) { - cell.classList.add("sort-" + column.sort); - this._sortColumnCell = cell; - } - - if (column.sortable) { - cell.addEventListener("click", this._clickInHeaderCell.bind(this), false); - cell.classList.add("sortable"); - } - - if (column.aligned) - this.aligned[columnIdentifier] = column.aligned; - - if (column.group) { - this.groups[columnIdentifier] = column.group; - cell.classList.add("column-group-" + column.group); - } - - if (column.collapsesGroup) { - console.assert(column.group !== column.collapsesGroup); - - var divider = document.createElement("div"); - divider.className = "divider"; - cell.appendChild(divider); - - var collapseDiv = document.createElement("div"); - collapseDiv.className = "collapser-button"; - collapseDiv.title = this._collapserButtonCollapseColumnsToolTip(); - collapseDiv.addEventListener("mouseover", this._mouseoverColumnCollapser.bind(this)); - collapseDiv.addEventListener("mouseout", this._mouseoutColumnCollapser.bind(this)); - collapseDiv.addEventListener("click", this._clickInColumnCollapser.bind(this)); - cell.appendChild(collapseDiv); - - cell.collapsesGroup = column.collapsesGroup; - cell.classList.add("collapser"); - } - - headerRow.appendChild(cell); - - ++this._columnCount; - } - - columnGroup.span = this._columnCount; - - this._headerTableColumnGroup = columnGroup; - this._headerTable.appendChild(this._headerTableColumnGroup); - this.headerTableBody.appendChild(headerRow); - - var fillerRow = document.createElement("tr"); - fillerRow.className = "filler"; - - for (var columnIdentifier in columns) { - var column = columns[columnIdentifier]; - var td = document.createElement("td"); - td.className = columnIdentifier + "-column"; - td.__columnIdentifier = columnIdentifier; - var group = this.groups[columnIdentifier]; - if (group) - td.classList.add("column-group-" + group); - fillerRow.appendChild(td); - } - - this._dataTableColumnGroup = columnGroup.cloneNode(true); - this._dataTable.appendChild(this._dataTableColumnGroup); - this.dataTableBody.appendChild(fillerRow); - - this.columns = columns || {}; - this._columnsArray = []; - - for (var columnIdentifier in columns) { - columns[columnIdentifier].ordinal = this._columnsArray.length; - columns[columnIdentifier].identifier = columnIdentifier; - this._columnsArray.push(columns[columnIdentifier]); - } - - for (var i = 0; i < this._columnsArray.length; ++i) - this._columnsArray[i].bodyElement = this._dataTableColumnGroup.children[i]; - - this.children = []; - this.selectedNode = null; - this.expandNodesWhenArrowing = false; - this.root = true; - this.hasChildren = false; - this.expanded = true; - this.revealed = true; - this.selected = false; - this.dataGrid = this; - this.indentWidth = 15; - this.resizers = []; - this._columnWidthsInitialized = false; - - for (var columnIdentifier in columns) { - if (columns[columnIdentifier].hidden) - this._hideColumn(columnIdentifier); - } - - this._generateSortIndicatorImagesIfNeeded(); -} - -WebInspector.DataGrid.Event = { - DidLayout: "datagrid-did-layout", - SortChanged: "datagrid-sort-changed", - SelectedNodeChanged: "datagrid-selected-node-changed", - ExpandedNode: "datagrid-expanded-node", - CollapsedNode: "datagrid-collapsed-node" -}; - -/** - * @param {Array.} columnNames - * @param {Array.} values - */ -WebInspector.DataGrid.createSortableDataGrid = function(columnNames, values) -{ - var numColumns = columnNames.length; - if (!numColumns) - return null; - - var columns = {}; - - for (var i = 0; i < columnNames.length; ++i) { - var column = {}; - column.width = columnNames[i].length; - column.title = columnNames[i]; - column.sortable = true; - - columns[columnNames[i]] = column; - } - - var nodes = []; - for (var i = 0; i < values.length / numColumns; ++i) { - var data = {}; - for (var j = 0; j < columnNames.length; ++j) - data[columnNames[j]] = values[numColumns * i + j]; - - var node = new WebInspector.DataGridNode(data, false); - node.selectable = false; - nodes.push(node); - } - - var dataGrid = new WebInspector.DataGrid(columns); - var length = nodes.length; - for (var i = 0; i < length; ++i) - dataGrid.appendChild(nodes[i]); - - dataGrid.addEventListener(WebInspector.DataGrid.Event.SortChanged, sortDataGrid, this); - - function sortDataGrid() - { - var nodes = dataGrid.children.slice(); - var sortColumnIdentifier = dataGrid.sortColumnIdentifier; - var sortDirection = dataGrid.sortOrder === "ascending" ? 1 : -1; - var columnIsNumeric = true; - - for (var i = 0; i < nodes.length; i++) { - if (isNaN(Number(nodes[i].data[sortColumnIdentifier] || ""))) - columnIsNumeric = false; - } - - function comparator(dataGridNode1, dataGridNode2) - { - var item1 = dataGridNode1.data[sortColumnIdentifier] || ""; - var item2 = dataGridNode2.data[sortColumnIdentifier] || ""; - - var comparison; - if (columnIsNumeric) { - // Sort numbers based on comparing their values rather than a lexicographical comparison. - var number1 = parseFloat(item1); - var number2 = parseFloat(item2); - comparison = number1 < number2 ? -1 : (number1 > number2 ? 1 : 0); - } else - comparison = item1 < item2 ? -1 : (item1 > item2 ? 1 : 0); - - return sortDirection * comparison; - } - - nodes.sort(comparator); - dataGrid.removeChildren(); - for (var i = 0; i < nodes.length; i++) - dataGrid.appendChild(nodes[i]); - } - return dataGrid; -} - -WebInspector.DataGrid.prototype = { - get refreshCallback() - { - return this._refreshCallback; - }, - - set refreshCallback(refreshCallback) - { - this._refreshCallback = refreshCallback; - }, - - _ondblclick: function(event) - { - if (this._editing || this._editingNode) - return; - - this._startEditing(event.target); - }, - - _startEditingColumnOfDataGridNode: function(node, column) - { - this._editing = true; - this._editingNode = node; - this._editingNode.select(); - - var element = this._editingNode._element.children[column]; - WebInspector.startEditing(element, this._startEditingConfig(element)); - window.getSelection().setBaseAndExtent(element, 0, element, 1); - }, - - _startEditing: function(target) - { - var element = target.enclosingNodeOrSelfWithNodeName("td"); - if (!element) - return; - - this._editingNode = this.dataGridNodeFromNode(target); - if (!this._editingNode) { - if (!this.creationNode) - return; - this._editingNode = this.creationNode; - } - - // Force editing the 1st column when editing the creation node - if (this._editingNode.isCreationNode) - return this._startEditingColumnOfDataGridNode(this._editingNode, 0); - - this._editing = true; - WebInspector.startEditing(element, this._startEditingConfig(element)); - - window.getSelection().setBaseAndExtent(element, 0, element, 1); - }, - - _startEditingConfig: function(element) - { - return new WebInspector.EditingConfig(this._editingCommitted.bind(this), this._editingCancelled.bind(this), element.textContent); - }, - - _editingCommitted: function(element, newText, oldText, context, moveDirection) - { - // FIXME: We need more column identifiers here throughout this function. - // Not needed yet since only editable DataGrid is DOM Storage, which is Key - Value. - - var columnIdentifier = element.__columnIdentifier; - - var textBeforeEditing = this._editingNode.data[columnIdentifier] || ""; - var currentEditingNode = this._editingNode; - - function moveToNextIfNeeded(wasChange) { - if (!moveDirection) - return; - - if (moveDirection === "forward") { - if (currentEditingNode.isCreationNode && columnIdentifier === "0" && !wasChange) - return; - - if (columnIdentifier === "0") - return this._startEditingColumnOfDataGridNode(currentEditingNode, "1"); - - var nextDataGridNode = currentEditingNode.traverseNextNode(true, null, true); - if (nextDataGridNode) - return this._startEditingColumnOfDataGridNode(nextDataGridNode, "0"); - if (currentEditingNode.isCreationNode && wasChange) { - this.addCreationNode(false); - return this._startEditingColumnOfDataGridNode(this.creationNode, "0"); - } - return; - } - - if (moveDirection === "backward") { - if (columnIdentifier === "1") - return this._startEditingColumnOfDataGridNode(currentEditingNode, "0"); - var nextDataGridNode = currentEditingNode.traversePreviousNode(true, null, true); - - if (nextDataGridNode) - return this._startEditingColumnOfDataGridNode(nextDataGridNode, "1"); - return; - } - } - - if (textBeforeEditing == newText) { - this._editingCancelled(element); - moveToNextIfNeeded.call(this, false); - return; - } - - // Update the text in the datagrid that we typed - this._editingNode.data[columnIdentifier] = newText; - - // Make the callback - expects an editing node (table row), the column number that is being edited, - // the text that used to be there, and the new text. - this._editCallback(this._editingNode, columnIdentifier, textBeforeEditing, newText); - - if (this._editingNode.isCreationNode) - this.addCreationNode(false); - - this._editingCancelled(element); - moveToNextIfNeeded.call(this, true); - }, - - _editingCancelled: function(element) - { - delete this._editing; - this._editingNode = null; - }, - - get sortColumnIdentifier() - { - if (!this._sortColumnCell) - return null; - return this._sortColumnCell.columnIdentifier; - }, - - get sortOrder() - { - if (!this._sortColumnCell || this._sortColumnCell.classList.contains("sort-ascending")) - return "ascending"; - if (this._sortColumnCell.classList.contains("sort-descending")) - return "descending"; - return null; - }, - - get headerTableBody() - { - if ("_headerTableBody" in this) - return this._headerTableBody; - - this._headerTableBody = this._headerTable.getElementsByTagName("tbody")[0]; - if (!this._headerTableBody) { - this._headerTableBody = this.element.ownerDocument.createElement("tbody"); - this._headerTable.insertBefore(this._headerTableBody, this._headerTable.tFoot); - } - - return this._headerTableBody; - }, - - get dataTableBody() - { - if ("_dataTableBody" in this) - return this._dataTableBody; - - this._dataTableBody = this._dataTable.getElementsByTagName("tbody")[0]; - if (!this._dataTableBody) { - this._dataTableBody = this.element.ownerDocument.createElement("tbody"); - this._dataTable.insertBefore(this._dataTableBody, this._dataTable.tFoot); - } - - return this._dataTableBody; - }, - - /** - * @param {number=} maxDescentLevel - */ - autoSizeColumns: function(minPercent, maxPercent, maxDescentLevel) - { - if (minPercent) - minPercent = Math.min(minPercent, Math.floor(100 / this._columnCount)); - var widths = {}; - var columns = this.columns; - for (var columnIdentifier in columns) - widths[columnIdentifier] = (columns[columnIdentifier].title || "").length; - - var children = maxDescentLevel ? this._enumerateChildren(this, [], maxDescentLevel + 1) : this.children; - for (var i = 0; i < children.length; ++i) { - var node = children[i]; - for (var columnIdentifier in columns) { - var text = node.data[columnIdentifier] || ""; - if (text.length > widths[columnIdentifier]) - widths[columnIdentifier] = text.length; - } - } - - var totalColumnWidths = 0; - for (var columnIdentifier in columns) - totalColumnWidths += widths[columnIdentifier]; - - var recoupPercent = 0; - for (var columnIdentifier in columns) { - var width = Math.round(100 * widths[columnIdentifier] / totalColumnWidths); - if (minPercent && width < minPercent) { - recoupPercent += (minPercent - width); - width = minPercent; - } else if (maxPercent && width > maxPercent) { - recoupPercent -= (width - maxPercent); - width = maxPercent; - } - widths[columnIdentifier] = width; - } - - while (minPercent && recoupPercent > 0) { - for (var columnIdentifier in columns) { - if (widths[columnIdentifier] > minPercent) { - --widths[columnIdentifier]; - --recoupPercent; - if (!recoupPercent) - break; - } - } - } - - while (maxPercent && recoupPercent < 0) { - for (var columnIdentifier in columns) { - if (widths[columnIdentifier] < maxPercent) { - ++widths[columnIdentifier]; - ++recoupPercent; - if (!recoupPercent) - break; - } - } - } - - for (var columnIdentifier in columns) - columns[columnIdentifier].element.style.width = widths[columnIdentifier] + "%"; - this._columnWidthsInitialized = false; - this.updateLayout(); - }, - - _enumerateChildren: function(rootNode, result, maxLevel) - { - if (!rootNode.root) - result.push(rootNode); - if (!maxLevel) - return; - for (var i = 0; i < rootNode.children.length; ++i) - this._enumerateChildren(rootNode.children[i], result, maxLevel - 1); - return result; - }, - - // Updates the widths of the table, including the positions of the column - // resizers. - // - // IMPORTANT: This function MUST be called once after the element of the - // DataGrid is attached to its parent element and every subsequent time the - // width of the parent element is changed in order to make it possible to - // resize the columns. - // - // If this function is not called after the DataGrid is attached to its - // parent element, then the DataGrid's columns will not be resizable. - updateLayout: function() - { - // Do not attempt to use offsetes if we're not attached to the document tree yet. - if (!this._columnWidthsInitialized && this.element.offsetWidth) { - // Give all the columns initial widths now so that during a resize, - // when the two columns that get resized get a percent value for - // their widths, all the other columns already have percent values - // for their widths. - var headerTableColumns = this._headerTableColumnGroup.children; - var tableWidth = this._dataTable.offsetWidth; - var numColumns = headerTableColumns.length; - for (var i = 0; i < numColumns; i++) { - var headerCell = this.headerTableBody.rows[0].cells[i] - if (this._isColumnVisible(headerCell.columnIdentifier)) { - var columnWidth = headerCell.offsetWidth; - var percentWidth = ((columnWidth / tableWidth) * 100) + "%"; - this._headerTableColumnGroup.children[i].style.width = percentWidth; - this._dataTableColumnGroup.children[i].style.width = percentWidth; - } else { - this._headerTableColumnGroup.children[i].style.width = 0; - this._dataTableColumnGroup.children[i].style.width = 0; - } - } - - this._columnWidthsInitialized = true; - } - - this._positionResizers(); - this.dispatchEventToListeners(WebInspector.DataGrid.Event.DidLayout); - }, - - columnWidthsMap: function() - { - var result = {}; - for (var columnIdentifier in this.columns) { - var column = this.columns[columnIdentifier]; - var width = this._headerTableColumnGroup.children[column.ordinal].style.width; - result[columnIdentifier] = parseFloat(width); - } - return result; - }, - - applyColumnWidthsMap: function(columnWidthsMap) - { - for (var columnIdentifier in this.columns) { - var column = this.columns[columnIdentifier]; - var width = (columnWidthsMap[columnIdentifier] || 0) + "%"; - this._headerTableColumnGroup.children[column.ordinal].style.width = width; - this._dataTableColumnGroup.children[column.ordinal].style.width = width; - } - - this.updateLayout(); - }, - - _isColumnVisible: function(columnIdentifier) - { - return !(columnIdentifier in this._hiddenColumns); - }, - - _showColumn: function(columnIdentifier) - { - delete this._hiddenColumns[columnIdentifier]; - }, - - _hideColumn: function(columnIdentifier) - { - this._hiddenColumns[columnIdentifier] = true; - - var column = this.columns[columnIdentifier]; - var columnElement = column.element; - columnElement.style.width = 0; - - var columnBodyElement = column.bodyElement; - columnBodyElement.style.width = 0; - - this._columnWidthsInitialized = false; - }, - - get scrollContainer() - { - return this._scrollContainer; - }, - - isScrolledToLastRow: function() - { - return this._scrollContainer.isScrolledToBottom(); - }, - - scrollToLastRow: function() - { - this._scrollContainer.scrollTop = this._scrollContainer.scrollHeight - this._scrollContainer.offsetHeight; - }, - - _positionResizers: function() - { - var headerTableColumns = this._headerTableColumnGroup.children; - var numColumns = headerTableColumns.length; - var left = 0; - var previousResizer = null; - - // Make n - 1 resizers for n columns. - for (var i = 0; i < numColumns - 1; i++) { - var resizer = this.resizers[i]; - - if (!resizer) { - // This is the first call to updateWidth, so the resizers need - // to be created. - resizer = document.createElement("div"); - resizer.classList.add("data-grid-resizer"); - // This resizer is associated with the column to its right. - resizer.addEventListener("mousedown", this._startResizerDragging.bind(this), false); - this.element.appendChild(resizer); - this.resizers[i] = resizer; - } - - // Get the width of the cell in the first (and only) row of the - // header table in order to determine the width of the column, since - // it is not possible to query a column for its width. - left += this.headerTableBody.rows[0].cells[i].offsetWidth; - - var columnIsVisible = this._isColumnVisible(this._columnsArray[i].identifier); - if (columnIsVisible) { - resizer.style.removeProperty("display"); - resizer.style.left = left + "px"; - resizer.leftNeighboringColumnID = i; - if (previousResizer) - previousResizer.rightNeighboringColumnID = i; - previousResizer = resizer; - } else { - resizer.style.setProperty("display", "none"); - resizer.leftNeighboringColumnID = 0; - resizer.rightNeighboringColumnID = 0; - } - } - if (previousResizer) - previousResizer.rightNeighboringColumnID = numColumns - 1; - }, - - addCreationNode: function(hasChildren) - { - if (this.creationNode) - this.creationNode.makeNormal(); - - var emptyData = {}; - for (var column in this.columns) - emptyData[column] = ''; - this.creationNode = new WebInspector.CreationDataGridNode(emptyData, hasChildren); - this.appendChild(this.creationNode); - }, - - appendChild: function(child) - { - this.insertChild(child, this.children.length); - }, - - insertChild: function(child, index) - { - if (!child) - throw("insertChild: Node can't be undefined or null."); - if (child.parent === this) - throw("insertChild: Node is already a child of this node."); - - if (child.parent) - child.parent.removeChild(child); - - this.children.splice(index, 0, child); - this.hasChildren = true; - - child.parent = this; - child.dataGrid = this.dataGrid; - child._recalculateSiblings(index); - - delete child._depth; - delete child._revealed; - delete child._attached; - child._shouldRefreshChildren = true; - - var current = child.children[0]; - while (current) { - current.dataGrid = this.dataGrid; - delete current._depth; - delete current._revealed; - delete current._attached; - current._shouldRefreshChildren = true; - current = current.traverseNextNode(false, child, true); - } - - if (this.expanded) - child._attach(); - }, - - removeChild: function(child) - { - if (!child) - throw("removeChild: Node can't be undefined or null."); - if (child.parent !== this) - throw("removeChild: Node is not a child of this node."); - - child.deselect(); - child._detach(); - - this.children.remove(child, true); - - if (child.previousSibling) - child.previousSibling.nextSibling = child.nextSibling; - if (child.nextSibling) - child.nextSibling.previousSibling = child.previousSibling; - - child.dataGrid = null; - child.parent = null; - child.nextSibling = null; - child.previousSibling = null; - - if (this.children.length <= 0) - this.hasChildren = false; - - if (this.creationNode === child) - delete this.creationNode; - }, - - removeChildren: function() - { - for (var i = 0; i < this.children.length; ++i) { - var child = this.children[i]; - child.deselect(); - child._detach(); - - child.dataGrid = null; - child.parent = null; - child.nextSibling = null; - child.previousSibling = null; - } - - this.children = []; - this.hasChildren = false; - }, - - removeChildrenRecursive: function() - { - var childrenToRemove = this.children; - - var child = this.children[0]; - while (child) { - if (child.children.length) - childrenToRemove = childrenToRemove.concat(child.children); - child = child.traverseNextNode(false, this, true); - } - - for (var i = 0; i < childrenToRemove.length; ++i) { - child = childrenToRemove[i]; - child.deselect(); - child._detach(); - - child.children = []; - child.dataGrid = null; - child.parent = null; - child.nextSibling = null; - child.previousSibling = null; - } - - this.children = []; - }, - - sortNodes: function(comparator, reverseMode) - { - function comparatorWrapper(a, b) - { - if (a._dataGridNode._data.summaryRow) - return 1; - if (b._dataGridNode._data.summaryRow) - return -1; - - var aDataGirdNode = a._dataGridNode; - var bDataGirdNode = b._dataGridNode; - return reverseMode ? comparator(bDataGirdNode, aDataGirdNode) : comparator(aDataGirdNode, bDataGirdNode); - } - - var tbody = this.dataTableBody; - var tbodyParent = tbody.parentElement; - tbodyParent.removeChild(tbody); - - var childNodes = tbody.childNodes; - var fillerRow = childNodes.lastValue; - - var sortedRows = Array.prototype.slice.call(childNodes, 0, childNodes.length - 1); - sortedRows.sort(comparatorWrapper); - var sortedRowsLength = sortedRows.length; - - tbody.removeChildren(); - var previousSiblingNode = null; - for (var i = 0; i < sortedRowsLength; ++i) { - var row = sortedRows[i]; - var node = row._dataGridNode; - node.previousSibling = previousSiblingNode; - if (previousSiblingNode) - previousSiblingNode.nextSibling = node; - tbody.appendChild(row); - previousSiblingNode = node; - } - if (previousSiblingNode) - previousSiblingNode.nextSibling = null; - - tbody.appendChild(fillerRow); - tbodyParent.appendChild(tbody); - }, - - _keyDown: function(event) - { - if (!this.selectedNode || event.shiftKey || event.metaKey || event.ctrlKey || this._editing) - return; - - var handled = false; - var nextSelectedNode; - if (event.keyIdentifier === "Up" && !event.altKey) { - nextSelectedNode = this.selectedNode.traversePreviousNode(true); - while (nextSelectedNode && !nextSelectedNode.selectable) - nextSelectedNode = nextSelectedNode.traversePreviousNode(true); - handled = nextSelectedNode ? true : false; - } else if (event.keyIdentifier === "Down" && !event.altKey) { - nextSelectedNode = this.selectedNode.traverseNextNode(true); - while (nextSelectedNode && !nextSelectedNode.selectable) - nextSelectedNode = nextSelectedNode.traverseNextNode(true); - handled = nextSelectedNode ? true : false; - } else if (event.keyIdentifier === "Left") { - if (this.selectedNode.expanded) { - if (event.altKey) - this.selectedNode.collapseRecursively(); - else - this.selectedNode.collapse(); - handled = true; - } else if (this.selectedNode.parent && !this.selectedNode.parent.root) { - handled = true; - if (this.selectedNode.parent.selectable) { - nextSelectedNode = this.selectedNode.parent; - handled = nextSelectedNode ? true : false; - } else if (this.selectedNode.parent) - this.selectedNode.parent.collapse(); - } - } else if (event.keyIdentifier === "Right") { - if (!this.selectedNode.revealed) { - this.selectedNode.reveal(); - handled = true; - } else if (this.selectedNode.hasChildren) { - handled = true; - if (this.selectedNode.expanded) { - nextSelectedNode = this.selectedNode.children[0]; - handled = nextSelectedNode ? true : false; - } else { - if (event.altKey) - this.selectedNode.expandRecursively(); - else - this.selectedNode.expand(); - } - } - } else if (event.keyCode === 8 || event.keyCode === 46) { - if (this._deleteCallback) { - handled = true; - this._deleteCallback(this.selectedNode); - } - } else if (isEnterKey(event)) { - if (this._editCallback) { - handled = true; - this._startEditing(this.selectedNode._element.children[0]); - } - } - - if (nextSelectedNode) { - nextSelectedNode.reveal(); - nextSelectedNode.select(); - } - - if (handled) { - event.preventDefault(); - event.stopPropagation(); - } - }, - - expand: function() - { - // This is the root, do nothing. - }, - - collapse: function() - { - // This is the root, do nothing. - }, - - reveal: function() - { - // This is the root, do nothing. - }, - - revealAndSelect: function() - { - // This is the root, do nothing. - }, - - dataGridNodeFromNode: function(target) - { - var rowElement = target.enclosingNodeOrSelfWithNodeName("tr"); - return rowElement && rowElement._dataGridNode; - }, - - dataGridNodeFromPoint: function(x, y) - { - var node = this._dataTable.ownerDocument.elementFromPoint(x, y); - var rowElement = node.enclosingNodeOrSelfWithNodeName("tr"); - return rowElement && rowElement._dataGridNode; - }, - - _clickInHeaderCell: function(event) - { - var cell = event.target.enclosingNodeOrSelfWithNodeName("th"); - if (!cell || !cell.columnIdentifier || !cell.classList.contains("sortable")) - return; - - var sortOrder = this.sortOrder; - - if (this._sortColumnCell) - this._sortColumnCell.removeMatchingStyleClasses("sort-\\w+"); - - if (cell == this._sortColumnCell) { - if (sortOrder === "ascending") - sortOrder = "descending"; - else - sortOrder = "ascending"; - } - - this._sortColumnCell = cell; - - cell.classList.add("sort-" + sortOrder); - - this.dispatchEventToListeners(WebInspector.DataGrid.Event.SortChanged); - }, - - _mouseoverColumnCollapser: function(event) - { - var cell = event.target.enclosingNodeOrSelfWithNodeName("th"); - if (!cell || !cell.collapsesGroup) - return; - - cell.classList.add("mouse-over-collapser"); - }, - - _mouseoutColumnCollapser: function(event) - { - var cell = event.target.enclosingNodeOrSelfWithNodeName("th"); - if (!cell || !cell.collapsesGroup) - return; - - cell.classList.remove("mouse-over-collapser"); - }, - - _clickInColumnCollapser: function(event) - { - var cell = event.target.enclosingNodeOrSelfWithNodeName("th"); - if (!cell || !cell.collapsesGroup) - return; - - this._collapseColumnGroupWithCell(cell); - - event.stopPropagation(); - event.preventDefault(); - }, - - collapseColumnGroup: function(columnGroup) - { - var collapserColumn = null; - for (var columnIdentifier in this.columns) { - var column = this.columns[columnIdentifier]; - if (column.collapsesGroup == columnGroup) { - collapserColumn = column; - break; - } - } - - console.assert(collapserColumn); - if (!collapserColumn) - return; - - var cell = this._headerTableHeaders[collapserColumn.identifier]; - this._collapseColumnGroupWithCell(cell); - }, - - _collapseColumnGroupWithCell: function(cell) - { - var columnsWillCollapse = cell.classList.toggle("collapsed"); - - this.willToggleColumnGroup(cell.collapsesGroup, columnsWillCollapse); - - var showOrHide = columnsWillCollapse ? this._hideColumn : this._showColumn; - for (var columnIdentifier in this.columns) { - var column = this.columns[columnIdentifier]; - if (column.group === cell.collapsesGroup) - showOrHide.call(this, columnIdentifier); - } - - var collapserButton = cell.querySelector(".collapser-button"); - if (collapserButton) - collapserButton.title = columnsWillCollapse ? this._collapserButtonExpandColumnsToolTip() : this._collapserButtonCollapseColumnsToolTip(); - - this.didToggleColumnGroup(cell.collapsesGroup, columnsWillCollapse); - }, - - _collapserButtonCollapseColumnsToolTip: function() - { - return WebInspector.UIString("Collapse columns"); - }, - - _collapserButtonExpandColumnsToolTip: function() - { - return WebInspector.UIString("Expand columns"); - }, - - willToggleColumnGroup: function(columnGroup, willCollapse) - { - // Implemented by subclasses if needed. - }, - - didToggleColumnGroup: function(columnGroup, didCollapse) - { - // Implemented by subclasses if needed. - }, - - isColumnSortColumn: function(columnIdentifier) - { - return this._sortColumnCell === this._headerTableHeaders[columnIdentifier]; - }, - - markColumnAsSortedBy: function(columnIdentifier, sortOrder) - { - if (this._sortColumnCell) - this._sortColumnCell.removeMatchingStyleClasses("sort-\\w+"); - this._sortColumnCell = this._headerTableHeaders[columnIdentifier]; - this._sortColumnCell.classList.add("sort-" + sortOrder); - }, - - headerTableHeader: function(columnIdentifier) - { - return this._headerTableHeaders[columnIdentifier]; - }, - - _generateSortIndicatorImagesIfNeeded: function() - { - if (WebInspector.DataGrid._generatedSortIndicatorImages) - return; - - WebInspector.DataGrid._generatedSortIndicatorImages = true; - - var specifications = {}; - specifications["arrow"] = { - fillColor: [81, 81, 81], - shadowColor: [255, 255, 255, 0.5], - shadowOffsetX: 0, - shadowOffsetY: 1, - shadowBlur: 0 - }; - - generateColoredImagesForCSS("Images/SortIndicatorDownArrow.svg", specifications, 9, 8, "data-grid-sort-indicator-down-"); - generateColoredImagesForCSS("Images/SortIndicatorUpArrow.svg", specifications, 9, 8, "data-grid-sort-indicator-up-"); - }, - - _mouseDownInDataTable: function(event) - { - var gridNode = this.dataGridNodeFromNode(event.target); - if (!gridNode || !gridNode.selectable) - return; - - if (gridNode.isEventWithinDisclosureTriangle(event)) - return; - - if (event.metaKey) { - if (gridNode.selected) - gridNode.deselect(); - else - gridNode.select(); - } else - gridNode.select(); - }, - - _contextMenuInDataTable: function(event) - { - var contextMenu = new WebInspector.ContextMenu(event); - - var gridNode = this.dataGridNodeFromNode(event.target); - if (this.dataGrid._refreshCallback && (!gridNode || gridNode !== this.creationNode)) - contextMenu.appendItem(WebInspector.UIString("Refresh"), this._refreshCallback.bind(this)); - - if (gridNode && gridNode.selectable && !gridNode.isEventWithinDisclosureTriangle(event)) { - contextMenu.appendItem(WebInspector.UIString("Copy Row"), this._copyRow.bind(this, event.target)); - - if (this.dataGrid._editCallback) { - if (gridNode === this.creationNode) - contextMenu.appendItem(WebInspector.UIString("Add New"), this._startEditing.bind(this, event.target)); - else { - var element = event.target.enclosingNodeOrSelfWithNodeName("td"); - var columnIdentifier = element.__columnIdentifier; - var columnTitle = this.dataGrid.columns[columnIdentifier].title; - contextMenu.appendItem(WebInspector.UIString("Edit “%s”").format(columnTitle), this._startEditing.bind(this, event.target)); - } - } - if (this.dataGrid._deleteCallback && gridNode !== this.creationNode) - contextMenu.appendItem(WebInspector.UIString("Delete"), this._deleteCallback.bind(this, gridNode)); - } - - contextMenu.show(); - }, - - _clickInDataTable: function(event) - { - var gridNode = this.dataGridNodeFromNode(event.target); - if (!gridNode || !gridNode.hasChildren) - return; - - if (!gridNode.isEventWithinDisclosureTriangle(event)) - return; - - if (gridNode.expanded) { - if (event.altKey) - gridNode.collapseRecursively(); - else - gridNode.collapse(); - } else { - if (event.altKey) - gridNode.expandRecursively(); - else - gridNode.expand(); - } - }, - - _copyTextForDataGridNode: function(node) - { - var fields = []; - for (var columnIdentifier in node.dataGrid.columns) - fields.push(node.data[columnIdentifier] || ""); - - var tabSeparatedValues = fields.join("\t"); - return tabSeparatedValues; - }, - - handleBeforeCopyEvent: function(event) - { - if (this.selectedNode && window.getSelection().isCollapsed) - event.preventDefault(); - }, - - handleCopyEvent: function(event) - { - if (!this.selectedNode || !window.getSelection().isCollapsed) - return; - - var copyText = this._copyTextForDataGridNode(this.selectedNode); - event.clipboardData.setData("text/plain", copyText); - event.stopPropagation(); - event.preventDefault(); - }, - - _copyRow: function(target) - { - var gridNode = this.dataGridNodeFromNode(target); - if (!gridNode) - return; - - var copyText = this._copyTextForDataGridNode(gridNode); - InspectorFrontendHost.copyText(copyText); - }, - - get resizeMethod() - { - if (typeof this._resizeMethod === "undefined") - return WebInspector.DataGrid.ResizeMethod.Nearest; - return this._resizeMethod; - }, - - set resizeMethod(method) - { - this._resizeMethod = method; - }, - - _startResizerDragging: function(event) - { - if (event.button !== 0 || event.ctrlKey) - return; - - this._currentResizer = event.target; - if (!this._currentResizer.rightNeighboringColumnID) - return; - - WebInspector.elementDragStart(this._currentResizer, this._resizerDragging.bind(this), - this._endResizerDragging.bind(this), event, "col-resize"); - }, - - _resizerDragging: function(event) - { - if (event.button !== 0) - return; - - var resizer = this._currentResizer; - if (!resizer) - return; - - // Constrain the dragpoint to be within the containing div of the - // datagrid. - var dragPoint = event.clientX - this.element.totalOffsetLeft; - // Constrain the dragpoint to be within the space made up by the - // column directly to the left and the column directly to the right. - var leftCellIndex = resizer.leftNeighboringColumnID; - var rightCellIndex = resizer.rightNeighboringColumnID; - var firstRowCells = this.headerTableBody.rows[0].cells; - var leftEdgeOfPreviousColumn = 0; - for (var i = 0; i < leftCellIndex; i++) - leftEdgeOfPreviousColumn += firstRowCells[i].offsetWidth; - - // Differences for other resize methods - if (this.resizeMethod == WebInspector.DataGrid.ResizeMethod.Last) { - rightCellIndex = this.resizers.length; - } else if (this.resizeMethod == WebInspector.DataGrid.ResizeMethod.First) { - leftEdgeOfPreviousColumn += firstRowCells[leftCellIndex].offsetWidth - firstRowCells[0].offsetWidth; - leftCellIndex = 0; - } - - var rightEdgeOfNextColumn = leftEdgeOfPreviousColumn + firstRowCells[leftCellIndex].offsetWidth + firstRowCells[rightCellIndex].offsetWidth; - - // Give each column some padding so that they don't disappear. - var leftMinimum = leftEdgeOfPreviousColumn + this.ColumnResizePadding; - var rightMaximum = rightEdgeOfNextColumn - this.ColumnResizePadding; - - dragPoint = Number.constrain(dragPoint, leftMinimum, rightMaximum); - - resizer.style.left = (dragPoint - this.CenterResizerOverBorderAdjustment) + "px"; - - var percentLeftColumn = (((dragPoint - leftEdgeOfPreviousColumn) / this._dataTable.offsetWidth) * 100) + "%"; - this._headerTableColumnGroup.children[leftCellIndex].style.width = percentLeftColumn; - this._dataTableColumnGroup.children[leftCellIndex].style.width = percentLeftColumn; - - var percentRightColumn = (((rightEdgeOfNextColumn - dragPoint) / this._dataTable.offsetWidth) * 100) + "%"; - this._headerTableColumnGroup.children[rightCellIndex].style.width = percentRightColumn; - this._dataTableColumnGroup.children[rightCellIndex].style.width = percentRightColumn; - - this._positionResizers(); - event.preventDefault(); - this.dispatchEventToListeners(WebInspector.DataGrid.Event.DidLayout); - }, - - _endResizerDragging: function(event) - { - if (event.button !== 0) - return; - - WebInspector.elementDragEnd(event); - this._currentResizer = null; - this.dispatchEventToListeners(WebInspector.DataGrid.Event.DidLayout); - }, - - ColumnResizePadding: 10, - - CenterResizerOverBorderAdjustment: 3, -} - -WebInspector.DataGrid.ResizeMethod = { - Nearest: "nearest", - First: "first", - Last: "last" -}; - -WebInspector.DataGrid.prototype.__proto__ = WebInspector.Object.prototype; - -/** - * @constructor - * @extends {WebInspector.Object} - * @param {boolean=} hasChildren - */ -WebInspector.DataGridNode = function(data, hasChildren) -{ - this._expanded = false; - this._selected = false; - this._shouldRefreshChildren = true; - this._data = data || {}; - this.hasChildren = hasChildren || false; - this.children = []; - this.dataGrid = null; - this.parent = null; - this.previousSibling = null; - this.nextSibling = null; - this.disclosureToggleWidth = 10; -} - -WebInspector.DataGridNode.prototype = { - get selectable() - { - return !this._element || !this._element.classList.contains("hidden"); - }, - - get element() - { - if (this._element) - return this._element; - - if (!this.dataGrid) - return null; - - this._element = document.createElement("tr"); - this._element._dataGridNode = this; - - if (this.hasChildren) - this._element.classList.add("parent"); - if (this.expanded) - this._element.classList.add("expanded"); - if (this.selected) - this._element.classList.add("selected"); - if (this.revealed) - this._element.classList.add("revealed"); - - this.createCells(); - return this._element; - }, - - createCells: function() - { - for (var columnIdentifier in this.dataGrid.columns) { - var cell = this.createCell(columnIdentifier); - this._element.appendChild(cell); - } - }, - - get data() - { - return this._data; - }, - - set data(x) - { - this._data = x || {}; - this.refresh(); - }, - - get revealed() - { - if ("_revealed" in this) - return this._revealed; - - var currentAncestor = this.parent; - while (currentAncestor && !currentAncestor.root) { - if (!currentAncestor.expanded) { - this._revealed = false; - return false; - } - - currentAncestor = currentAncestor.parent; - } - - this._revealed = true; - return true; - }, - - set hasChildren(x) - { - if (this._hasChildren === x) - return; - - this._hasChildren = x; - - if (!this._element) - return; - - if (this._hasChildren) - { - this._element.classList.add("parent"); - if (this.expanded) - this._element.classList.add("expanded"); - } - else - { - this._element.classList.remove("parent"); - this._element.classList.remove("expanded"); - } - }, - - get hasChildren() - { - return this._hasChildren; - }, - - set revealed(x) - { - if (this._revealed === x) - return; - - this._revealed = x; - - if (this._element) { - if (this._revealed) - this._element.classList.add("revealed"); - else - this._element.classList.remove("revealed"); - } - - for (var i = 0; i < this.children.length; ++i) - this.children[i].revealed = x && this.expanded; - }, - - get depth() - { - if ("_depth" in this) - return this._depth; - if (this.parent && !this.parent.root) - this._depth = this.parent.depth + 1; - else - this._depth = 0; - return this._depth; - }, - - get leftPadding() - { - if (typeof(this._leftPadding) === "number") - return this._leftPadding; - - this._leftPadding = this.depth * this.dataGrid.indentWidth; - return this._leftPadding; - }, - - get shouldRefreshChildren() - { - return this._shouldRefreshChildren; - }, - - set shouldRefreshChildren(x) - { - this._shouldRefreshChildren = x; - if (x && this.expanded) - this.expand(); - }, - - get selected() - { - return this._selected; - }, - - set selected(x) - { - if (x) - this.select(); - else - this.deselect(); - }, - - get expanded() - { - return this._expanded; - }, - - set expanded(x) - { - if (x) - this.expand(); - else - this.collapse(); - }, - - refresh: function() - { - if (!this._element || !this.dataGrid) - return; - - this._element.removeChildren(); - this.createCells(); - }, - - updateLayout: function() - { - // Implemented by subclasses if needed. - }, - - createCell: function(columnIdentifier) - { - var cell = document.createElement("td"); - cell.className = columnIdentifier + "-column"; - cell.__columnIdentifier = columnIdentifier; - - var alignment = this.dataGrid.aligned[columnIdentifier]; - if (alignment) - cell.classList.add(alignment); - - var group = this.dataGrid.groups[columnIdentifier]; - if (group) - cell.classList.add("column-group-" + group); - - var div = document.createElement("div"); - var content = this.createCellContent(columnIdentifier, cell); - div.appendChild(content instanceof Node ? content : document.createTextNode(content)); - cell.appendChild(div); - - if (columnIdentifier === this.dataGrid.disclosureColumnIdentifier) { - cell.classList.add("disclosure"); - if (this.leftPadding) - cell.style.setProperty("padding-left", this.leftPadding + "px"); - } - - return cell; - }, - - createCellContent: function(columnIdentifier) - { - return this.data[columnIdentifier] || "\u200b"; // Zero width space to keep the cell from collapsing. - }, - - elementWithColumnIdentifier: function(columnIdentifier) - { - var index = Object.keys(this.dataGrid.columns).indexOf(columnIdentifier); - if (index === -1) - return null; - - return this._element.children[index]; - }, - - // Share these functions with DataGrid. They are written to work with a DataGridNode this object. - appendChild: WebInspector.DataGrid.prototype.appendChild, - insertChild: WebInspector.DataGrid.prototype.insertChild, - removeChild: WebInspector.DataGrid.prototype.removeChild, - removeChildren: WebInspector.DataGrid.prototype.removeChildren, - removeChildrenRecursive: WebInspector.DataGrid.prototype.removeChildrenRecursive, - - _recalculateSiblings: function(myIndex) - { - if (!this.parent) - return; - - var previousChild = (myIndex > 0 ? this.parent.children[myIndex - 1] : null); - - if (previousChild) { - previousChild.nextSibling = this; - this.previousSibling = previousChild; - } else - this.previousSibling = null; - - var nextChild = this.parent.children[myIndex + 1]; - - if (nextChild) { - nextChild.previousSibling = this; - this.nextSibling = nextChild; - } else - this.nextSibling = null; - }, - - collapse: function() - { - if (this._element) - this._element.classList.remove("expanded"); - - this._expanded = false; - - for (var i = 0; i < this.children.length; ++i) - this.children[i].revealed = false; - - this.dispatchEventToListeners("collapsed"); - - if (this.dataGrid) - this.dataGrid.dispatchEventToListeners(WebInspector.DataGrid.Event.CollapsedNode, {dataGridNode: this}); - }, - - collapseRecursively: function() - { - var item = this; - while (item) { - if (item.expanded) - item.collapse(); - item = item.traverseNextNode(false, this, true); - } - }, - - expand: function() - { - if (!this.hasChildren || this.expanded) - return; - - if (this.revealed && !this._shouldRefreshChildren) - for (var i = 0; i < this.children.length; ++i) - this.children[i].revealed = true; - - if (this._shouldRefreshChildren) { - for (var i = 0; i < this.children.length; ++i) - this.children[i]._detach(); - - this.dispatchEventToListeners("populate"); - - if (this._attached) { - for (var i = 0; i < this.children.length; ++i) { - var child = this.children[i]; - if (this.revealed) - child.revealed = true; - child._attach(); - } - } - - delete this._shouldRefreshChildren; - } - - if (this._element) - this._element.classList.add("expanded"); - - this._expanded = true; - - this.dispatchEventToListeners("expanded"); - - if (this.dataGrid) - this.dataGrid.dispatchEventToListeners(WebInspector.DataGrid.Event.ExpandedNode, {dataGridNode: this}); - }, - - expandRecursively: function() - { - var item = this; - while (item) { - item.expand(); - item = item.traverseNextNode(false, this); - } - }, - - reveal: function() - { - var currentAncestor = this.parent; - while (currentAncestor && !currentAncestor.root) { - if (!currentAncestor.expanded) - currentAncestor.expand(); - currentAncestor = currentAncestor.parent; - } - - this.element.scrollIntoViewIfNeeded(false); - - this.dispatchEventToListeners("revealed"); - }, - - /** - * @param {boolean=} supressSelectedEvent - */ - select: function(supressSelectedEvent) - { - if (!this.dataGrid || !this.selectable || this.selected) - return; - - if (this.dataGrid.selectedNode) - this.dataGrid.selectedNode.deselect(); - - this._selected = true; - this.dataGrid.selectedNode = this; - - if (this._element) - this._element.classList.add("selected"); - - if (!supressSelectedEvent) - this.dataGrid.dispatchEventToListeners(WebInspector.DataGrid.Event.SelectedNodeChanged); - }, - - revealAndSelect: function() - { - this.reveal(); - this.select(); - }, - - /** - * @param {boolean=} supressDeselectedEvent - */ - deselect: function(supressDeselectedEvent) - { - if (!this.dataGrid || this.dataGrid.selectedNode !== this || !this.selected) - return; - - this._selected = false; - this.dataGrid.selectedNode = null; - - if (this._element) - this._element.classList.remove("selected"); - - if (!supressDeselectedEvent) - this.dataGrid.dispatchEventToListeners(WebInspector.DataGrid.Event.SelectedNodeChanged); - }, - - traverseNextNode: function(skipHidden, stayWithin, dontPopulate, info) - { - if (!dontPopulate && this.hasChildren) - this.dispatchEventToListeners("populate"); - - if (info) - info.depthChange = 0; - - var node = (!skipHidden || this.revealed) ? this.children[0] : null; - if (node && (!skipHidden || this.expanded)) { - if (info) - info.depthChange = 1; - return node; - } - - if (this === stayWithin) - return null; - - node = (!skipHidden || this.revealed) ? this.nextSibling : null; - if (node) - return node; - - node = this; - while (node && !node.root && !((!skipHidden || node.revealed) ? node.nextSibling : null) && node.parent !== stayWithin) { - if (info) - info.depthChange -= 1; - node = node.parent; - } - - if (!node) - return null; - - return (!skipHidden || node.revealed) ? node.nextSibling : null; - }, - - traversePreviousNode: function(skipHidden, dontPopulate) - { - var node = (!skipHidden || this.revealed) ? this.previousSibling : null; - if (!dontPopulate && node && node.hasChildren) - node.dispatchEventToListeners("populate"); - - while (node && ((!skipHidden || (node.revealed && node.expanded)) ? node.children.lastValue : null)) { - if (!dontPopulate && node.hasChildren) - node.dispatchEventToListeners("populate"); - node = ((!skipHidden || (node.revealed && node.expanded)) ? node.children.lastValue : null); - } - - if (node) - return node; - - if (!this.parent || this.parent.root) - return null; - - return this.parent; - }, - - isEventWithinDisclosureTriangle: function(event) - { - if (!this.hasChildren) - return false; - var cell = event.target.enclosingNodeOrSelfWithNodeName("td"); - if (!cell.classList.contains("disclosure")) - return false; - - var left = cell.totalOffsetLeft + this.leftPadding; - return event.pageX >= left && event.pageX <= left + this.disclosureToggleWidth; - }, - - _attach: function() - { - if (!this.dataGrid || this._attached) - return; - - this._attached = true; - - var nextElement = null; - - var previousGridNode = this.traversePreviousNode(true, true); - if (previousGridNode && previousGridNode.element.parentNode) - nextElement = previousGridNode.element.nextSibling; - else if (!previousGridNode) - nextElement = this.dataGrid.dataTableBody.firstChild; - - // If there is no next grid node, then append before the last child since the last child is the filler row. - console.assert(this.dataGrid.dataTableBody.lastChild.classList.contains("filler")); - if (!nextElement) - nextElement = this.dataGrid.dataTableBody.lastChild; - - this.dataGrid.dataTableBody.insertBefore(this.element, nextElement); - - if (this.expanded) - for (var i = 0; i < this.children.length; ++i) - this.children[i]._attach(); - }, - - _detach: function() - { - if (!this._attached) - return; - - this._attached = false; - - if (this._element && this._element.parentNode) - this._element.parentNode.removeChild(this._element); - - for (var i = 0; i < this.children.length; ++i) - this.children[i]._detach(); - }, - - savePosition: function() - { - if (this._savedPosition) - return; - - if (!this.parent) - throw("savePosition: Node must have a parent."); - this._savedPosition = { - parent: this.parent, - index: this.parent.children.indexOf(this) - }; - }, - - restorePosition: function() - { - if (!this._savedPosition) - return; - - if (this.parent !== this._savedPosition.parent) - this._savedPosition.parent.insertChild(this, this._savedPosition.index); - - delete this._savedPosition; - } -} - -WebInspector.DataGridNode.prototype.__proto__ = WebInspector.Object.prototype; - -/** - * @constructor - * @extends {WebInspector.DataGridNode} - */ -WebInspector.CreationDataGridNode = function(data, hasChildren) -{ - WebInspector.DataGridNode.call(this, data, hasChildren); - this.isCreationNode = true; -} - -WebInspector.CreationDataGridNode.prototype = { - makeNormal: function() - { - delete this.isCreationNode; - delete this.makeNormal; - } -} - -WebInspector.CreationDataGridNode.prototype.__proto__ = WebInspector.DataGridNode.prototype; diff --git a/Source/WebInspectorUI/UserInterface/DatabaseContentView.css b/Source/WebInspectorUI/UserInterface/DatabaseContentView.css deleted file mode 100644 index 4cada73ec..000000000 --- a/Source/WebInspectorUI/UserInterface/DatabaseContentView.css +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.storage-view { - /* Added so fonts look good */ - font-family: Menlo, monospace; - font-size: 11px; -} - -.storage-view .data-grid { - border: none; - height: 100%; -} - -.storage-view .storage-table-error { - color: rgb(66%, 33%, 33%); -} - -.storage-view.query { - padding: 2px 0; - overflow-y: overlay; - overflow-x: hidden; - -webkit-text-size-adjust: auto; -} - -.database-query-prompt { - position: relative; - padding: 4px 22px 4px 11px; - min-height: 16px; - white-space: pre-wrap; - -webkit-user-modify: read-write-plaintext-only; - -webkit-user-select: text; - - /* Added to remove outline */ - outline: none; -} - -.database-user-query::before, .database-query-prompt::before, .database-query-result::before { - position: absolute; - display: block; - z-index: 1; - content: ""; - left: 4px; - top: 10px; - width: 10px; - height: 10px; - margin-top: -5px; - -webkit-user-select: none; -} - -.database-query-prompt::before { - background-image: url(Images/UserInputPrompt.svg); -} - -.database-user-query { - position: relative; - border-bottom: 1px solid rgb(245, 245, 245); - padding: 4px 22px 4px 18px; - min-height: 16px; -} - -.database-user-query::before { - background-image: url(Images/UserInputPromptPrevious.svg); -} - -.database-query-text { - color: rgb(0, 128, 255); - -webkit-user-select: text; -} - -.database-query-result { - position: relative; - padding: 4px 0 1px 18px; - min-height: 16px; - margin-left: -18px; -} - -.database-query-result.error { - color: red; - -webkit-user-select: text; -} - -.database-query-result.error::before { - background-image: url(Images/Error.svg); - background-size: 10px 10px; -} diff --git a/Source/WebInspectorUI/UserInterface/DatabaseContentView.js b/Source/WebInspectorUI/UserInterface/DatabaseContentView.js deleted file mode 100644 index 597d614cf..000000000 --- a/Source/WebInspectorUI/UserInterface/DatabaseContentView.js +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.DatabaseContentView = function(representedObject) -{ - WebInspector.ContentView.call(this, representedObject); - - this.database = representedObject; - - this.element.classList.add("storage-view"); - this.element.classList.add("query"); - this.element.classList.add("monospace"); - - this._promptElement = document.createElement("div"); - this._promptElement.className = "database-query-prompt"; - this.element.appendChild(this._promptElement); - - this.prompt = new WebInspector.ConsolePrompt(this, "text/x-sql"); - this._promptElement.appendChild(this.prompt.element); - - this.element.addEventListener("click", this._messagesClicked.bind(this), true); -} - -WebInspector.DatabaseContentView.Event = { - SchemaUpdated: "SchemaUpdated" -}; - -WebInspector.DatabaseContentView.prototype = { - constructor: WebInspector.DatabaseContentView, - - // Public - - shown: function() - { - this.prompt.shown(); - }, - - updateLayout: function() - { - this.prompt.updateLayout(); - - var results = this.element.querySelectorAll(".database-query-result"); - for (var i = 0; i < results.length; ++i) { - var resultElement = results[i]; - if (resultElement.dataGrid) - resultElement.dataGrid.updateLayout(); - } - }, - - saveToCookie: function(cookie) - { - cookie.type = WebInspector.ContentViewCookieType.Database; - cookie.host = this.representedObject.host; - cookie.name = this.representedObject.name; - }, - - consolePromptCompletionsNeeded: function(prompt, defaultCompletions, base, prefix, suffix) - { - var results = []; - - prefix = prefix.toLowerCase(); - - function accumulateMatches(textArray) - { - for (var i = 0; i < textArray.length; ++i) { - var lowerCaseText = textArray[i].toLowerCase(); - if (lowerCaseText.startsWith(prefix)) - results.push(textArray[i]); - } - } - - function tableNamesCallback(tableNames) - { - accumulateMatches(tableNames); - accumulateMatches(["SELECT", "FROM", "WHERE", "LIMIT", "DELETE FROM", "CREATE", "DROP", "TABLE", "INDEX", "UPDATE", "INSERT INTO", "VALUES"]); - - this.prompt.updateCompletions(results, " "); - } - - this.database.getTableNames(tableNamesCallback.bind(this)); - }, - - consolePromptTextCommitted: function(prompt, query) - { - this.database.executeSQL(query, this._queryFinished.bind(this, query), this._queryError.bind(this, query)); - }, - - // Private - - _messagesClicked: function() - { - this.prompt.focus(); - }, - - _queryFinished: function(query, columnNames, values) - { - var dataGrid = WebInspector.DataGrid.createSortableDataGrid(columnNames, values); - var trimmedQuery = query.trim(); - - if (dataGrid) { - dataGrid.element.classList.add("inline"); - this._appendViewQueryResult(trimmedQuery, dataGrid); - dataGrid.autoSizeColumns(5); - } - - if (trimmedQuery.match(/^create /i) || trimmedQuery.match(/^drop table /i)) - this.dispatchEventToListeners(WebInspector.DatabaseContentView.Event.SchemaUpdated, this.database); - }, - - _queryError: function(query, error) - { - if (error.message) - var message = error.message; - else if (error.code == 2) - var message = WebInspector.UIString("Database no longer has expected version."); - else - var message = WebInspector.UIString("An unexpected error %s occurred.").format(error.code); - - this._appendErrorQueryResult(query, message); - }, - - /** - * @param {string} query - * @param {WebInspector.View} view - */ - _appendViewQueryResult: function(query, view) - { - var resultElement = this._appendQueryResult(query); - - // Add our DataGrid with the results to the database query result div. - resultElement.dataGrid = view; - resultElement.appendChild(view.element); - - this._promptElement.scrollIntoView(false); - }, - - /** - * @param {string} query - * @param {string} errorText - */ - _appendErrorQueryResult: function(query, errorText) - { - var resultElement = this._appendQueryResult(query); - resultElement.classList.add("error"); - resultElement.textContent = errorText; - - this._promptElement.scrollIntoView(false); - }, - - _appendQueryResult: function(query) - { - var element = document.createElement("div"); - element.className = "database-user-query"; - this.element.insertBefore(element, this._promptElement); - - var commandTextElement = document.createElement("span"); - commandTextElement.className = "database-query-text"; - commandTextElement.textContent = query; - element.appendChild(commandTextElement); - - var resultElement = document.createElement("div"); - resultElement.className = "database-query-result"; - element.appendChild(resultElement); - return resultElement; - } -} - -WebInspector.DatabaseContentView.prototype.__proto__ = WebInspector.ContentView.prototype; diff --git a/Source/WebInspectorUI/UserInterface/DatabaseHostTreeElement.js b/Source/WebInspectorUI/UserInterface/DatabaseHostTreeElement.js deleted file mode 100644 index 5a52d2013..000000000 --- a/Source/WebInspectorUI/UserInterface/DatabaseHostTreeElement.js +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.DatabaseHostTreeElement = function(host) -{ - WebInspector.StorageTreeElement.call(this, WebInspector.FolderTreeElement.FolderIconStyleClassName, WebInspector.displayNameForHost(host), null); - - this._host = host; - - this.hasChildren = true; -}; - -WebInspector.DatabaseHostTreeElement.prototype = { - constructor: WebInspector.DatabaseHostTreeElement, - - // Public - - get name() - { - return WebInspector.displayNameForHost(this._host); - }, - - get categoryName() - { - return WebInspector.UIString("Databases"); - } -}; - -WebInspector.DatabaseHostTreeElement.prototype.__proto__ = WebInspector.StorageTreeElement.prototype; diff --git a/Source/WebInspectorUI/UserInterface/DatabaseIcon.css b/Source/WebInspectorUI/UserInterface/DatabaseIcon.css deleted file mode 100644 index d0dcdbc42..000000000 --- a/Source/WebInspectorUI/UserInterface/DatabaseIcon.css +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.database-icon .icon { - content: -webkit-image-set(url(Images/Database.png) 1x, url(Images/Database@2x.png) 2x); -} diff --git a/Source/WebInspectorUI/UserInterface/DatabaseObject.js b/Source/WebInspectorUI/UserInterface/DatabaseObject.js deleted file mode 100644 index 018159767..000000000 --- a/Source/WebInspectorUI/UserInterface/DatabaseObject.js +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.DatabaseObject = function(id, host, name, version) -{ - this._id = id; - this._host = host ? host : WebInspector.UIString("Local File"); - this._name = name; - this._version = version; -}; - -WebInspector.DatabaseObject.TypeIdentifier = "database"; -WebInspector.DatabaseObject.HostCookieKey = "database-object-host"; -WebInspector.DatabaseObject.NameCookieKey = "database-object-name"; - -WebInspector.DatabaseObject.prototype = { - constructor: WebInspector.DatabaseObject, - - // Public - - get id() - { - return this._id; - }, - - get host() - { - return this._host; - }, - - get name() - { - return this._name; - }, - - get version() - { - return this._version; - }, - - saveIdentityToCookie: function(cookie) - { - cookie[WebInspector.DatabaseObject.HostCookieKey] = this.host; - cookie[WebInspector.DatabaseObject.NameCookieKey] = this.name; - }, - - getTableNames: function(callback) - { - function sortingCallback(error, names) - { - if (!error) - callback(names.sort()); - } - - DatabaseAgent.getDatabaseTableNames(this._id, sortingCallback); - }, - - executeSQL: function(query, successCallback, errorCallback) - { - function queryCallback(columnNames, values, sqlError) - { - if (sqlError) { - var message; - - switch (sqlError.code) { - case SQLException.VERSION_ERR: - message = WebInspector.UIString("Database no longer has expected version."); - break; - case SQLException.TOO_LARGE_ERR: - message = WebInspector.UIString("Data returned from the database is too large."); - break; - default: - message = WebInspector.UIString("An unexpected error occurred."); - break; - } - - errorCallback(message); - return; - } - - successCallback(columnNames, values); - } - - function callback(error, result) - { - if (error) { - errorCallback(WebInspector.UIString("An unexpected error occurred.")); - return; - } - - // COMPATIBILITY (iOS 6): Newer versions of DatabaseAgent.executeSQL can delay before - // sending the results. The version on iOS 6 instead returned a transactionId that - // would be used later in the sqlTransactionSucceeded or sqlTransactionFailed events. - if ("transactionId" in result) { - if (!result.success) { - errorCallback(WebInspector.UIString("An unexpected error occurred.")); - return; - } - - WebInspector.DatabaseObserver._callbacks[result.transactionId] = queryCallback; - return; - } - - queryCallback(result.columnNames, result.values, result.sqlError); - } - - // COMPATIBILITY (iOS 6): Since the parameters of the DatabaseAgent.executeSQL callback differ - // we need the result object to lookup parameters by name. - callback.expectsResultObject = true; - - DatabaseAgent.executeSQL(this._id, query, callback); - } -}; diff --git a/Source/WebInspectorUI/UserInterface/DatabaseObserver.js b/Source/WebInspectorUI/UserInterface/DatabaseObserver.js deleted file mode 100644 index bc134ae80..000000000 --- a/Source/WebInspectorUI/UserInterface/DatabaseObserver.js +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.DatabaseObserver = function() -{ - WebInspector.Object.call(this); -}; - -WebInspector.DatabaseObserver._callbacks = {}; - -WebInspector.DatabaseObserver.prototype = { - constructor: WebInspector.DatabaseObserver, - - // Events defined by the "Database" domain. - - addDatabase: function(database) - { - WebInspector.storageManager.databaseWasAdded(database.id, database.domain, database.name, database.version); - }, - - // COMPATIBILITY (iOS 6): This event was removed in favor of a more async DatabaseAgent.executeSQL. - sqlTransactionSucceeded: function(transactionId, columnNames, values) - { - if (!WebInspector.DatabaseObserver._callbacks[transactionId]) - return; - - var callback = WebInspector.DatabaseObserver._callbacks[transactionId]; - delete WebInspector.DatabaseObserver._callbacks[transactionId]; - - if (callback) - callback(columnNames, values, null); - }, - - // COMPATIBILITY (iOS 6): This event was removed in favor of a more async DatabaseAgent.executeSQL. - sqlTransactionFailed: function(transactionId, sqlError) - { - if (!WebInspector.DatabaseObserver._callbacks[transactionId]) - return; - - var callback = WebInspector.DatabaseObserver._callbacks[transactionId]; - delete WebInspector.DatabaseObserver._callbacks[transactionId]; - - if (callback) - callback(null, null, sqlError); - } -}; - -WebInspector.DatabaseObserver.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/DatabaseTableContentView.css b/Source/WebInspectorUI/UserInterface/DatabaseTableContentView.css deleted file mode 100644 index b25a67390..000000000 --- a/Source/WebInspectorUI/UserInterface/DatabaseTableContentView.css +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.content-view.database-table > .data-grid { - position: absolute; - top: 0; - left: 0; - right: 0; - bottom: 0; - border: none; -} diff --git a/Source/WebInspectorUI/UserInterface/DatabaseTableContentView.js b/Source/WebInspectorUI/UserInterface/DatabaseTableContentView.js deleted file mode 100644 index 699917d3b..000000000 --- a/Source/WebInspectorUI/UserInterface/DatabaseTableContentView.js +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.DatabaseTableContentView = function(representedObject) -{ - WebInspector.ContentView.call(this, representedObject); - - this.element.classList.add(WebInspector.DatabaseTableContentView.StyleClassName); - - this.update(); -}; - -WebInspector.DatabaseTableContentView.StyleClassName = "database-table"; - -WebInspector.DatabaseTableContentView.prototype = { - constructor: WebInspector.DatabaseTableContentView, - - // Public - - update: function() - { - this.representedObject.database.executeSQL("SELECT * FROM \"" + this._escapeTableName(this.representedObject.name) + "\"", this._queryFinished.bind(this), this._queryError.bind(this)); - }, - - updateLayout: function() - { - if (this._dataGrid) - this._dataGrid.updateLayout(); - }, - - saveToCookie: function(cookie) - { - cookie.type = WebInspector.ContentViewCookieType.DatabaseTable; - cookie.host = this.representedObject.host; - cookie.name = this.representedObject.name; - cookie.database = this.representedObject.database.name; - }, - - get scrollableElements() - { - if (!this._dataGrid) - return []; - return [this._dataGrid.scrollContainer]; - }, - - // Private - - _escapeTableName: function(name) - { - return name.replace(/\"/g, "\"\""); - }, - - _queryFinished: function(columnNames, values) - { - // It would be nice to do better than creating a new data grid each time the table is updated, but the table updating - // doesn't happen very frequently. Additionally, using DataGrid's createSortableDataGrid makes our code much cleaner and it knows - // how to sort arbitrary columns. - this.element.removeChildren(); - - this._dataGrid = new WebInspector.DataGrid.createSortableDataGrid(columnNames, values); - if (!this._dataGrid || !this._dataGrid.element) { - // If the DataGrid is empty, then we were returned a table with no columns. This can happen when a table has - // no data, the SELECT query only returns column names when there is data. - this.element.removeChildren(); - this.element.appendChild(WebInspector.createMessageTextView(WebInspector.UIString("The “%s”\ntable is empty.").format(this.representedObject.name), false)); - return; - } - - this.element.appendChild(this._dataGrid.element); - this._dataGrid.updateLayout(); - }, - - _queryError: function(error) - { - this.element.removeChildren(); - this.element.appendChild(WebInspector.createMessageTextView(WebInspector.UIString("An error occured trying to\nread the “%s” table.").format(this.representedObject.name), true)); - } -}; - -WebInspector.DatabaseTableContentView.prototype.__proto__ = WebInspector.ContentView.prototype; diff --git a/Source/WebInspectorUI/UserInterface/DatabaseTableIcon.css b/Source/WebInspectorUI/UserInterface/DatabaseTableIcon.css deleted file mode 100644 index 15408948e..000000000 --- a/Source/WebInspectorUI/UserInterface/DatabaseTableIcon.css +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.database-table-icon .icon { - content: -webkit-image-set(url(Images/DatabaseTable.png) 1x, url(Images/DatabaseTable@2x.png) 2x); -} diff --git a/Source/WebInspectorUI/UserInterface/DatabaseTableObject.js b/Source/WebInspectorUI/UserInterface/DatabaseTableObject.js deleted file mode 100644 index 5e61d258e..000000000 --- a/Source/WebInspectorUI/UserInterface/DatabaseTableObject.js +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.DatabaseTableObject = function(name, database) -{ - console.assert(database instanceof WebInspector.DatabaseObject); - - this._name = name; - this._database = database; -}; - -WebInspector.DatabaseTableObject.TypeIdentifier = "database-table"; -WebInspector.DatabaseTableObject.NameCookieKey = "database-table-object-name"; - -WebInspector.DatabaseTableObject.prototype = { - constructor: WebInspector.DatabaseTableObject, - - get name() - { - return this._name; - }, - - get database() - { - return this._database; - }, - - saveIdentityToCookie: function(cookie) - { - cookie[WebInspector.DatabaseTableObject.NameCookieKey] = this.name; - }, -}; - -WebInspector.DatabaseTableObject.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/DatabaseTableTreeElement.js b/Source/WebInspectorUI/UserInterface/DatabaseTableTreeElement.js deleted file mode 100644 index b4a5d4696..000000000 --- a/Source/WebInspectorUI/UserInterface/DatabaseTableTreeElement.js +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.DatabaseTableTreeElement = function(representedObject) -{ - console.assert(representedObject instanceof WebInspector.DatabaseTableObject); - - WebInspector.GeneralTreeElement.call(this, WebInspector.DatabaseTableTreeElement.DatabaseTableIconStyleClassName, representedObject.name, null, representedObject, false); - - this.small = true; -}; - -WebInspector.DatabaseTableTreeElement.DatabaseTableIconStyleClassName = "database-table-icon"; - -WebInspector.DatabaseTableTreeElement.prototype = { - constructor: WebInspector.DatabaseTableTreeElement -}; - -WebInspector.DatabaseTableTreeElement.prototype.__proto__ = WebInspector.GeneralTreeElement.prototype; diff --git a/Source/WebInspectorUI/UserInterface/DatabaseTreeElement.js b/Source/WebInspectorUI/UserInterface/DatabaseTreeElement.js deleted file mode 100644 index cb4799e9e..000000000 --- a/Source/WebInspectorUI/UserInterface/DatabaseTreeElement.js +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.DatabaseTreeElement = function(representedObject) -{ - console.assert(representedObject instanceof WebInspector.DatabaseObject); - - WebInspector.GeneralTreeElement.call(this, WebInspector.DatabaseTreeElement.DatabaseIconStyleClassName, representedObject.name, null, representedObject, true); - - this.small = true; - this.hasChildren = false; - - // Since we are initially telling the tree element we don't have any children, make sure that we try to populate - // the tree element (which will get a list of tables) when the element is created. - this.onpopulate(); -}; - -WebInspector.DatabaseTreeElement.DatabaseIconStyleClassName = "database-icon"; - -WebInspector.DatabaseTreeElement.prototype = { - constructor: WebInspector.DatabaseTreeElement, - - // Overrides from TreeElement (Private) - - oncollapse: function() - { - this.shouldRefreshChildren = true; - }, - - onpopulate: function() - { - if (this.children.length && !this.shouldRefreshChildren) - return; - - this.shouldRefreshChildren = false; - - this.removeChildren(); - - function tableNamesCallback(tableNames) - { - for (var i = 0; i < tableNames.length; ++i) { - var databaseTable = new WebInspector.DatabaseTableObject(tableNames[i], this.representedObject); - this.appendChild(new WebInspector.DatabaseTableTreeElement(databaseTable)); - } - - this.hasChildren = tableNames.length; - } - - this.representedObject.getTableNames(tableNamesCallback.bind(this)); - } -}; - -WebInspector.DatabaseTreeElement.prototype.__proto__ = WebInspector.GeneralTreeElement.prototype; diff --git a/Source/WebInspectorUI/UserInterface/Debug/Bootstrap.js b/Source/WebInspectorUI/UserInterface/Debug/Bootstrap.js new file mode 100644 index 000000000..f54d93ae7 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Debug/Bootstrap.js @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2015 University of Washington. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +// This function is invoked after the inspector has loaded. +WebInspector.runBootstrapOperations = function() { + WebInspector.showDebugUISetting = new WebInspector.Setting("show-debug-ui", false); + + // Toggle Debug UI setting. + new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.Option | WebInspector.KeyboardShortcut.Modifier.Shift | WebInspector.KeyboardShortcut.Modifier.CommandOrControl, "D", () => { + WebInspector.showDebugUISetting.value = !WebInspector.showDebugUISetting.value; + }); + + // Reload the Web Inspector. + new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.Option | WebInspector.KeyboardShortcut.Modifier.Shift | WebInspector.KeyboardShortcut.Modifier.CommandOrControl, "R", () => { + window.location.reload(); + }); + + let toolTip = "Enable dump inspector messages to console"; + let activatedToolTip = "Disable dump inspector messages to console"; + let debugInspectorToolbarButton = new WebInspector.ActivateButtonToolbarItem("debug-inspector", toolTip, activatedToolTip, null, "Images/Console.svg"); + debugInspectorToolbarButton.activated = InspectorBackend.dumpInspectorProtocolMessages; + WebInspector.toolbar.addToolbarItem(debugInspectorToolbarButton, WebInspector.Toolbar.Section.CenterRight); + debugInspectorToolbarButton.addEventListener(WebInspector.ButtonNavigationItem.Event.Clicked, () => { + InspectorBackend.dumpInspectorProtocolMessages = !InspectorBackend.dumpInspectorProtocolMessages; + debugInspectorToolbarButton.activated = InspectorBackend.dumpInspectorProtocolMessages; + }); + + function updateDebugUI() + { + debugInspectorToolbarButton.hidden = !WebInspector.showDebugUISetting.value; + } + + WebInspector.showDebugUISetting.addEventListener(WebInspector.Setting.Event.Changed, () => { + updateDebugUI(); + WebInspector.notifications.dispatchEventToListeners(WebInspector.Notification.DebugUIEnabledDidChange); + }); + + updateDebugUI(); +}; diff --git a/Source/WebInspectorUI/UserInterface/Debug/CapturingProtocolTracer.js b/Source/WebInspectorUI/UserInterface/Debug/CapturingProtocolTracer.js new file mode 100644 index 000000000..f44754a8e --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Debug/CapturingProtocolTracer.js @@ -0,0 +1,89 @@ +/* + * Copyright (C) 2016 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.CapturingProtocolTracer = class CapturingProtocolTracer extends WebInspector.ProtocolTracer +{ + constructor() + { + super(); + + this._trace = new WebInspector.ProtocolTrace; + } + + // Public + + get trace() + { + return this._trace; + } + + logFrontendException(message, exception) + { + this._processEntry({type: "exception", message: this._stringifyMessage(message), exception}); + } + + logProtocolError(message, error) + { + this._processEntry({type: "error", message: this._stringifyMessage(message), error}); + } + + logFrontendRequest(message) + { + this._processEntry({type: "request", message: this._stringifyMessage(message)}); + } + + logDidHandleResponse(message, timings = null) + { + let entry = {type: "response", message: this._stringifyMessage(message)}; + if (timings) + entry.timings = Object.shallowCopy(timings); + + this._processEntry(entry); + } + + logDidHandleEvent(message, timings = null) + { + let entry = {type: "event", message: this._stringifyMessage(message)}; + if (timings) + entry.timings = Object.shallowCopy(timings); + + this._processEntry(entry); + } + + _stringifyMessage(message) + { + try { + return JSON.stringify(message); + } catch (e) { + console.error("couldn't stringify object:", message, e); + return {}; + } + } + + _processEntry(entry) + { + this._trace.addEntry(entry); + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Debug/ProtocolTrace.js b/Source/WebInspectorUI/UserInterface/Debug/ProtocolTrace.js new file mode 100644 index 000000000..a26a965d8 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Debug/ProtocolTrace.js @@ -0,0 +1,56 @@ +/* + * Copyright (C) 2016 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.ProtocolTrace = class ProtocolTrace extends WebInspector.Object +{ + constructor() + { + super(); + + this._entries = []; + } + + // Public + + addEntry(entry) { + this._entries.push(entry); + } + + get saveData() { + let now = new Date(); + let YYYY = now.getFullYear(); + let MM = now.getMonth() + 1; + let DD = now.getDate(); + let hh = now.getHours(); + let mm = now.getMinutes(); + let ss = now.getSeconds(); + + // This follows the file name of screen shots on OS X (en-US): + // "Protocol Trace 2015-12-31 at 12.43.04.json". + // When the Intl API is implemented, we can do a better job. + let filename = WebInspector.unlocalizedString(`Protocol Trace at ${YYYY}-${MM}-${DD} ${hh}.${mm}.${ss}.json`); + return {url: "web-inspector:///" + encodeURIComponent(filename), content: JSON.stringify(this._entries)}; + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Debug/UncaughtExceptionReporter.css b/Source/WebInspectorUI/UserInterface/Debug/UncaughtExceptionReporter.css new file mode 100644 index 000000000..8b7e01dd0 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Debug/UncaughtExceptionReporter.css @@ -0,0 +1,114 @@ +/* + * Copyright (C) 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +.sheet-container { + position: absolute; + left: 0; + right: 0; + top: 0; + bottom: 0; + z-index: var(--z-index-uncaught-exception-sheet); + background-color: hsl(0, 0%, 96%); + overflow: scroll; +} + +.uncaught-exception-sheet { + padding: 50px 55px 50px 65px; + font-family: '-webkit-system-font'; + font-size: 11pt; + min-width: 400px; + color: hsl(0, 0%, 40%); +} + +.uncaught-exception-sheet a { + text-decoration: underline; + color: hsl(240, 55%, 30%); + cursor: pointer; + font-weight: 500; + font-size: 97%; +} +.uncaught-exception-sheet a:hover, +.uncaught-exception-sheet a:active { + color: hsl(240, 55%, 25%); +} + +.uncaught-exception-sheet h1, +.uncaught-exception-sheet h2 { + font-size: 24px; + line-height: 28px; + margin-bottom: 0px; + margin-top: 10px; + font-weight: normal; +} + +.uncaught-exception-sheet h2 { + margin-top: 40px; +} + +.uncaught-exception-sheet h1 > img { + height: 35px; + position: relative; + margin-left: -50px; + margin-top: -5px; + float: left; +} + +.uncaught-exception-sheet h2 > img { + height: 25px; + position: relative; + margin-left: -45px; + margin-top: 0px; + float: left; +} + +.uncaught-exception-sheet dl { + max-width: 600px; +} + +.uncaught-exception-sheet dt { + font-style: italic; + font-size: 17px; +} + +.uncaught-exception-sheet dd { + margin: 10px 0 20px 10px; + font-size: 13px; + line-height: 18px; +} + +.uncaught-exception-sheet ul { + font-family: Menlo, monospace; + font-size: 12px; + line-height: 18px; + margin: 0 0 0 2px; + padding: 0; +} + +.uncaught-exception-sheet li { + margin-bottom: 20px; + word-break: break-word; + -webkit-user-select: text; + white-space: pre; +} diff --git a/Source/WebInspectorUI/UserInterface/Debug/UncaughtExceptionReporter.js b/Source/WebInspectorUI/UserInterface/Debug/UncaughtExceptionReporter.js new file mode 100644 index 000000000..43ce09db6 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Debug/UncaughtExceptionReporter.js @@ -0,0 +1,275 @@ +/* + * Copyright (C) 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +(function() { + +const windowEvents = ["beforecopy", "copy", "click", "dragover", "focus"]; +const documentEvents = ["focus", "blur", "resize", "keydown", "keyup", "mousemove", "pagehide", "contextmenu"]; + +function stopEventPropagation(event) { + if (event.target.classList && event.target.classList.contains("bypass-event-blocking")) + return; + + event.stopPropagation(); +} + +function blockEventHandlers() { + // FIXME (151959): text selection on the sheet doesn't work for some reason. + for (let name of windowEvents) + window.addEventListener(name, stopEventPropagation, true); + for (let name of documentEvents) + document.addEventListener(name, stopEventPropagation, true); +} + +function unblockEventHandlers() { + for (let name of windowEvents) + window.removeEventListener(name, stopEventPropagation, true); + for (let name of documentEvents) + document.removeEventListener(name, stopEventPropagation, true); +} + +function handleError(error) { + handleUncaughtExceptionRecord({ + message: error.message, + url: parseURL(error.sourceURL).lastPathComponent, + lineNumber: error.line, + columnNumber: error.column, + stack: error.stack, + details: error.details, + }); +} + +function handleUncaughtException(event) { + handleUncaughtExceptionRecord({ + message: event.message, + url: parseURL(event.filename).lastPathComponent, + lineNumber: event.lineno, + columnNumber: event.colno, + stack: typeof event.error === "object" && event.error !== null ? event.error.stack : null, + }); +} + +function handleUncaughtExceptionRecord(exceptionRecord) { + if (!window.__uncaughtExceptions) + window.__uncaughtExceptions = []; + + const loadCompleted = window.__frontendCompletedLoad; + const isFirstException = !window.__uncaughtExceptions.length; + + // If an uncaught exception happens after loading is done, only show + // the first such exception. Many others may follow if internal + // state has been corrupted, but these are unhelpful to report. + if (!loadCompleted || isFirstException) + window.__uncaughtExceptions.push(exceptionRecord); + + // If WebInspector.contentLoaded throws an uncaught exception, then these + // listeners will not work correctly because the UI is not fully loaded. + // Prevent any event handlers from running in an inconsistent state. + if (isFirstException) + blockEventHandlers(); + + if (isFirstException && !loadCompleted) { + // Signal that loading is done even though we can't guarantee that + // evaluating code on the inspector page will do anything useful. + // Without this, the frontend host may never show the window. + if (InspectorFrontendHost) + InspectorFrontendHost.loaded(); + + // Don't tell InspectorFrontendAPI that loading is done, since it can + // clear some of the error boilerplate page by accident. + } + + createErrorSheet(); +} + +function dismissErrorSheet() { + unblockEventHandlers(); + + window.__sheetElement.remove(); + window.__sheetElement = null; + window.__uncaughtExceptions = []; + + // Do this last in case WebInspector's internal state is corrupted. + WebInspector.updateWindowTitle(); + + // FIXME (151959): tell the frontend host to hide a draggable title bar. +} + +function createErrorSheet() { + // Early errors like parse errors may happen in the , so attach + // a body if none exists yet. Code below expects document.body to exist. + if (!document.body) + document.write(""); + + // FIXME (151959): tell the frontend host to show a draggable title bar. + if (InspectorFrontendHost) + InspectorFrontendHost.inspectedURLChanged("Internal Error"); + + // Only allow one sheet element at a time. + if (window.__sheetElement) { + window.__sheetElement.remove(); + window.__sheetElement = null; + } + + const loadCompleted = window.__frontendCompletedLoad; + let firstException = window.__uncaughtExceptions[0]; + + // Inlined from Utilities.js, because that file may not have loaded. + function insertWordBreakCharacters(text) { + return text.replace(/([\/;:\)\]\}&?])/g, "$1\u200b"); + } + + // This trampoline is necessary since none of our functions will be + // in scope of an href="javascript:"-style evaluation. + function handleLinkClick(event) { + if (event.target.tagName !== "A") + return; + if (event.target.id === "dismiss-error-sheet") + dismissErrorSheet(); + } + + function formattedEntry(entry) { + const indent = " "; + let lines = [`${entry.message} (at ${entry.url}:${entry.lineNumber}:${entry.columnNumber})`]; + if (entry.stack) { + let stackLines = entry.stack.split(/\n/g); + for (let stackLine of stackLines) { + let atIndex = stackLine.indexOf("@"); + let slashIndex = Math.max(stackLine.lastIndexOf("/"), atIndex); + let functionName = stackLine.substring(0, atIndex) || "?"; + let location = stackLine.substring(slashIndex + 1, stackLine.length); + lines.push(`${indent}${functionName} @ ${location}`); + } + } + + if (entry.details) { + lines.push(""); + lines.push("Additional Details:"); + for (let key in entry.details) { + let value = entry.details[key]; + lines.push(`${indent}${key} --> ${value}`); + } + } + + return lines.join("\n"); + } + + let inspectedPageURL = null; + try { + inspectedPageURL = WebInspector.frameResourceManager.mainFrame.url; + } catch (e) { } + + let topLevelItems = [ + `Inspected URL: ${inspectedPageURL || "(unknown)"}`, + `Loading completed: ${!!loadCompleted}`, + `Frontend User Agent: ${window.navigator.userAgent}`, + ]; + + function stringifyAndTruncateObject(object) { + let string = JSON.stringify(object); + return string.length > 500 ? string.substr(0, 500) + "…" : string; + } + + if (InspectorBackend && InspectorBackend.currentDispatchState) { + let state = InspectorBackend.currentDispatchState; + if (state.event) { + topLevelItems.push("Dispatch Source: Protocol Event"); + topLevelItems.push(""); + topLevelItems.push("Protocol Event:"); + topLevelItems.push(stringifyAndTruncateObject(state.event)); + } + if (state.response) { + topLevelItems.push("Dispatch Source: Protocol Command Response"); + topLevelItems.push(""); + topLevelItems.push("Protocol Command Response:"); + topLevelItems.push(stringifyAndTruncateObject(state.response)); + } + if (state.request) { + topLevelItems.push(""); + topLevelItems.push("Protocol Command Request:"); + topLevelItems.push(stringifyAndTruncateObject(state.request)); + } + } + + let formattedErrorDetails = window.__uncaughtExceptions.map((entry) => formattedEntry(entry)); + let detailsForBugReport = formattedErrorDetails.map((line) => ` - ${line}`).join("\n"); + topLevelItems.push(""); + topLevelItems.push("Uncaught Exceptions:"); + topLevelItems.push(detailsForBugReport); + + let encodedBugDescription = encodeURIComponent(`------- +${topLevelItems.join("\n")} +------- + +* STEPS TO REPRODUCE +1. What were you doing? Include setup or other preparations to reproduce the exception. +2. Include explicit, accurate, and minimal steps taken. Do not include extraneous or irrelevant steps. + +* NOTES +Document any additional information that might be useful in resolving the problem, such as screen shots or other included attachments. +`); + let encodedBugTitle = encodeURIComponent(`Uncaught Exception: ${firstException.message}`); + let encodedInspectedURL = encodeURIComponent(inspectedPageURL || "http://"); + let prefilledBugReportLink = `https://bugs.webkit.org/enter_bug.cgi?alias=&assigned_to=webkit-unassigned%40lists.webkit.org&attach_text=&blocked=&bug_file_loc=${encodedInspectedURL}&bug_severity=Normal&bug_status=NEW&comment=${encodedBugDescription}&component=Web%20Inspector&contenttypeentry=&contenttypemethod=autodetect&contenttypeselection=text%2Fplain&data=&dependson=&description=&flag_type-1=X&flag_type-3=X&form_name=enter_bug&keywords=&op_sys=All&priority=P2&product=WebKit&rep_platform=All&short_desc=${encodedBugTitle}&version=WebKit%20Nightly%20Build`; + let detailsForHTML = formattedErrorDetails.map((line) => `
    1. ${insertWordBreakCharacters(line)}
    2. `).join("\n"); + + let dismissOptionHTML = !loadCompleted ? "" : `
      A frivolous exception will not stop me!
      +
      Click to close this view and return + to the Web Inspector without reloading. However, some things might not work without reloading if the error corrupted the Inspector's internal state.
      `; + + let sheetElement = window.__sheetElement = document.createElement("div"); + sheetElement.classList.add("sheet-container"); + sheetElement.innerHTML = `
      +

      + + Web Inspector encountered an internal error. +

      +
      +
      Usually, this is caused by a syntax error while modifying the Web Inspector + UI, or running an updated frontend with out-of-date WebKit build. +
      I didn't do anything...?
      +
      If you don't think you caused this error to happen, + click to file a pre-populated + bug with this information. It is possible that someone else broke it by accident.
      +
      Oops, can I try again?
      +
      Click to reload the Inspector + again after making local changes.
      + ${dismissOptionHTML} +
      +

      + + These uncaught exceptions caused the problem: +

      +

        ${detailsForHTML}

      +
      `; + + sheetElement.addEventListener("click", handleLinkClick, true); + document.body.appendChild(sheetElement); +} + +window.addEventListener("error", handleUncaughtException); +window.handlePromiseException = window.handleInternalException = handleError; + +})(); diff --git a/Source/WebInspectorUI/UserInterface/DebuggerManager.js b/Source/WebInspectorUI/UserInterface/DebuggerManager.js deleted file mode 100644 index cfd219538..000000000 --- a/Source/WebInspectorUI/UserInterface/DebuggerManager.js +++ /dev/null @@ -1,702 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.DebuggerManager = function() -{ - WebInspector.Object.call(this); - - if (window.DebuggerAgent) - DebuggerAgent.enable(); - - WebInspector.Breakpoint.addEventListener(WebInspector.Breakpoint.Event.DisplayLocationDidChange, this._breakpointDisplayLocationDidChange, this); - WebInspector.Breakpoint.addEventListener(WebInspector.Breakpoint.Event.DisabledStateDidChange, this._breakpointDisabledStateDidChange, this); - WebInspector.Breakpoint.addEventListener(WebInspector.Breakpoint.Event.ConditionDidChange, this._breakpointEditablePropertyDidChange, this); - WebInspector.Breakpoint.addEventListener(WebInspector.Breakpoint.Event.AutoContinueDidChange, this._breakpointEditablePropertyDidChange, this); - WebInspector.Breakpoint.addEventListener(WebInspector.Breakpoint.Event.ActionsDidChange, this._breakpointEditablePropertyDidChange, this); - - window.addEventListener("pagehide", this._inspectorClosing.bind(this)); - - this._allExceptionsBreakpointEnabledSetting = new WebInspector.Setting("break-on-all-exceptions", false); - this._allUncaughtExceptionsBreakpointEnabledSetting = new WebInspector.Setting("break-on-all-uncaught-exceptions", false); - - var specialBreakpointLocation = new WebInspector.SourceCodeLocation(null, Infinity, Infinity); - - this._allExceptionsBreakpoint = new WebInspector.Breakpoint(specialBreakpointLocation, !this._allExceptionsBreakpointEnabledSetting.value); - this._allExceptionsBreakpoint.resolved = true; - - this._allUncaughtExceptionsBreakpoint = new WebInspector.Breakpoint(specialBreakpointLocation, !this._allUncaughtExceptionsBreakpointEnabledSetting.value); - - this._breakpoints = []; - this._breakpointURLMap = {}; - this._breakpointScriptIdentifierMap = {}; - this._breakpointIdMap = {}; - - this._scriptIdMap = {}; - this._scriptURLMap = {}; - - this._breakpointsSetting = new WebInspector.Setting("breakpoints", []); - this._breakpointsEnabledSetting = new WebInspector.Setting("breakpoints-enabled", true); - - if (window.DebuggerAgent) - DebuggerAgent.setBreakpointsActive(this._breakpointsEnabledSetting.value); - - this._updateBreakOnExceptionsState(); - - var savedBreakpoints = this._breakpointsSetting.value; - for (var i = 0; i < savedBreakpoints.length; ++i) { - var breakpoint = new WebInspector.Breakpoint(savedBreakpoints[i]); - this.addBreakpoint(breakpoint, true); - } -}; - -WebInspector.DebuggerManager.Event = { - BreakpointAdded: "debugger-manager-breakpoint-added", - BreakpointRemoved: "debugger-manager-breakpoint-removed", - BreakpointMoved: "debugger-manager-breakpoint-moved", - Paused: "debugger-manager-paused", - Resumed: "debugger-manager-resumed", - CallFramesDidChange: "debugger-manager-call-frames-did-change", - ActiveCallFrameDidChange: "debugger-manager-active-call-frame-did-change", - ScriptAdded: "debugger-manager-script-added", - ScriptsCleared: "debugger-manager-scripts-cleared" -}; - -WebInspector.DebuggerManager.prototype = { - constructor: WebInspector.DebuggerManager, - - // Public - - get breakpointsEnabled() - { - return this._breakpointsEnabledSetting.value; - }, - - set breakpointsEnabled(enabled) - { - if (this._breakpointsEnabled === enabled) - return; - - this._breakpointsEnabledSetting.value = enabled; - - this._allExceptionsBreakpoint.dispatchEventToListeners(WebInspector.Breakpoint.Event.ResolvedStateDidChange); - this._allUncaughtExceptionsBreakpoint.dispatchEventToListeners(WebInspector.Breakpoint.Event.ResolvedStateDidChange); - - for (var i = 0; i < this._breakpoints.length; ++i) - this._breakpoints[i].dispatchEventToListeners(WebInspector.Breakpoint.Event.ResolvedStateDidChange); - - DebuggerAgent.setBreakpointsActive(enabled); - - this._updateBreakOnExceptionsState(); - }, - - get paused() - { - return this._paused; - }, - - get callFrames() - { - return this._callFrames; - }, - - get activeCallFrame() - { - return this._activeCallFrame; - }, - - set activeCallFrame(callFrame) - { - if (callFrame === this._activeCallFrame) - return; - - this._activeCallFrame = callFrame || null; - - this.dispatchEventToListeners(WebInspector.DebuggerManager.Event.ActiveCallFrameDidChange); - }, - - pause: function() - { - DebuggerAgent.pause(); - }, - - resume: function() - { - DebuggerAgent.resume(); - }, - - stepOver: function() - { - DebuggerAgent.stepOver(); - }, - - stepInto: function() - { - DebuggerAgent.stepInto(); - }, - - stepOut: function() - { - DebuggerAgent.stepOut(); - }, - - get allExceptionsBreakpoint() - { - return this._allExceptionsBreakpoint; - }, - - get allUncaughtExceptionsBreakpoint() - { - return this._allUncaughtExceptionsBreakpoint; - }, - - get breakpoints() - { - return this._breakpoints; - }, - - breakpointsForSourceCode: function(sourceCode) - { - console.assert(sourceCode instanceof WebInspector.Resource || sourceCode instanceof WebInspector.Script); - - if (sourceCode instanceof WebInspector.SourceMapResource) { - var mappedResourceBreakpoints = []; - var originalSourceCodeBreakpoints = this.breakpointsForSourceCode(sourceCode.sourceMap.originalSourceCode); - return originalSourceCodeBreakpoints.filter(function(breakpoint) { - return breakpoint.sourceCodeLocation.displaySourceCode === sourceCode; - }); - } - - if (sourceCode.url in this._breakpointURLMap) { - var urlBreakpoint = this._breakpointURLMap[sourceCode.url] || []; - this._associateBreakpointsWithSourceCode(urlBreakpoint, sourceCode); - return urlBreakpoint; - } - - if (sourceCode instanceof WebInspector.Script && sourceCode.id in this._breakpointScriptIdentifierMap) { - var scriptIdentifierBreakpoints = this._breakpointScriptIdentifierMap[sourceCode.id] || []; - this._associateBreakpointsWithSourceCode(scriptIdentifierBreakpoints, sourceCode); - return scriptIdentifierBreakpoints; - } - - return []; - }, - - scriptForIdentifier: function(id) - { - return this._scriptIdMap[id] || null; - }, - - scriptsForURL: function(url) - { - // FIXME: This may not be safe. A Resource's URL may differ from a Script's URL. - return this._scriptURLMap[url] || []; - }, - - continueToLocation: function(scriptIdentifier, lineNumber, columnNumber) - { - DebuggerAgent.continueToLocation({scriptId: scriptIdentifier, lineNumber: lineNumber, columnNumber: columnNumber}); - }, - - addBreakpoint: function(breakpoint, skipEventDispatch) - { - console.assert(breakpoint); - if (!breakpoint) - return; - - if (breakpoint.url) { - var urlBreakpoints = this._breakpointURLMap[breakpoint.url]; - if (!urlBreakpoints) - urlBreakpoints = this._breakpointURLMap[breakpoint.url] = []; - urlBreakpoints.push(breakpoint); - } - - if (breakpoint.scriptIdentifier) { - var scriptIdentifierBreakpoints = this._breakpointScriptIdentifierMap[breakpoint.scriptIdentifier]; - if (!scriptIdentifierBreakpoints) - scriptIdentifierBreakpoints = this._breakpointScriptIdentifierMap[breakpoint.scriptIdentifier] = []; - scriptIdentifierBreakpoints.push(breakpoint); - } - - this._breakpoints.push(breakpoint); - - if (!breakpoint.disabled) - this._setBreakpoint(breakpoint); - - if (!skipEventDispatch) - this.dispatchEventToListeners(WebInspector.DebuggerManager.Event.BreakpointAdded, {breakpoint: breakpoint}); - }, - - removeBreakpoint: function(breakpoint) - { - console.assert(breakpoint); - if (!breakpoint) - return; - - console.assert(this.isBreakpointRemovable(breakpoint)); - if (!this.isBreakpointRemovable(breakpoint)) - return; - - this._breakpoints.remove(breakpoint); - - if (breakpoint.id) - this._removeBreakpoint(breakpoint); - - if (breakpoint.url) { - var urlBreakpoints = this._breakpointURLMap[breakpoint.url]; - if (urlBreakpoints) { - urlBreakpoints.remove(breakpoint); - if (!urlBreakpoints.length) - delete this._breakpointURLMap[breakpoint.url]; - } - } - - if (breakpoint.scriptIdentifier) { - var scriptIdentifierBreakpoints = this._breakpointScriptIdentifierMap[breakpoint.scriptIdentifier]; - if (scriptIdentifierBreakpoints) { - scriptIdentifierBreakpoints.remove(breakpoint); - if (!scriptIdentifierBreakpoints.length) - delete this._breakpointScriptIdentifierMap[breakpoint.scriptIdentifier]; - } - } - - this.dispatchEventToListeners(WebInspector.DebuggerManager.Event.BreakpointRemoved, {breakpoint: breakpoint}); - }, - - breakpointResolved: function(breakpointIdentifier, location) - { - // Called from WebInspector.DebuggerObserver. - - var breakpoint = this._breakpointIdMap[breakpointIdentifier]; - console.assert(breakpoint); - if (!breakpoint) - return; - - console.assert(breakpoint.id === breakpointIdentifier); - - breakpoint.resolved = true; - }, - - reset: function() - { - // Called from WebInspector.DebuggerObserver. - - var wasPaused = this._paused; - - WebInspector.Script.resetUniqueDisplayNameNumbers(); - - this._paused = false; - this._scriptIdMap = {}; - this._scriptURLMap = {}; - - this._ignoreBreakpointDisplayLocationDidChangeEvent = true; - - // Mark all the breakpoints as unresolved. They will be reported as resolved when - // breakpointResolved is called as the page loads. - for (var i = 0; i < this._breakpoints.length; ++i) { - var breakpoint = this._breakpoints[i]; - breakpoint.resolved = false; - if (breakpoint.sourceCodeLocation.sourceCode) - breakpoint.sourceCodeLocation.sourceCode = null; - } - - delete this._ignoreBreakpointDisplayLocationDidChangeEvent; - - this.dispatchEventToListeners(WebInspector.DebuggerManager.Event.ScriptsCleared); - - if (wasPaused) - this.dispatchEventToListeners(WebInspector.DebuggerManager.Event.Resumed); - }, - - debuggerDidPause: function(callFramesPayload) - { - // Called from WebInspector.DebuggerObserver. - - if (this._delayedResumeTimeout) { - clearTimeout(this._delayedResumeTimeout); - delete this._delayedResumeTimeout; - } - - var wasStillPaused = this._paused; - - this._paused = true; - this._callFrames = []; - - for (var i = 0; i < callFramesPayload.length; ++i) { - var callFramePayload = callFramesPayload[i]; - var sourceCodeLocation = this._sourceCodeLocationFromPayload(callFramePayload.location); - // Exclude the case where the call frame is in the inspector code. - if (!sourceCodeLocation || !sourceCodeLocation._sourceCode || !sourceCodeLocation._sourceCode._url || sourceCodeLocation._sourceCode._url.indexOf("__WebInspector") === 0) - continue; - var thisObject = WebInspector.RemoteObject.fromPayload(callFramePayload.this); - var scopeChain = this._scopeChainFromPayload(callFramePayload.scopeChain); - var callFrame = new WebInspector.CallFrame(callFramePayload.callFrameId, sourceCodeLocation, callFramePayload.functionName, thisObject, scopeChain); - this._callFrames.push(callFrame); - } - - if (!this._callFrames.length) { - this.resume(); - return; - } - - this._activeCallFrame = this._callFrames[0]; - - if (!wasStillPaused) - this.dispatchEventToListeners(WebInspector.DebuggerManager.Event.Paused); - this.dispatchEventToListeners(WebInspector.DebuggerManager.Event.CallFramesDidChange); - this.dispatchEventToListeners(WebInspector.DebuggerManager.Event.ActiveCallFrameDidChange); - }, - - debuggerDidResume: function() - { - // Called from WebInspector.DebuggerObserver. - - function delayedWork() - { - delete this._delayedResumeTimeout; - - this._paused = false; - this._callFrames = null; - this._activeCallFrame = null; - - this.dispatchEventToListeners(WebInspector.DebuggerManager.Event.Resumed); - this.dispatchEventToListeners(WebInspector.DebuggerManager.Event.CallFramesDidChange); - this.dispatchEventToListeners(WebInspector.DebuggerManager.Event.ActiveCallFrameDidChange); - } - - // We delay clearing the state and firing events so the user interface does not flash - // between brief steps or successive breakpoints. - this._delayedResumeTimeout = setTimeout(delayedWork.bind(this), 50); - }, - - scriptDidParse: function(scriptIdentifier, url, isContentScript, startLine, startColumn, endLine, endColumn, sourceMapURL) - { - // Don't add the script again if it is already known. - if (this._scriptIdMap[scriptIdentifier]) { - console.assert(this._scriptIdMap[scriptIdentifier].url === url); - console.assert(this._scriptIdMap[scriptIdentifier].range.startLine === startLine); - console.assert(this._scriptIdMap[scriptIdentifier].range.startColumn === startColumn); - console.assert(this._scriptIdMap[scriptIdentifier].range.endLine === endLine); - console.assert(this._scriptIdMap[scriptIdentifier].range.endColumn === endColumn); - return; - } - - var script = new WebInspector.Script(scriptIdentifier, new WebInspector.TextRange(startLine, startColumn, endLine, endColumn), url, isContentScript, sourceMapURL); - - this._scriptIdMap[scriptIdentifier] = script; - - if (script.url) { - var scripts = this._scriptURLMap[script.url]; - if (!scripts) - scripts = this._scriptURLMap[script.url] = []; - scripts.push(script); - } - - this.dispatchEventToListeners(WebInspector.DebuggerManager.Event.ScriptAdded, {script: script}); - }, - - isBreakpointRemovable: function(breakpoint) - { - return breakpoint !== this._allExceptionsBreakpoint && breakpoint !== this._allUncaughtExceptionsBreakpoint; - }, - - isBreakpointEditable: function(breakpoint) - { - return this.isBreakpointRemovable(breakpoint); - }, - - // Private - - _sourceCodeLocationFromPayload: function(payload) - { - var script = this._scriptIdMap[payload.scriptId]; - console.assert(script); - if (!script) - return null; - - return script.createSourceCodeLocation(payload.lineNumber, payload.columnNumber); - }, - - _scopeChainFromPayload: function(payload) - { - var scopeChain = []; - for (var i = 0; i < payload.length; ++i) - scopeChain.push(this._scopeChainNodeFromPayload(payload[i])); - return scopeChain; - }, - - _scopeChainNodeFromPayload: function(payload) - { - var type = null; - switch (payload.type) { - case "local": - type = WebInspector.ScopeChainNode.Type.Local; - break; - case "global": - type = WebInspector.ScopeChainNode.Type.Global; - break; - case "with": - type = WebInspector.ScopeChainNode.Type.With; - break; - case "closure": - type = WebInspector.ScopeChainNode.Type.Closure; - break; - case "catch": - type = WebInspector.ScopeChainNode.Type.Catch; - break; - default: - console.error("Unknown type: " + payload.type); - } - - var object = WebInspector.RemoteObject.fromPayload(payload.object); - return new WebInspector.ScopeChainNode(type, object); - }, - - _debuggerBreakpointActionType: function(type) - { - switch (type) { - case WebInspector.BreakpointAction.Type.Log: - return DebuggerAgent.BreakpointActionType.Log; - case WebInspector.BreakpointAction.Type.Evaluate: - return DebuggerAgent.BreakpointActionType.Evaluate; - case WebInspector.BreakpointAction.Type.Sound: - return DebuggerAgent.BreakpointActionType.Sound; - default: - console.assert(false); - return DebuggerAgent.BreakpointActionType.Log; - } - }, - - _setBreakpoint: function(breakpoint, callback) - { - console.assert(!breakpoint.id); - console.assert(!breakpoint.disabled); - - if (breakpoint.id || breakpoint.disabled) - return; - - function didSetBreakpoint(error, breakpointIdentifier) - { - if (error) - return; - - this._breakpointIdMap[breakpointIdentifier] = breakpoint; - - breakpoint.id = breakpointIdentifier; - breakpoint.resolved = true; - - if (typeof callback === "function") - callback(); - } - - // The breakpoint will be resolved again by calling DebuggerAgent, so mark it as unresolved. - // If something goes wrong it will stay unresolved and show up as such in the user interface. - breakpoint.resolved = false; - - // Convert BreakpointAction types to DebuggerAgent protocol types. - // NOTE: Breakpoint.options returns new objects each time, so it is safe to modify. - var options; - if (DebuggerAgent.BreakpointActionType) { - options = breakpoint.options; - if (options.actions.length) { - for (var i = 0; i < options.actions.length; ++i) - options.actions[i].type = this._debuggerBreakpointActionType(options.actions[i].type); - } - } - - // COMPATIBILITY (iOS 7): iOS 7 and earlier, DebuggerAgent.setBreakpoint* took a "condition" string argument. - // This has been replaced with an "options" BreakpointOptions object. - if (breakpoint.url) { - DebuggerAgent.setBreakpointByUrl.invoke({ - lineNumber: breakpoint.sourceCodeLocation.lineNumber, - url: breakpoint.url, - urlRegex: undefined, - columnNumber: breakpoint.sourceCodeLocation.columnNumber, - condition: breakpoint.condition, - options: options - }, didSetBreakpoint.bind(this)); - } else if (breakpoint.scriptIdentifier) { - DebuggerAgent.setBreakpoint.invoke({ - location: {scriptId: breakpoint.scriptIdentifier, lineNumber: breakpoint.sourceCodeLocation.lineNumber, columnNumber: breakpoint.sourceCodeLocation.columnNumber}, - condition: breakpoint.condition, - options: options - }, didSetBreakpoint.bind(this)); - } - }, - - _removeBreakpoint: function(breakpoint, callback) - { - console.assert(breakpoint.id); - - if (!breakpoint.id) - return; - - function didRemoveBreakpoint(error) - { - if (error) - console.error(error); - - delete this._breakpointIdMap[breakpoint.id]; - - breakpoint.id = null; - - // Don't reset resolved here since we want to keep disabled breakpoints looking like they - // are resolved in the user interface. They will get marked as unresolved in reset. - - if (typeof callback === "function") - callback(); - } - - DebuggerAgent.removeBreakpoint(breakpoint.id, didRemoveBreakpoint.bind(this)); - }, - - _breakpointDisplayLocationDidChange: function(event) - { - if (this._ignoreBreakpointDisplayLocationDidChangeEvent) - return; - - var breakpoint = event.target; - if (!breakpoint.id || breakpoint.disabled) - return; - - // Remove the breakpoint with its old id. - this._removeBreakpoint(breakpoint, breakpointRemoved.bind(this)); - - function breakpointRemoved() - { - // Add the breakpoint at its new lineNumber and get a new id. - this._setBreakpoint(breakpoint); - - this.dispatchEventToListeners(WebInspector.DebuggerManager.Event.BreakpointMoved, {breakpoint: breakpoint}); - } - }, - - _breakpointDisabledStateDidChange: function(event) - { - var breakpoint = event.target; - - if (breakpoint === this._allExceptionsBreakpoint) { - this._allExceptionsBreakpointEnabledSetting.value = !breakpoint.disabled; - this._updateBreakOnExceptionsState(); - return; - } - - if (breakpoint === this._allUncaughtExceptionsBreakpoint) { - this._allUncaughtExceptionsBreakpointEnabledSetting.value = !breakpoint.disabled; - this._updateBreakOnExceptionsState(); - return; - } - - if (breakpoint.disabled) - this._removeBreakpoint(breakpoint); - else - this._setBreakpoint(breakpoint); - }, - - _breakpointEditablePropertyDidChange: function(event) - { - var breakpoint = event.target; - if (breakpoint.disabled) - return; - - console.assert(this.isBreakpointEditable(breakpoint)); - if (!this.isBreakpointEditable(breakpoint)) - return; - - // Remove the breakpoint with its old id. - this._removeBreakpoint(breakpoint, breakpointRemoved.bind(this)); - - function breakpointRemoved() - { - // Add the breakpoint with its new condition and get a new id. - this._setBreakpoint(breakpoint); - } - }, - - _updateBreakOnExceptionsState: function() - { - var state = "none"; - - if (this._breakpointsEnabledSetting.value) { - if (!this._allExceptionsBreakpoint.disabled) - state = "all"; - else if (!this._allUncaughtExceptionsBreakpoint.disabled) - state = "uncaught"; - } - - switch (state) { - case "all": - // Mark the uncaught breakpoint as unresolved since "all" includes "uncaught". - // That way it is clear in the user interface that the breakpoint is ignored. - this._allUncaughtExceptionsBreakpoint.resolved = false; - break; - case "uncaught": - case "none": - // Mark the uncaught breakpoint as resolved again. - this._allUncaughtExceptionsBreakpoint.resolved = true; - break; - } - - DebuggerAgent.setPauseOnExceptions(state); - }, - - _inspectorClosing: function(event) - { - this._saveBreakpoints(); - }, - - _saveBreakpoints: function() - { - var savedBreakpoints = []; - - for (var i = 0; i < this._breakpoints.length; ++i) { - var breakpoint = this._breakpoints[i]; - - // Only breakpoints with URLs can be saved. Breakpoints for transient scripts can't. - if (!breakpoint.url) - continue; - - savedBreakpoints.push(breakpoint.info); - } - - this._breakpointsSetting.value = savedBreakpoints; - }, - - _associateBreakpointsWithSourceCode: function(breakpoints, sourceCode) - { - this._ignoreBreakpointDisplayLocationDidChangeEvent = true; - - for (var i = 0; i < breakpoints.length; ++i) { - var breakpoint = breakpoints[i]; - if (breakpoint.sourceCodeLocation.sourceCode === null) - breakpoint.sourceCodeLocation.sourceCode = sourceCode; - // SourceCodes can be unequal if the SourceCodeLocation is associated with a Script and we are looking at the Resource. - console.assert(breakpoint.sourceCodeLocation.sourceCode === sourceCode || breakpoint.sourceCodeLocation.sourceCode.url === sourceCode.url); - } - - delete this._ignoreBreakpointDisplayLocationDidChangeEvent; - } -}; - -WebInspector.DebuggerManager.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/DebuggerObserver.js b/Source/WebInspectorUI/UserInterface/DebuggerObserver.js deleted file mode 100644 index 0b8f54cc5..000000000 --- a/Source/WebInspectorUI/UserInterface/DebuggerObserver.js +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.DebuggerObserver = function() -{ - WebInspector.Object.call(this); -}; - -WebInspector.DebuggerObserver.prototype = { - constructor: WebInspector.DebuggerObserver, - - // Events defined by the "Debugger" domain. - - globalObjectCleared: function() - { - WebInspector.debuggerManager.reset(); - }, - - scriptParsed: function(scriptId, url, startLine, startColumn, endLine, endColumn, isContentScript, sourceMapURL, hasSourceURL) - { - WebInspector.debuggerManager.scriptDidParse(scriptId, url, isContentScript, startLine, startColumn, endLine, endColumn, sourceMapURL); - }, - - scriptFailedToParse: function(url, scriptSource, startLine, errorLine, errorMessage) - { - // FIXME: Not implemented. - }, - - breakpointResolved: function(breakpointId, location) - { - WebInspector.debuggerManager.breakpointResolved(breakpointId, location); - }, - - paused: function(callFrames, reason, data) - { - WebInspector.debuggerManager.debuggerDidPause(callFrames); - }, - - resumed: function() - { - WebInspector.debuggerManager.debuggerDidResume(); - } -}; - -WebInspector.DebuggerObserver.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/DebuggerSidebarPanel.css b/Source/WebInspectorUI/UserInterface/DebuggerSidebarPanel.css deleted file mode 100644 index 54d283e72..000000000 --- a/Source/WebInspectorUI/UserInterface/DebuggerSidebarPanel.css +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.sidebar > .panel.debugger > .content { - top: 22px; -} - -.sidebar > .panel.debugger > .navigation-bar { - position: absolute; - top: 0; - left: 0; - right: 0; -} diff --git a/Source/WebInspectorUI/UserInterface/DebuggerSidebarPanel.js b/Source/WebInspectorUI/UserInterface/DebuggerSidebarPanel.js deleted file mode 100644 index a45891454..000000000 --- a/Source/WebInspectorUI/UserInterface/DebuggerSidebarPanel.js +++ /dev/null @@ -1,558 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.DebuggerSidebarPanel = function() -{ - WebInspector.NavigationSidebarPanel.call(this, "debugger", WebInspector.UIString("Debugger"), "Images/NavigationItemBug.svg", "3", true); - - WebInspector.Frame.addEventListener(WebInspector.Frame.Event.MainResourceDidChange, this._mainResourceChanged, this); - WebInspector.Frame.addEventListener(WebInspector.Frame.Event.ResourceWasAdded, this._resourceAdded, this); - - WebInspector.debuggerManager.addEventListener(WebInspector.DebuggerManager.Event.CallFramesDidChange, this._debuggerCallFramesDidChange, this); - WebInspector.debuggerManager.addEventListener(WebInspector.DebuggerManager.Event.BreakpointAdded, this._breakpointAdded, this); - WebInspector.debuggerManager.addEventListener(WebInspector.DebuggerManager.Event.BreakpointRemoved, this._breakpointRemoved, this); - WebInspector.debuggerManager.addEventListener(WebInspector.DebuggerManager.Event.ScriptAdded, this._scriptAdded, this); - WebInspector.debuggerManager.addEventListener(WebInspector.DebuggerManager.Event.ScriptsCleared, this._scriptsCleared, this); - WebInspector.debuggerManager.addEventListener(WebInspector.DebuggerManager.Event.Paused, this._debuggerDidPause, this); - WebInspector.debuggerManager.addEventListener(WebInspector.DebuggerManager.Event.Resumed, this._debuggerDidResume, this); - WebInspector.debuggerManager.addEventListener(WebInspector.DebuggerManager.Event.ActiveCallFrameDidChange, this._debuggerActiveCallFrameDidChange, this); - - this._pauseOrResumeKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.Control | WebInspector.KeyboardShortcut.Modifier.CommandOrControl, "Y", this._debuggerPauseResumeButtonClicked.bind(this)); - this._stepOverKeyboardShortcut = new WebInspector.KeyboardShortcut(null, WebInspector.KeyboardShortcut.Key.F6, this._debuggerStepOverButtonClicked.bind(this)); - this._stepIntoKeyboardShortcut = new WebInspector.KeyboardShortcut(null, WebInspector.KeyboardShortcut.Key.F7, this._debuggerStepIntoButtonClicked.bind(this)); - this._stepOutKeyboardShortcut = new WebInspector.KeyboardShortcut(null, WebInspector.KeyboardShortcut.Key.F8, this._debuggerStepOutButtonClicked.bind(this)); - - this._pauseOrResumeAlternateKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, WebInspector.KeyboardShortcut.Key.Slash, this._debuggerPauseResumeButtonClicked.bind(this)); - this._stepOverAlternateKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, WebInspector.KeyboardShortcut.Key.SingleQuote, this._debuggerStepOverButtonClicked.bind(this)); - this._stepIntoAlternateKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, WebInspector.KeyboardShortcut.Key.Semicolon, this._debuggerStepIntoButtonClicked.bind(this)); - this._stepOutAlternateKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.Shift | WebInspector.KeyboardShortcut.Modifier.CommandOrControl, WebInspector.KeyboardShortcut.Key.Semicolon, this._debuggerStepOutButtonClicked.bind(this)); - - this._navigationBar = new WebInspector.NavigationBar; - this.element.appendChild(this._navigationBar.element); - - var toolTip = WebInspector.UIString("Enable all breakpoints"); - var altToolTip = WebInspector.UIString("Disable all breakpoints"); - - this._debuggerBreakpointsButtonItem = new WebInspector.ActivateButtonNavigationItem("debugger-breakpoints", toolTip, altToolTip, "Images/Breakpoints.svg", 16, 16); - this._debuggerBreakpointsButtonItem.activated = WebInspector.debuggerManager.breakpointsEnabled; - this._debuggerBreakpointsButtonItem.addEventListener(WebInspector.ButtonNavigationItem.Event.Clicked, this._breakpointsToggleButtonClicked, this); - this._navigationBar.addNavigationItem(this._debuggerBreakpointsButtonItem); - - toolTip = WebInspector.UIString("Pause script execution (%s or %s)").format(this._pauseOrResumeKeyboardShortcut.displayName, this._pauseOrResumeAlternateKeyboardShortcut.displayName); - altToolTip = WebInspector.UIString("Continue script execution (%s or %s)").format(this._pauseOrResumeKeyboardShortcut.displayName, this._pauseOrResumeAlternateKeyboardShortcut.displayName); - - this._debuggerPauseResumeButtonItem = new WebInspector.ToggleButtonNavigationItem("debugger-pause-resume", toolTip, altToolTip, "Images/Pause.svg", "Images/Resume.svg", 16, 16); - this._debuggerPauseResumeButtonItem.addEventListener(WebInspector.ButtonNavigationItem.Event.Clicked, this._debuggerPauseResumeButtonClicked, this); - this._navigationBar.addNavigationItem(this._debuggerPauseResumeButtonItem); - - this._debuggerStepOverButtonItem = new WebInspector.ButtonNavigationItem("debugger-step-over", WebInspector.UIString("Step over (%s or %s)").format(this._stepOverKeyboardShortcut.displayName, this._stepOverAlternateKeyboardShortcut.displayName), "Images/StepOver.svg", 16, 16); - this._debuggerStepOverButtonItem.addEventListener(WebInspector.ButtonNavigationItem.Event.Clicked, this._debuggerStepOverButtonClicked, this); - this._debuggerStepOverButtonItem.enabled = false; - this._navigationBar.addNavigationItem(this._debuggerStepOverButtonItem); - - this._debuggerStepIntoButtonItem = new WebInspector.ButtonNavigationItem("debugger-step-into", WebInspector.UIString("Step into (%s or %s)").format(this._stepIntoKeyboardShortcut.displayName, this._stepIntoAlternateKeyboardShortcut.displayName), "Images/StepInto.svg", 16, 16); - this._debuggerStepIntoButtonItem.addEventListener(WebInspector.ButtonNavigationItem.Event.Clicked, this._debuggerStepIntoButtonClicked, this); - this._debuggerStepIntoButtonItem.enabled = false; - this._navigationBar.addNavigationItem(this._debuggerStepIntoButtonItem); - - this._debuggerStepOutButtonItem = new WebInspector.ButtonNavigationItem("debugger-step-out", WebInspector.UIString("Step out (%s or %s)").format(this._stepOutKeyboardShortcut.displayName, this._stepOutAlternateKeyboardShortcut.displayName), "Images/StepOut.svg", 16, 16); - this._debuggerStepOutButtonItem.addEventListener(WebInspector.ButtonNavigationItem.Event.Clicked, this._debuggerStepOutButtonClicked, this); - this._debuggerStepOutButtonItem.enabled = false; - this._navigationBar.addNavigationItem(this._debuggerStepOutButtonItem); - - // Add this offset-sections class name so the sticky headers don't overlap the navigation bar. - this.element.classList.add(WebInspector.DebuggerSidebarPanel.OffsetSectionsStyleClassName); - - this._allExceptionsBreakpointTreeElement = new WebInspector.BreakpointTreeElement(WebInspector.debuggerManager.allExceptionsBreakpoint, WebInspector.DebuggerSidebarPanel.ExceptionIconStyleClassName, WebInspector.UIString("All Exceptions")); - this._allUncaughtExceptionsBreakpointTreeElement = new WebInspector.BreakpointTreeElement(WebInspector.debuggerManager.allUncaughtExceptionsBreakpoint, WebInspector.DebuggerSidebarPanel.ExceptionIconStyleClassName, WebInspector.UIString("All Uncaught Exceptions")); - - this.filterBar.placeholder = WebInspector.UIString("Filter Breakpoint List"); - - this._breakpointsContentTreeOutline = this.contentTreeOutline; - this._breakpointsContentTreeOutline.onselect = this._treeElementSelected.bind(this); - this._breakpointsContentTreeOutline.ondelete = this._breakpointTreeOutlineDeleteTreeElement.bind(this); - this._breakpointsContentTreeOutline.oncontextmenu = this._breakpointTreeOutlineContextMenuTreeElement.bind(this); - - this._breakpointsContentTreeOutline.appendChild(this._allExceptionsBreakpointTreeElement); - this._breakpointsContentTreeOutline.appendChild(this._allUncaughtExceptionsBreakpointTreeElement); - - var breakpointsRow = new WebInspector.DetailsSectionRow; - breakpointsRow.element.appendChild(this._breakpointsContentTreeOutline.element); - - var breakpointsGroup = new WebInspector.DetailsSectionGroup([breakpointsRow]); - var breakpointsSection = new WebInspector.DetailsSection("breakpoints", WebInspector.UIString("Breakpoints"), [breakpointsGroup]); - this.contentElement.appendChild(breakpointsSection.element); - - this._callStackContentTreeOutline = this.createContentTreeOutline(true); - this._callStackContentTreeOutline.onselect = this._treeElementSelected.bind(this); - - this._callStackRow = new WebInspector.DetailsSectionRow(WebInspector.UIString("No Call Frames")); - this._callStackRow.showEmptyMessage(); - - var callStackGroup = new WebInspector.DetailsSectionGroup([this._callStackRow]); - this._callStackSection = new WebInspector.DetailsSection("call-stack", WebInspector.UIString("Call Stack"), [callStackGroup]); - - WebInspector.Breakpoint.addEventListener(WebInspector.Breakpoint.Event.DisplayLocationDidChange, this._breakpointDisplayLocationDidChange, this); -}; - -WebInspector.DebuggerSidebarPanel.OffsetSectionsStyleClassName = "offset-sections"; -WebInspector.DebuggerSidebarPanel.ExceptionIconStyleClassName = "breakpoint-exception-icon"; - -WebInspector.DebuggerSidebarPanel.SelectedAllExceptionsCookieKey = "debugger-sidebar-panel-all-exceptions-breakpoint"; -WebInspector.DebuggerSidebarPanel.SelectedAllUncaughtExceptionsCookieKey = "debugger-sidebar-panel-all-uncaught-exceptions-breakpoint"; - -WebInspector.DebuggerSidebarPanel.prototype = { - constructor: WebInspector.DebuggerSidebarPanel, - - // Public - - treeElementForRepresentedObject: function(representedObject) - { - // The main resource is used as the representedObject instead of Frame in our tree. - if (representedObject instanceof WebInspector.Frame) - representedObject = representedObject.mainResource; - - return this.contentTreeOutline.getCachedTreeElement(representedObject); - }, - - // Protected - - saveStateToCookie: function(cookie) - { - console.assert(cookie); - - var selectedTreeElement = this._breakpointsContentTreeOutline.selectedTreeElement; - if (!selectedTreeElement) - return; - - var representedObject = selectedTreeElement.representedObject; - - if (representedObject === WebInspector.debuggerManager.allExceptionsBreakpoint) - cookie[WebInspector.DebuggerSidebarPanel.SelectedAllExceptionsCookieKey] = true; - - if (representedObject === WebInspector.debuggerManager.allUncaughtExceptionsBreakpoint) - cookie[WebInspector.DebuggerSidebarPanel.SelectedAllUncaughtExceptionsCookieKey] = true; - - WebInspector.NavigationSidebarPanel.prototype.saveStateToCookie.call(this, cookie); - }, - - restoreStateFromCookie: function(cookie, relaxedMatchDelay) - { - console.assert(cookie); - - // Eagerly resolve the special breakpoints; otherwise, use the default behavior. - if (cookie[WebInspector.DebuggerSidebarPanel.SelectedAllExceptionsCookieKey]) - this._allExceptionsBreakpointTreeElement.revealAndSelect(); - else if (cookie[WebInspector.DebuggerSidebarPanel.SelectedAllUncaughtExceptionsCookieKey]) - this._allUncaughtExceptionsBreakpointTreeElement.revealAndSelect(); - else - WebInspector.NavigationSidebarPanel.prototype.restoreStateFromCookie.call(this, cookie, relaxedMatchDelay); - }, - - // Private - - _debuggerPauseResumeButtonClicked: function(event) - { - if (WebInspector.debuggerManager.paused) - WebInspector.debuggerManager.resume(); - else { - this._debuggerPauseResumeButtonItem.enabled = false; - WebInspector.debuggerManager.pause(); - } - }, - - _debuggerStepOverButtonClicked: function(event) - { - WebInspector.debuggerManager.stepOver(); - }, - - _debuggerStepIntoButtonClicked: function(event) - { - WebInspector.debuggerManager.stepInto(); - }, - - _debuggerStepOutButtonClicked: function(event) - { - WebInspector.debuggerManager.stepOut(); - }, - - _debuggerDidPause: function(event) - { - this.contentElement.insertBefore(this._callStackSection.element, this.contentElement.firstChild); - - this._debuggerPauseResumeButtonItem.enabled = true; - this._debuggerPauseResumeButtonItem.toggled = true; - this._debuggerStepOverButtonItem.enabled = true; - this._debuggerStepIntoButtonItem.enabled = true; - }, - - _debuggerDidResume: function(event) - { - this._callStackSection.element.remove(); - - this._debuggerPauseResumeButtonItem.enabled = true; - this._debuggerPauseResumeButtonItem.toggled = false; - this._debuggerStepOverButtonItem.enabled = false; - this._debuggerStepIntoButtonItem.enabled = false; - this._debuggerStepOutButtonItem.enabled = false; - }, - - _breakpointsToggleButtonClicked: function(event) - { - this._debuggerBreakpointsButtonItem.activated = !this._debuggerBreakpointsButtonItem.activated; - WebInspector.debuggerManager.breakpointsEnabled = this._debuggerBreakpointsButtonItem.activated; - }, - - _addBreakpoint: function(breakpoint, sourceCode) - { - var sourceCode = breakpoint.sourceCodeLocation.displaySourceCode; - if (!sourceCode) - return null; - - var parentTreeElement = this._breakpointsContentTreeOutline.getCachedTreeElement(sourceCode); - if (!parentTreeElement) { - if (sourceCode instanceof WebInspector.SourceMapResource) - parentTreeElement = new WebInspector.SourceMapResourceTreeElement(sourceCode); - else if (sourceCode instanceof WebInspector.Resource) - parentTreeElement = new WebInspector.ResourceTreeElement(sourceCode); - else if (sourceCode instanceof WebInspector.Script) - parentTreeElement = new WebInspector.ScriptTreeElement(sourceCode); - } - - if (!parentTreeElement.parent) { - parentTreeElement.hasChildren = true; - parentTreeElement.expand(); - - this._breakpointsContentTreeOutline.insertChild(parentTreeElement, insertionIndexForObjectInListSortedByFunction(parentTreeElement, this._breakpointsContentTreeOutline.children, this._compareTopLevelTreeElements.bind(this))); - } - - // Mark disabled breakpoints as resolved if there is source code loaded with that URL. - // This gives the illusion the breakpoint was resolved, but since we don't send disabled - // breakpoints to the backend we don't know for sure. If the user enables the breakpoint - // it will be resolved properly. - if (breakpoint.disabled) - breakpoint.resolved = true; - - var breakpointTreeElement = new WebInspector.BreakpointTreeElement(breakpoint); - parentTreeElement.insertChild(breakpointTreeElement, insertionIndexForObjectInListSortedByFunction(breakpointTreeElement, parentTreeElement.children, this._compareBreakpointTreeElements)); - return breakpointTreeElement; - }, - - _addBreakpointsForSourceCode: function(sourceCode) - { - var breakpoints = WebInspector.debuggerManager.breakpointsForSourceCode(sourceCode); - for (var i = 0; i < breakpoints.length; ++i) - this._addBreakpoint(breakpoints[i], sourceCode); - }, - - _resourceAdded: function(event) - { - var resource = event.data.resource; - this._addBreakpointsForSourceCode(resource); - }, - - _mainResourceChanged: function(event) - { - var resource = event.target.mainResource; - this._addBreakpointsForSourceCode(resource); - }, - - _scriptAdded: function(event) - { - var script = event.data.script; - - // Don't add breakpoints if the script is represented by a Resource. They were - // already added by _resourceAdded. - if (script.resource) - return; - - this._addBreakpointsForSourceCode(script); - }, - - _scriptsCleared: function(event) - { - for (var i = this._breakpointsContentTreeOutline.children.length - 1; i >= 0; --i) { - var treeElement = this._breakpointsContentTreeOutline.children[i]; - if (!(treeElement instanceof WebInspector.ScriptTreeElement)) - continue; - - this._breakpointsContentTreeOutline.removeChildAtIndex(i, true, true); - } - }, - - _breakpointAdded: function(event) - { - var breakpoint = event.data.breakpoint; - this._addBreakpoint(breakpoint); - }, - - _breakpointRemoved: function(event) - { - var breakpoint = event.data.breakpoint; - - var breakpointTreeElement = this._breakpointsContentTreeOutline.getCachedTreeElement(breakpoint); - console.assert(breakpointTreeElement); - if (!breakpointTreeElement) - return; - - this._removeBreakpointTreeElement(breakpointTreeElement); - }, - - _breakpointDisplayLocationDidChange: function(event) - { - var breakpoint = event.target; - if (event.data.oldDisplaySourceCode === breakpoint.displaySourceCode) - return; - - var breakpointTreeElement = this._breakpointsContentTreeOutline.getCachedTreeElement(breakpoint); - if (!breakpointTreeElement) - return; - - // A known breakpoint moved between resources, remove the old tree element - // and create a new tree element with the updated file. - - var wasSelected = breakpointTreeElement.selected; - - this._removeBreakpointTreeElement(breakpointTreeElement); - var newBreakpointTreeElement = this._addBreakpoint(breakpoint); - - if (newBreakpointTreeElement && wasSelected) - newBreakpointTreeElement.revealAndSelect(true, false, true, true); - }, - - _removeBreakpointTreeElement: function(breakpointTreeElement) - { - var parentTreeElement = breakpointTreeElement.parent; - parentTreeElement.removeChild(breakpointTreeElement); - - console.assert(parentTreeElement.parent === this._breakpointsContentTreeOutline); - - if (!parentTreeElement.children.length) - this._breakpointsContentTreeOutline.removeChild(parentTreeElement); - }, - - _debuggerCallFramesDidChange: function() - { - this._callStackContentTreeOutline.removeChildren(); - - var callFrames = WebInspector.debuggerManager.callFrames; - if (!callFrames || !callFrames.length) { - this._callStackRow.showEmptyMessage(); - return; - } - - this._callStackRow.hideEmptyMessage(); - this._callStackRow.element.appendChild(this._callStackContentTreeOutline.element); - - var treeElementToSelect = null; - - var activeCallFrame = WebInspector.debuggerManager.activeCallFrame; - for (var i = 0; i < callFrames.length; ++i) { - var callFrameTreeElement = new WebInspector.CallFrameTreeElement(callFrames[i]); - if (callFrames[i] === activeCallFrame) - treeElementToSelect = callFrameTreeElement; - this._callStackContentTreeOutline.appendChild(callFrameTreeElement); - } - - if (treeElementToSelect) - treeElementToSelect.select(true, true); - }, - - _debuggerActiveCallFrameDidChange: function() - { - var callFrames = WebInspector.debuggerManager.callFrames; - if (!callFrames) - return; - - var indexOfActiveCallFrame = callFrames.indexOf(WebInspector.debuggerManager.activeCallFrame); - // It is useful to turn off the step out button when there is no call frame to go through - // since there might be call frames in the backend that were removed when processing the call - // frame payload. - this._debuggerStepOutButtonItem.enabled = indexOfActiveCallFrame < callFrames.length - 1; - }, - - _breakpointsBeneathTreeElement: function(treeElement) - { - console.assert(treeElement instanceof WebInspector.ResourceTreeElement || treeElement instanceof WebInspector.ScriptTreeElement); - if (!(treeElement instanceof WebInspector.ResourceTreeElement) && !(treeElement instanceof WebInspector.ScriptTreeElement)) - return []; - - var breakpoints = []; - var breakpointTreeElements = treeElement.children; - for (var i = 0; i < breakpointTreeElements.length; ++i) { - console.assert(breakpointTreeElements[i] instanceof WebInspector.BreakpointTreeElement); - console.assert(breakpointTreeElements[i].breakpoint); - var breakpoint = breakpointTreeElements[i].breakpoint; - if (breakpoint) - breakpoints.push(breakpoint); - } - - return breakpoints; - }, - - _removeAllBreakpoints: function(breakpoints) - { - for (var i = 0; i < breakpoints.length; ++i) { - var breakpoint = breakpoints[i]; - if (WebInspector.debuggerManager.isBreakpointRemovable(breakpoint)) - WebInspector.debuggerManager.removeBreakpoint(breakpoint); - } - }, - - _toggleAllBreakpoints: function(breakpoints, disabled) - { - for (var i = 0; i < breakpoints.length; ++i) - breakpoints[i].disabled = disabled; - }, - - _breakpointTreeOutlineDeleteTreeElement: function(treeElement) - { - console.assert(treeElement.selected); - console.assert(treeElement instanceof WebInspector.ResourceTreeElement || treeElement instanceof WebInspector.ScriptTreeElement); - if (!(treeElement instanceof WebInspector.ResourceTreeElement) && !(treeElement instanceof WebInspector.ScriptTreeElement)) - return false; - - var wasTopResourceTreeElement = treeElement.previousSibling === this._allUncaughtExceptionsBreakpointTreeElement; - var nextSibling = treeElement.nextSibling; - - var breakpoints = this._breakpointsBeneathTreeElement(treeElement); - this._removeAllBreakpoints(breakpoints); - - if (wasTopResourceTreeElement && nextSibling) - nextSibling.select(true, true); - - return true; - }, - - _breakpointTreeOutlineContextMenuTreeElement: function(event, treeElement) - { - console.assert(treeElement instanceof WebInspector.ResourceTreeElement || treeElement instanceof WebInspector.ScriptTreeElement); - if (!(treeElement instanceof WebInspector.ResourceTreeElement) && !(treeElement instanceof WebInspector.ScriptTreeElement)) - return; - - var breakpoints = this._breakpointsBeneathTreeElement(treeElement); - var shouldDisable = false; - for (var i = 0; i < breakpoints.length; ++i) { - if (!breakpoints[i].disabled) { - shouldDisable = true; - break; - } - } - - function removeAllResourceBreakpoints() - { - this._removeAllBreakpoints(breakpoints); - } - - function toggleAllResourceBreakpoints() - { - this._toggleAllBreakpoints(breakpoints, shouldDisable); - } - - var contextMenu = new WebInspector.ContextMenu(event); - if (shouldDisable) - contextMenu.appendItem(WebInspector.UIString("Disable Breakpoints"), toggleAllResourceBreakpoints.bind(this)); - else - contextMenu.appendItem(WebInspector.UIString("Enable Breakpoints"), toggleAllResourceBreakpoints.bind(this)); - contextMenu.appendItem(WebInspector.UIString("Delete Breakpoints"), removeAllResourceBreakpoints.bind(this)); - contextMenu.show(); - }, - - _treeElementSelected: function(treeElement, selectedByUser) - { - function deselectCallStackContentTreeElements() - { - // Deselect any tree element in the call stack content tree outline to prevent two selections in the sidebar. - var selectedTreeElement = this._callStackContentTreeOutline.selectedTreeElement; - if (selectedTreeElement) - selectedTreeElement.deselect(); - } - - if (treeElement instanceof WebInspector.ResourceTreeElement || treeElement instanceof WebInspector.ScriptTreeElement) { - // If the resource is being selected when it has no children it is in the process of being deleted, don't do anything. - if (!treeElement.children.length) - return; - deselectCallStackContentTreeElements.call(this); - WebInspector.resourceSidebarPanel.showSourceCode(treeElement.representedObject); - return; - } - - if (treeElement instanceof WebInspector.CallFrameTreeElement) { - // Deselect any tree element in the breakpoints content tree outline to prevent two selections in the sidebar. - var selectedTreeElement = this._breakpointsContentTreeOutline.selectedTreeElement; - if (selectedTreeElement) - selectedTreeElement.deselect(); - - var callFrame = treeElement.callFrame; - WebInspector.debuggerManager.activeCallFrame = callFrame; - WebInspector.resourceSidebarPanel.showSourceCodeLocation(callFrame.sourceCodeLocation); - return; - } - - if (!(treeElement instanceof WebInspector.BreakpointTreeElement)) - return; - - deselectCallStackContentTreeElements.call(this); - - if (!treeElement.parent.representedObject) - return; - - console.assert(treeElement.parent.representedObject instanceof WebInspector.SourceCode); - if (!(treeElement.parent.representedObject instanceof WebInspector.SourceCode)) - return; - - var breakpoint = treeElement.breakpoint; - WebInspector.resourceSidebarPanel.showSourceCodeLocation(breakpoint.sourceCodeLocation); - }, - - _compareTopLevelTreeElements: function(a, b) - { - if (a === this._allExceptionsBreakpointTreeElement) - return -1; - if (b === this._allExceptionsBreakpointTreeElement) - return 1; - - if (a === this._allUncaughtExceptionsBreakpointTreeElement) - return -1; - if (b === this._allUncaughtExceptionsBreakpointTreeElement) - return 1; - - return a.mainTitle.localeCompare(b.mainTitle); - }, - - _compareBreakpointTreeElements: function(a, b) - { - var aLocation = a.breakpoint.sourceCodeLocation; - var bLocation = b.breakpoint.sourceCodeLocation; - - var comparisonResult = aLocation.displayLineNumber - bLocation.displayLineNumber; - if (comparisonResult !== 0) - return comparisonResult; - - return aLocation.displayColumnNumber - bLocation.displayColumnNumber; - } -}; - -WebInspector.DebuggerSidebarPanel.prototype.__proto__ = WebInspector.NavigationSidebarPanel.prototype; diff --git a/Source/WebInspectorUI/UserInterface/DetailsSection.css b/Source/WebInspectorUI/UserInterface/DetailsSection.css deleted file mode 100644 index a04f7eabc..000000000 --- a/Source/WebInspectorUI/UserInterface/DetailsSection.css +++ /dev/null @@ -1,260 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.details-section { - margin-top: -1px; - margin-bottom: -1px; - - font-family: "Lucida Grande", sans-serif; - font-size: 10px; -} - -.details-section > .header { - position: -webkit-sticky; - top: -1px; - height: 23px; - - border-top: 1px solid rgb(153, 153, 153); - border-bottom: 1px solid rgb(153, 153, 153); - box-shadow: inset rgba(255, 255, 255, 0.2) 0 1px 0; - background-image: -webkit-linear-gradient(top, rgb(238, 240, 244), rgb(224, 226, 230)); - - color: rgb(57, 57, 57); - text-shadow: rgba(255, 255, 255, 0.5) 0 1px 0; - - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; - - font-size: 11px; - font-weight: bold; - - padding: 4px 5px 4px 0; - - /* Ensure the headers are displayed above scrollbars. */ - z-index: 200; -} - -.details-section .details-section > .header { - background-image: -webkit-linear-gradient(top, rgb(250, 250, 250), rgb(240, 240, 240)); - - top: 21px; - - /* Ensure these headers are displayed below the parent header but above scrollbars. */ - z-index: 100; -} - -.details-section > .header::before { - display: block; - float: left; - - width: 21px; - height: 100%; - - background-image: -webkit-canvas(details-section-disclosure-triangle-open-normal); - background-repeat: no-repeat; - background-position: center; - background-size: 13px 13px; - - content: ""; -} - -.details-section > .header:not(.mouse-over-options-element):active::before { - background-image: -webkit-canvas(details-section-disclosure-triangle-open-active); -} - -.details-section.collapsed > .header::before { - background-image: -webkit-canvas(details-section-disclosure-triangle-closed-normal); -} - -.details-section.collapsed > .header:not(.mouse-over-options-element):active::before { - background-image: -webkit-canvas(details-section-disclosure-triangle-closed-active); -} - -.details-section > .header > label { - float: right; - font-size: 10px; - color: rgba(0, 0, 0, 0.6); - text-align: right; -} - -.details-section.collapsed > .header > label { - display: none; -} - -.details-section > .header > label > input[type="checkbox"] { - margin: 0 0 0 5px; - vertical-align: 1px; - font-size: 10px; -} - -.details-section > .header > .node-link, -.details-section > .header > .go-to-arrow { - float: right; -} - -.details-section > .header .go-to-arrow { - width: 10px; - height: 12px; - margin-left: 3px; -} - -.details-section > .content { - display: table; - table-layout: fixed; - width: 100%; - border-spacing: 0; - border-collapse: collapse; -} - -.details-section.collapsed > .content { - display: none; -} - -.details-section > .content > .group { - display: table-row-group; -} - -.details-section > .content > .group:nth-child(even) { - background-color: rgb(222, 222, 222); -} - -.details-section > .content > .group:nth-child(even) > .row:not(.simple):first-child, -.details-section > .content > .group:nth-child(even) > .row.simple:first-child > * { - border-top: 1px solid rgb(153, 153, 153); -} - -.details-section > .content > .group:nth-child(even) > .row:not(.simple):last-child, -.details-section > .content > .group:last-child > .row:not(.simple):last-child, -.details-section > .content > .group:nth-child(even) > .row.simple:last-child > *, -.details-section > .content > .group:last-child > .row.simple:last-child > * { - border-bottom: 1px solid rgb(153, 153, 153); -} - -.details-section > .content > .group > .row.simple { - display: table-row; -} - -.details-section > .content > .group > .row.simple:last-child > * { - padding-bottom: 5px !important; -} - -.details-section > .content > .group > .row.simple.empty { - display: none; -} - -.details-section > .content > .group > .row.empty.syntax-highlighted { - font-family: "Lucida Grande", sans-serif; - font-size: 10px; -} - -.details-section > .content > .group > .row.simple.empty:last-child { - display: table-row; -} - -.details-section > .content > .group > .row.simple.empty:last-child > * { - display: table-cell; - height: 1px; - font-size: 0; - color: transparent; - padding-top: 0; - padding-bottom: 3px !important; -} - -.details-section > .content > .group > .row.simple.empty:last-child > * > * { - display: none; -} - -.details-section > .content > .group > .row.simple > * { - display: table-cell; - vertical-align: top; - padding: 5px 4px 2px; -} - -.details-section > .content > .group > .row.simple > .label { - color: rgb(51, 51, 51); - - text-align: right; - - padding-left: 6px; - - width: 85px; -} - -.details-section > .content > .group > .row.simple > .value { - word-wrap: break-word; - - padding-right: 6px; - - -webkit-user-select: text; - cursor: text; -} - -.details-section > .content > .group > .row.simple > .value .go-to-arrow { - width: 10px; - height: 12px; - margin-left: 5px; -} - -.details-section > .content > .group > .row.simple.data > .value { - word-break: break-all; -} - -.details-section > .content > .group > .row.empty { - padding: 6px; - text-align: center; - color: gray; -} - -.details-section > .content > .group > .row.properties:not(.empty) { - padding: 4px 6px; -} - -.details-section > .content .data-grid { - border: none; -} - -.details-section > .content .data-grid table.data { - background-image: none; -} - -.details-section > .content .data-grid tr:nth-child(even) { - background-color: white; -} - -.details-section > .content .data-grid tr:nth-child(odd) { - background-color: rgb(243, 246, 250); -} - -.details-section > .content .data-grid td.value-column { - height: auto; - line-height: initial; - white-space: normal; -} - -.details-section > .content .data-grid td.value-column > div { - white-space: normal; - word-break: break-all; -} diff --git a/Source/WebInspectorUI/UserInterface/DetailsSection.js b/Source/WebInspectorUI/UserInterface/DetailsSection.js deleted file mode 100644 index 0b1296578..000000000 --- a/Source/WebInspectorUI/UserInterface/DetailsSection.js +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.DetailsSection = function(identifier, title, groups, optionsElement, defaultCollapsedSettingValue) { - WebInspector.Object.call(this); - - console.assert(identifier); - - this._element = document.createElement("div"); - this._element.className = WebInspector.DetailsSection.StyleClassName; - this._element.classList.add(identifier); - - this._headerElement = document.createElement("div"); - this._headerElement.addEventListener("click", this._headerElementClicked.bind(this)); - this._headerElement.className = WebInspector.DetailsSection.HeaderElementStyleClassName; - this._element.appendChild(this._headerElement); - - if (optionsElement instanceof HTMLElement) { - this._optionsElement = optionsElement; - this._optionsElement.addEventListener("mousedown", this._optionsElementMouseDown.bind(this)); - this._optionsElement.addEventListener("mouseup", this._optionsElementMouseUp.bind(this)); - this._headerElement.appendChild(this._optionsElement); - } - - this._titleElement = document.createElement("span"); - this._headerElement.appendChild(this._titleElement); - - this._contentElement = document.createElement("div"); - this._contentElement.className = WebInspector.DetailsSection.ContentElementStyleClassName; - this._element.appendChild(this._contentElement); - - this._generateDisclosureTrianglesIfNeeded(); - - this._identifier = identifier; - this.title = title; - this.groups = groups || [new WebInspector.DetailsSectionGroup]; - - this._collapsedSetting = new WebInspector.Setting(identifier + "-details-section-collapsed", !!defaultCollapsedSettingValue); - this.collapsed = this._collapsedSetting.value; -}; - -WebInspector.DetailsSection.StyleClassName = "details-section"; -WebInspector.DetailsSection.HeaderElementStyleClassName = "header"; -WebInspector.DetailsSection.TitleElementStyleClassName = "title"; -WebInspector.DetailsSection.ContentElementStyleClassName = "content"; -WebInspector.DetailsSection.CollapsedStyleClassName = "collapsed"; -WebInspector.DetailsSection.MouseOverOptionsElementStyleClassName = "mouse-over-options-element"; -WebInspector.DetailsSection.DisclosureTriangleOpenCanvasIdentifier = "details-section-disclosure-triangle-open"; -WebInspector.DetailsSection.DisclosureTriangleClosedCanvasIdentifier = "details-section-disclosure-triangle-closed"; -WebInspector.DetailsSection.DisclosureTriangleNormalCanvasIdentifierSuffix = "-normal"; -WebInspector.DetailsSection.DisclosureTriangleActiveCanvasIdentifierSuffix = "-active"; - -WebInspector.DetailsSection.prototype = { - constructor: WebInspector.DetailsSection, - - // Public - - get element() - { - return this._element; - }, - - get identifier() - { - return this._identifier; - }, - - get title() - { - return this._titleElement.textContent; - }, - - set title(title) - { - this._titleElement.textContent = title; - }, - - get collapsed() - { - return this._element.classList.contains(WebInspector.DetailsSection.CollapsedStyleClassName); - }, - - set collapsed(flag) - { - if (flag) - this._element.classList.add(WebInspector.DetailsSection.CollapsedStyleClassName); - else - this._element.classList.remove(WebInspector.DetailsSection.CollapsedStyleClassName); - - this._collapsedSetting.value = flag || false; - }, - - get groups() - { - return this._groups; - }, - - set groups(groups) - { - this._contentElement.removeChildren(); - - this._groups = groups || []; - - for (var i = 0; i < this._groups.length; ++i) - this._contentElement.appendChild(this._groups[i].element); - }, - - // Private - - _headerElementClicked: function(event) - { - if (event.target.isSelfOrDescendant(this._optionsElement)) - return; - - this.collapsed = !this.collapsed; - - this._element.scrollIntoViewIfNeeded(false); - }, - - _optionsElementMouseDown: function(event) - { - this._headerElement.classList.add(WebInspector.DetailsSection.MouseOverOptionsElementStyleClassName); - }, - - _optionsElementMouseUp: function(event) - { - this._headerElement.classList.remove(WebInspector.DetailsSection.MouseOverOptionsElementStyleClassName); - }, - - _generateDisclosureTrianglesIfNeeded: function() - { - if (WebInspector.DetailsSection._generatedDisclosureTriangles) - return; - - // Set this early instead of in _generateDisclosureTriangle because we don't want multiple sections that are - // created at the same time to duplicate the work (even though it would be harmless.) - WebInspector.DetailsSection._generatedDisclosureTriangles = true; - - var specifications = {}; - specifications[WebInspector.DetailsSection.DisclosureTriangleNormalCanvasIdentifierSuffix] = { - fillColor: [134, 134, 134] - }; - - specifications[WebInspector.DetailsSection.DisclosureTriangleActiveCanvasIdentifierSuffix] = { - fillColor: [57, 57, 57] - }; - - generateColoredImagesForCSS("Images/DisclosureTriangleSmallOpen.svg", specifications, 13, 13, WebInspector.DetailsSection.DisclosureTriangleOpenCanvasIdentifier); - generateColoredImagesForCSS("Images/DisclosureTriangleSmallClosed.svg", specifications, 13, 13, WebInspector.DetailsSection.DisclosureTriangleClosedCanvasIdentifier); - } -}; - -WebInspector.DetailsSection.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/DetailsSectionDataGridRow.js b/Source/WebInspectorUI/UserInterface/DetailsSectionDataGridRow.js deleted file mode 100644 index 95b7bd431..000000000 --- a/Source/WebInspectorUI/UserInterface/DetailsSectionDataGridRow.js +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.DetailsSectionDataGridRow = function(dataGrid, emptyMessage) { - WebInspector.DetailsSectionRow.call(this, emptyMessage); - - this.element.classList.add(WebInspector.DetailsSectionDataGridRow.StyleClassName); - - this.dataGrid = dataGrid; -}; - -WebInspector.DetailsSectionDataGridRow.StyleClassName = "data-grid"; - -WebInspector.DetailsSectionDataGridRow.prototype = { - constructor: WebInspector.DetailsSectionDataGridRow, - - // Public - - get dataGrid() - { - return this._dataGrid; - }, - - set dataGrid(dataGrid) - { - if (this._dataGrid === dataGrid) - return; - - this._dataGrid = dataGrid || null; - - if (dataGrid) { - dataGrid.element.classList.add("inline"); - - this.hideEmptyMessage(); - this.element.appendChild(dataGrid.element); - } else - this.showEmptyMessage(); - } -}; - -WebInspector.DetailsSectionDataGridRow.prototype.__proto__ = WebInspector.DetailsSectionRow.prototype; diff --git a/Source/WebInspectorUI/UserInterface/DetailsSectionGroup.js b/Source/WebInspectorUI/UserInterface/DetailsSectionGroup.js deleted file mode 100644 index 91d4e7b23..000000000 --- a/Source/WebInspectorUI/UserInterface/DetailsSectionGroup.js +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.DetailsSectionGroup = function(rows) { - WebInspector.Object.call(this); - - this._element = document.createElement("div"); - this._element.className = WebInspector.DetailsSectionGroup.StyleClassName; - - this.rows = rows; -}; - -WebInspector.DetailsSectionGroup.StyleClassName = "group"; - -WebInspector.DetailsSectionGroup.prototype = { - constructor: WebInspector.DetailsSectionGroup, - - // Public - - get element() - { - return this._element; - }, - - get rows() - { - return this._rows; - }, - - set rows(rows) - { - this._element.removeChildren(); - - this._rows = rows || []; - - for (var i = 0; i < this._rows.length; ++i) - this._element.appendChild(this._rows[i].element); - } -}; - -WebInspector.DetailsSectionGroup.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/DetailsSectionPropertiesRow.js b/Source/WebInspectorUI/UserInterface/DetailsSectionPropertiesRow.js deleted file mode 100644 index a98615277..000000000 --- a/Source/WebInspectorUI/UserInterface/DetailsSectionPropertiesRow.js +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.DetailsSectionPropertiesRow = function(propertiesSection, emptyMessage) { - WebInspector.DetailsSectionRow.call(this, emptyMessage); - - this.element.classList.add(WebInspector.DetailsSectionPropertiesRow.StyleClassName); - this.element.classList.add(WebInspector.SyntaxHighlightedStyleClassName); - - this.propertiesSection = propertiesSection; -}; - -WebInspector.DetailsSectionPropertiesRow.StyleClassName = "properties"; - -WebInspector.DetailsSectionPropertiesRow.prototype = { - constructor: WebInspector.DetailsSectionPropertiesRow, - - // Public - - get propertiesSection() - { - return this._propertiesSection; - }, - - set propertiesSection(propertiesSection) - { - this._propertiesSection = propertiesSection || null; - - if (propertiesSection) { - // Call expand to cause the section to populate. - propertiesSection.expand(); - - this.hideEmptyMessage(); - this.element.appendChild(propertiesSection.element); - } else - this.showEmptyMessage(); - } -}; - -WebInspector.DetailsSectionPropertiesRow.prototype.__proto__ = WebInspector.DetailsSectionRow.prototype; diff --git a/Source/WebInspectorUI/UserInterface/DetailsSectionRow.js b/Source/WebInspectorUI/UserInterface/DetailsSectionRow.js deleted file mode 100644 index f19584792..000000000 --- a/Source/WebInspectorUI/UserInterface/DetailsSectionRow.js +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.DetailsSectionRow = function(emptyMessage) { - WebInspector.Object.call(this); - - this._element = document.createElement("div"); - this._element.className = WebInspector.DetailsSectionRow.StyleClassName; - - this._emptyMessage = emptyMessage || ""; -}; - -WebInspector.DetailsSectionRow.StyleClassName = "row"; -WebInspector.DetailsSectionRow.EmptyStyleClassName = "empty"; - -WebInspector.DetailsSectionRow.prototype = { - constructor: WebInspector.DetailsSectionRow, - - // Public - - get element() - { - return this._element; - }, - - get emptyMessage() - { - return this._emptyMessage; - }, - - set emptyMessage(emptyMessage) - { - this._emptyMessage = emptyMessage || ""; - - if (!this.childNodes.length) - this.showEmptyMessage(); - }, - - showEmptyMessage: function() - { - this.element.classList.add(WebInspector.DetailsSectionRow.EmptyStyleClassName); - - if (this._emptyMessage instanceof Node) { - this.element.removeChildren(); - this.element.appendChild(this._emptyMessage); - } else - this.element.textContent = this._emptyMessage; - }, - - hideEmptyMessage: function() - { - this.element.classList.remove(WebInspector.DetailsSectionRow.EmptyStyleClassName); - this.element.removeChildren(); - } -}; - -WebInspector.DetailsSectionRow.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/DetailsSectionSimpleRow.js b/Source/WebInspectorUI/UserInterface/DetailsSectionSimpleRow.js deleted file mode 100644 index d6c7e0e87..000000000 --- a/Source/WebInspectorUI/UserInterface/DetailsSectionSimpleRow.js +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.DetailsSectionSimpleRow = function(label, value) { - WebInspector.DetailsSectionRow.call(this); - - this.element.classList.add(WebInspector.DetailsSectionSimpleRow.StyleClassName); - - this._labelElement = document.createElement("div"); - this._labelElement.className = WebInspector.DetailsSectionSimpleRow.LabelElementStyleClassName; - this.element.appendChild(this._labelElement); - - this._valueElement = document.createElement("div"); - this._valueElement.className = WebInspector.DetailsSectionSimpleRow.ValueElementStyleClassName; - this.element.appendChild(this._valueElement); - - // Workaround for Triple-clicking text within a - //
      set to "display: table-cell" selects text outside the cell. - // - // On triple-click, adjust the selection range to include only the value - // element if the selection extends beyond it. - var valueElementClicked = function(event) { - event.stopPropagation(); - - if (event.detail < 3) - return; - - var currentSelection = window.getSelection(); - if (!currentSelection) - return; - - var currentRange = currentSelection.getRangeAt(0); - if (!currentRange || currentRange.startContainer == currentRange.endContainer) - return; - - var correctedRange = document.createRange(); - correctedRange.selectNodeContents(event.currentTarget); - currentSelection.removeAllRanges(); - currentSelection.addRange(correctedRange); - }; - this._valueElement.addEventListener("click", valueElementClicked); - - this.label = label; - this.value = value; -}; - -WebInspector.DetailsSectionSimpleRow.StyleClassName = "simple"; -WebInspector.DetailsSectionSimpleRow.DataStyleClassName = "data"; -WebInspector.DetailsSectionSimpleRow.EmptyStyleClassName = "empty"; -WebInspector.DetailsSectionSimpleRow.LabelElementStyleClassName = "label"; -WebInspector.DetailsSectionSimpleRow.ValueElementStyleClassName = "value"; - -WebInspector.DetailsSectionSimpleRow.prototype = { - constructor: WebInspector.DetailsSectionSimpleRow, - - // Public - - get label() - { - return this._labelElement.textContent; - }, - - set label(label) - { - this._labelElement.textContent = label; - }, - - get value() - { - return this._value; - }, - - set value(value) - { - this._value = value || ""; - - if (this._value) { - this.element.classList.remove(WebInspector.DetailsSectionSimpleRow.EmptyStyleClassName); - - // If the value has space characters that cause word wrapping then we don't need the data class. - if (/[\s\u200b]/.test(this._value)) - this.element.classList.remove(WebInspector.DetailsSectionSimpleRow.DataStyleClassName); - else - this.element.classList.add(WebInspector.DetailsSectionSimpleRow.DataStyleClassName); - } else { - this.element.classList.add(WebInspector.DetailsSectionSimpleRow.EmptyStyleClassName); - this.element.classList.remove(WebInspector.DetailsSectionSimpleRow.DataStyleClassName); - } - - if (value instanceof Node) { - this._valueElement.removeChildren(); - this._valueElement.appendChild(this._value); - } else - this._valueElement.textContent = this._value; - } -}; - -WebInspector.DetailsSectionSimpleRow.prototype.__proto__ = WebInspector.DetailsSectionRow.prototype; diff --git a/Source/WebInspectorUI/UserInterface/DetailsSidebarPanel.css b/Source/WebInspectorUI/UserInterface/DetailsSidebarPanel.css deleted file mode 100644 index 5bb2e6e83..000000000 --- a/Source/WebInspectorUI/UserInterface/DetailsSidebarPanel.css +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.sidebar > .panel.details { - overflow-x: hidden; - overflow-y: auto; -} diff --git a/Source/WebInspectorUI/UserInterface/DetailsSidebarPanel.js b/Source/WebInspectorUI/UserInterface/DetailsSidebarPanel.js deleted file mode 100644 index 70317e651..000000000 --- a/Source/WebInspectorUI/UserInterface/DetailsSidebarPanel.js +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.DetailsSidebarPanel = function(identifier, displayName, singularDisplayName, image, keyboardShortcutKey, element) { - if (keyboardShortcutKey) - this._keyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.Control | WebInspector.KeyboardShortcut.Modifier.Shift, keyboardShortcutKey, this.toggle.bind(this)); - - if (this._keyboardShortcut) { - var showToolTip = WebInspector.UIString("Show the %s details sidebar (%s)").format(singularDisplayName, this._keyboardShortcut.displayName); - var hideToolTip = WebInspector.UIString("Hide the %s details sidebar (%s)").format(singularDisplayName, this._keyboardShortcut.displayName); - } else { - var showToolTip = WebInspector.UIString("Show the %s details sidebar").format(singularDisplayName); - var hideToolTip = WebInspector.UIString("Hide the %s details sidebar").format(singularDisplayName); - } - - WebInspector.SidebarPanel.call(this, identifier, displayName, showToolTip, hideToolTip, image, element); - - this.element.classList.add(WebInspector.DetailsSidebarPanel.StyleClassName); -}; - -WebInspector.DetailsSidebarPanel.StyleClassName = "details"; - -WebInspector.DetailsSidebarPanel.prototype = { - constructor: WebInspector.DetailsSidebarPanel, - - // Public - - inspect: function(objects) - { - // Implemented by subclasses. - return false; - }, - - shown: function() - { - if (this._needsRefresh) { - delete this._needsRefresh; - this.refresh(); - } - }, - - needsRefresh: function() - { - if (!this.selected) { - this._needsRefresh = true; - return; - } - - this.refresh(); - }, - - refresh: function() - { - // Implemented by subclasses. - } -}; - -WebInspector.DetailsSidebarPanel.prototype.__proto__ = WebInspector.SidebarPanel.prototype; diff --git a/Source/WebInspectorUI/UserInterface/DividerNavigationItem.css b/Source/WebInspectorUI/UserInterface/DividerNavigationItem.css deleted file mode 100644 index cbadc5b6e..000000000 --- a/Source/WebInspectorUI/UserInterface/DividerNavigationItem.css +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.navigation-bar .item.divider { - width: 1px; - - background-image: -webkit-linear-gradient(rgb(190, 190, 190), rgb(190, 190, 190)); - background-size: 100% 13px; - background-repeat: no-repeat; - background-position: center; -} diff --git a/Source/WebInspectorUI/UserInterface/DividerNavigationItem.js b/Source/WebInspectorUI/UserInterface/DividerNavigationItem.js deleted file mode 100644 index 5e9767a02..000000000 --- a/Source/WebInspectorUI/UserInterface/DividerNavigationItem.js +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.DividerNavigationItem = function(identifier) { - WebInspector.NavigationItem.call(this, identifier); -}; - -WebInspector.DividerNavigationItem.StyleClassName = "divider"; - -WebInspector.DividerNavigationItem.prototype = { - constructor: WebInspector.DividerNavigationItem, - - // Private - - _additionalClassNames: [WebInspector.DividerNavigationItem.StyleClassName], -}; - -WebInspector.DividerNavigationItem.prototype.__proto__ = WebInspector.NavigationItem.prototype; diff --git a/Source/WebInspectorUI/UserInterface/Editing.css b/Source/WebInspectorUI/UserInterface/Editing.css deleted file mode 100644 index f68c02170..000000000 --- a/Source/WebInspectorUI/UserInterface/Editing.css +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.editing { - -webkit-user-select: text; - box-shadow: rgba(0, 0, 0, .5) 3px 3px 4px; - outline: 1px solid rgb(66%, 66%, 66%) !important; - background-color: white; - -webkit-user-modify: read-write-plaintext-only; - text-overflow: clip !important; - padding-left: 2px; - margin-left: -2px; - padding-right: 2px; - margin-right: -2px; - margin-bottom: -1px; - padding-bottom: 1px; - opacity: 1.0 !important; -} - -.editing.multiline { - white-space: pre-wrap; -} - -.editing, .editing * { - color: black !important; - text-decoration: none !important; -} - -.editing br { - display: none; -} diff --git a/Source/WebInspectorUI/UserInterface/EditingSupport.js b/Source/WebInspectorUI/UserInterface/EditingSupport.js deleted file mode 100644 index 119299940..000000000 --- a/Source/WebInspectorUI/UserInterface/EditingSupport.js +++ /dev/null @@ -1,271 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.isBeingEdited = function(element) -{ - while (element) { - if (element.__editing) - return true; - element = element.parentNode; - } - - return false; -} - -WebInspector.markBeingEdited = function(element, value) -{ - if (value) { - if (element.__editing) - return false; - element.__editing = true; - WebInspector.__editingCount = (WebInspector.__editingCount || 0) + 1; - } else { - if (!element.__editing) - return false; - delete element.__editing; - --WebInspector.__editingCount; - } - return true; -} - -WebInspector.isEditingAnyField = function() -{ - return !!WebInspector.__editingCount; -} - -WebInspector.isEventTargetAnEditableField = function(event) -{ - const textInputTypes = {"text": true, "search": true, "tel": true, "url": true, "email": true, "password": true}; - if (event.target instanceof HTMLInputElement) - return event.target.type in textInputTypes; - - var codeMirrorEditorElement = event.target.enclosingNodeOrSelfWithClass("CodeMirror"); - if (codeMirrorEditorElement && codeMirrorEditorElement.CodeMirror) - return !codeMirrorEditorElement.CodeMirror.getOption("readOnly"); - - if (event.target instanceof HTMLTextAreaElement) - return true; - - if (event.target.enclosingNodeOrSelfWithClass("text-prompt")) - return true; - - return false; -} - -/** - * @constructor - * @param {function(Element,string,string,*,string)} commitHandler - * @param {function(Element,*)} cancelHandler - * @param {*=} context - */ -WebInspector.EditingConfig = function(commitHandler, cancelHandler, context) -{ - this.commitHandler = commitHandler; - this.cancelHandler = cancelHandler; - this.context = context; - - /** - * Handles the "paste" event, return values are the same as those for customFinishHandler - * @type {function(Element)|undefined} - */ - this.pasteHandler; - - /** - * Whether the edited element is multiline - * @type {boolean|undefined} - */ - this.multiline; - - /** - * Custom finish handler for the editing session (invoked on keydown) - * @type {function(Element,*)|undefined} - */ - this.customFinishHandler; - - /** - * Whether or not spellcheck is enabled. - * @type {boolean} - */ - this.spellcheck = false; -} - -WebInspector.EditingConfig.prototype = { - setPasteHandler: function(pasteHandler) - { - this.pasteHandler = pasteHandler; - }, - - setMultiline: function(multiline) - { - this.multiline = multiline; - }, - - setCustomFinishHandler: function(customFinishHandler) - { - this.customFinishHandler = customFinishHandler; - } -} - -/** - * @param {Element} element - * @param {WebInspector.EditingConfig=} config - */ -WebInspector.startEditing = function(element, config) -{ - if (!WebInspector.markBeingEdited(element, true)) - return; - - config = config || new WebInspector.EditingConfig(function() {}, function() {}); - var committedCallback = config.commitHandler; - var cancelledCallback = config.cancelHandler; - var pasteCallback = config.pasteHandler; - var context = config.context; - var oldText = getContent(element); - var moveDirection = ""; - - element.classList.add("editing"); - - var oldSpellCheck = element.hasAttribute("spellcheck") ? element.spellcheck : undefined; - element.spellcheck = config.spellcheck; - - if (config.multiline) - element.classList.add("multiline"); - - var oldTabIndex = element.tabIndex; - if (element.tabIndex < 0) - element.tabIndex = 0; - - function blurEventListener() { - editingCommitted.call(element); - } - - function getContent(element) { - if (element.tagName === "INPUT" && element.type === "text") - return element.value; - else - return element.textContent; - } - - /** @this {Element} */ - function cleanUpAfterEditing() - { - WebInspector.markBeingEdited(element, false); - - this.classList.remove("editing"); - this.scrollTop = 0; - this.scrollLeft = 0; - - if (oldSpellCheck === undefined) - element.removeAttribute("spellcheck"); - else - element.spellcheck = oldSpellCheck; - - if (oldTabIndex === -1) - this.removeAttribute("tabindex"); - else - this.tabIndex = oldTabIndex; - - element.removeEventListener("blur", blurEventListener, false); - element.removeEventListener("keydown", keyDownEventListener, true); - if (pasteCallback) - element.removeEventListener("paste", pasteEventListener, true); - - WebInspector.restoreFocusFromElement(element); - } - - /** @this {Element} */ - function editingCancelled() - { - if (this.tagName === "INPUT" && this.type === "text") - this.value = oldText; - else - this.textContent = oldText; - - cleanUpAfterEditing.call(this); - - cancelledCallback(this, context); - } - - /** @this {Element} */ - function editingCommitted() - { - cleanUpAfterEditing.call(this); - - committedCallback(this, getContent(this), oldText, context, moveDirection); - } - - function defaultFinishHandler(event) - { - var hasOnlyMetaModifierKey = event.metaKey && !event.shiftKey && !event.ctrlKey && !event.altKey; - if (isEnterKey(event) && (!config.multiline || hasOnlyMetaModifierKey)) - return "commit"; - else if (event.keyCode === WebInspector.KeyboardShortcut.Key.Escape.keyCode || event.keyIdentifier === "U+001B") - return "cancel"; - else if (event.keyIdentifier === "U+0009") // Tab key - return "move-" + (event.shiftKey ? "backward" : "forward"); - } - - function handleEditingResult(result, event) - { - if (result === "commit") { - editingCommitted.call(element); - event.preventDefault(); - event.stopPropagation(); - } else if (result === "cancel") { - editingCancelled.call(element); - event.preventDefault(); - event.stopPropagation(); - } else if (result && result.startsWith("move-")) { - moveDirection = result.substring(5); - if (event.keyIdentifier !== "U+0009") - blurEventListener(); - } - } - - function pasteEventListener(event) - { - var result = pasteCallback(event); - handleEditingResult(result, event); - } - - function keyDownEventListener(event) - { - var handler = config.customFinishHandler || defaultFinishHandler; - var result = handler(event); - handleEditingResult(result, event); - } - - element.addEventListener("blur", blurEventListener, false); - element.addEventListener("keydown", keyDownEventListener, true); - if (pasteCallback) - element.addEventListener("paste", pasteEventListener, true); - - element.focus(); - - return { - cancel: editingCancelled.bind(element), - commit: editingCommitted.bind(element) - }; -} diff --git a/Source/WebInspectorUI/UserInterface/EventHandler.js b/Source/WebInspectorUI/UserInterface/EventHandler.js deleted file mode 100644 index ff9d3720e..000000000 --- a/Source/WebInspectorUI/UserInterface/EventHandler.js +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.EventHandler = function(delegate, eventHandlers) -{ - this._delegate = delegate; - this._eventHandlers = eventHandlers; - - this._tracking = false; - this._target = null; -}; - -WebInspector.EventHandler.prototype = { - constructor: WebInspector.EventHandler, - - // Public - - trackEvents: function(target) - { - if (this._tracking && target === this._target) - return; - - if (this._tracking && this._target) - this.stopTrackingEvents(); - - Object.getOwnPropertyNames(this._eventHandlers).forEach(function(eventName) { - target.addEventListener(eventName, this); - }, this); - - this._target = target; - this._tracking = true; - }, - - stopTrackingEvents: function() - { - if (!this._tracking) - return; - - Object.getOwnPropertyNames(this._eventHandlers).forEach(function(eventType) { - this._target.removeEventListener(eventType, this); - }, this); - - this._tracking = false; - }, - - handleEvent: function(event) - { - if (event.currentTarget !== this._target) - return; - - var handler = this._eventHandlers[event.type]; - if (handler) - handler.call(this._delegate, event); - } -} - -WebInspector.EventHandler.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/EventListenerSection.js b/Source/WebInspectorUI/UserInterface/EventListenerSection.js deleted file mode 100644 index e74b4546e..000000000 --- a/Source/WebInspectorUI/UserInterface/EventListenerSection.js +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.EventListenerSection = function(type, nodeId) -{ - WebInspector.DetailsSection.call(this, type + "-event-listener-section", type, [], null, true); - - this.element.classList.add("event-listener-section"); - - this._nodeId = nodeId; -} - -WebInspector.EventListenerSection.prototype = { - constructor: WebInspector.EventListenerSection, - - addListener: function(eventListener) - { - var groups = this.groups; - groups.push(new WebInspector.EventListenerSectionGroup(eventListener, this._nodeId)); - this.groups = groups; - } -} - -WebInspector.EventListenerSection.prototype.__proto__ = WebInspector.DetailsSection.prototype; diff --git a/Source/WebInspectorUI/UserInterface/EventListenerSectionGroup.css b/Source/WebInspectorUI/UserInterface/EventListenerSectionGroup.css deleted file mode 100644 index 00b18892e..000000000 --- a/Source/WebInspectorUI/UserInterface/EventListenerSectionGroup.css +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.event-listener-section > .content > .group > .row.simple > .value { - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; -} diff --git a/Source/WebInspectorUI/UserInterface/EventListenerSectionGroup.js b/Source/WebInspectorUI/UserInterface/EventListenerSectionGroup.js deleted file mode 100644 index 2d8ec9022..000000000 --- a/Source/WebInspectorUI/UserInterface/EventListenerSectionGroup.js +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.EventListenerSectionGroup = function(eventListener, nodeId) -{ - this._eventListener = eventListener; - this._nodeId = nodeId; - - var rows = []; - rows.push(new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("Node"), this._nodeTextOrLink())); - rows.push(new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("Function"), this._functionTextOrLink())); - rows.push(new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("Type"), this._type())); - - WebInspector.DetailsSectionGroup.call(this, rows); -} - -WebInspector.EventListenerSectionGroup.prototype = { - constructor: WebInspector.EventListenerSectionGroup, - - _nodeTextOrLink: function() - { - var node = this._eventListener.node; - if (!node) - return; - - if (node.nodeType() === Node.DOCUMENT_NODE) - return "document"; - - return WebInspector.linkifyNodeReference(node); - }, - - _type: function() - { - if (this._eventListener.useCapture) - return WebInspector.UIString("Capturing"); - - if (this._eventListener.isAttribute) - return WebInspector.UIString("Attribute"); - - return WebInspector.UIString("Bubbling"); - }, - - _functionTextOrLink: function() - { - var match = this._eventListener.handlerBody.match(/function ([^\(]+?)\(/); - if (match) { - var anonymous = false; - var functionName = match[1]; - } else { - var anonymous = true; - var functionName = WebInspector.UIString("(anonymous function)"); - } - - if (!this._eventListener.location) - return functionName; - - // COMPATIBILITY (iOS 6): In the past scriptId could be a URL. Now it is always a script identifier. - // So try looking up the resource by URL if a script can't be found directly. - var scriptIdentifierOrURL = this._eventListener.location.scriptId; - var sourceCode = WebInspector.debuggerManager.scriptForIdentifier(scriptIdentifierOrURL); - if (!sourceCode) - sourceCode = WebInspector.frameResourceManager.resourceForURL(scriptIdentifierOrURL); - - if (!sourceCode) - return functionName; - - var sourceCodeLocation = sourceCode.createSourceCodeLocation(this._eventListener.location.lineNumber, this._eventListener.location.columnNumber || 0); - var linkElement = WebInspector.createSourceCodeLocationLink(sourceCodeLocation, anonymous); - if (anonymous) - return linkElement; - - var fragment = document.createDocumentFragment(); - fragment.appendChild(linkElement); - fragment.appendChild(document.createTextNode(functionName)); - return fragment; - } -} - -WebInspector.EventListenerSectionGroup.prototype.__proto__ = WebInspector.DetailsSectionGroup.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ExecutionContext.js b/Source/WebInspectorUI/UserInterface/ExecutionContext.js deleted file mode 100644 index 0b8b81d40..000000000 --- a/Source/WebInspectorUI/UserInterface/ExecutionContext.js +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ExecutionContext = function(id, name, isPageContext, frame) -{ - WebInspector.Object.call(this); - - console.assert(typeof id === "number" || id === WebInspector.QuickConsole.MainFrameContextExecutionIdentifier); - console.assert(typeof name === "string"); - - this._id = id; - this._name = name; - this._isPageContext = isPageContext || false; - this._frame = frame || null; -}; - -WebInspector.ExecutionContext.supported = function() -{ - // Execution contexts were added to the Inspector protocol alongside RuntimeAgent.enable and - // disable methods, which turn on and off sending Runtime agent execution context created events. - // So we can feature detect support for execution contexts with these RuntimeAgent functions. - return typeof RuntimeAgent.enable === "function"; -} - -WebInspector.ExecutionContext.prototype = { - constructor: WebInspector.ExecutionContext, - - // Public - - get id() - { - return this._id; - }, - - get name() - { - return this._name; - }, - - get isPageContext() - { - return this._isPageContext; - }, - - get frame() - { - return this._frame; - } -}; - -WebInspector.ExecutionContext.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ExecutionContextList.js b/Source/WebInspectorUI/UserInterface/ExecutionContextList.js deleted file mode 100644 index c806c270f..000000000 --- a/Source/WebInspectorUI/UserInterface/ExecutionContextList.js +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ExecutionContextList = function() -{ - WebInspector.Object.call(this); - - this._contexts = []; - this._pageExecutionContext = null; -}; - -WebInspector.ExecutionContextList.prototype = { - constructor: WebInspector.ExecutionContextList, - - // Public - - get pageExecutionContext() - { - return this._pageExecutionContext; - }, - - get contexts() - { - return this._contexts; - }, - - add: function(context) - { - // FIXME: The backend sends duplicate page context execution contexts with the same id. Why? - if (context.isPageContext && this._pageExecutionContext) { - console.assert(context.id === this._pageExecutionContext.id); - return false; - } - - this._contexts.push(context); - - if (context.isPageContext) { - console.assert(!this._pageExecutionContext); - this._pageExecutionContext = context; - return true; - } - - return false; - }, - - clear: function() - { - this._contexts = []; - this._pageExecutionContext = null; - } -}; - -WebInspector.ExecutionContextList.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/External/.eslintrc b/Source/WebInspectorUI/UserInterface/External/.eslintrc new file mode 100644 index 000000000..ecab33702 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/External/.eslintrc @@ -0,0 +1,30 @@ +/* + * Copyright (C) 2014 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +{ + "rules": { + "eqeqeq": 0 + } +} diff --git a/Source/WebInspectorUI/UserInterface/External/CodeMirror/LICENSE b/Source/WebInspectorUI/UserInterface/External/CodeMirror/LICENSE new file mode 100644 index 000000000..766132177 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/External/CodeMirror/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2016 by Marijn Haverbeke and others + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/Source/WebInspectorUI/UserInterface/External/CodeMirror/clojure.js b/Source/WebInspectorUI/UserInterface/External/CodeMirror/clojure.js index ee22a12fe..ed6af2c83 100644 --- a/Source/WebInspectorUI/UserInterface/External/CodeMirror/clojure.js +++ b/Source/WebInspectorUI/UserInterface/External/CodeMirror/clojure.js @@ -1,11 +1,26 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + /** * Author: Hans Engel * Branched from CodeMirror's Scheme mode (by Koh Zi Han, based on implementation by Koh Zi Chun) */ -CodeMirror.defineMode("clojure", function () { + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +CodeMirror.defineMode("clojure", function (options) { var BUILTIN = "builtin", COMMENT = "comment", STRING = "string", CHARACTER = "string-2", - ATOM = "atom", NUMBER = "number", BRACKET = "bracket", KEYWORD = "keyword"; - var INDENT_WORD_SKIP = 2; + ATOM = "atom", NUMBER = "number", BRACKET = "bracket", KEYWORD = "keyword", VAR = "variable"; + var INDENT_WORD_SKIP = options.indentUnit || 2; + var NORMAL_INDENT_UNIT = options.indentUnit || 2; function makeKeywords(str) { var obj = {}, words = str.split(" "); @@ -16,14 +31,70 @@ CodeMirror.defineMode("clojure", function () { var atoms = makeKeywords("true false nil"); var keywords = makeKeywords( - "defn defn- def def- defonce defmulti defmethod defmacro defstruct deftype defprotocol defrecord defproject deftest slice defalias defhinted defmacro- defn-memo defnk defnk defonce- defunbound defunbound- defvar defvar- let letfn do case cond condp for loop recur when when-not when-let when-first if if-let if-not . .. -> ->> doto and or dosync doseq dotimes dorun doall load import unimport ns in-ns refer try catch finally throw with-open with-local-vars binding gen-class gen-and-load-class gen-and-save-class handler-case handle"); + "defn defn- def def- defonce defmulti defmethod defmacro defstruct deftype defprotocol defrecord defproject deftest " + + "slice defalias defhinted defmacro- defn-memo defnk defnk defonce- defunbound defunbound- defvar defvar- let letfn " + + "do case cond condp for loop recur when when-not when-let when-first if if-let if-not . .. -> ->> doto and or dosync " + + "doseq dotimes dorun doall load import unimport ns in-ns refer try catch finally throw with-open with-local-vars " + + "binding gen-class gen-and-load-class gen-and-save-class handler-case handle"); var builtins = makeKeywords( - "* *' *1 *2 *3 *agent* *allow-unresolved-vars* *assert* *clojure-version* *command-line-args* *compile-files* *compile-path* *compiler-options* *data-readers* *e *err* *file* *flush-on-newline* *fn-loader* *in* *math-context* *ns* *out* *print-dup* *print-length* *print-level* *print-meta* *print-readably* *read-eval* *source-path* *unchecked-math* *use-context-classloader* *verbose-defrecords* *warn-on-reflection* + +' - -' -> ->> ->ArrayChunk ->Vec ->VecNode ->VecSeq -cache-protocol-fn -reset-methods .. / < <= = == > >= EMPTY-NODE accessor aclone add-classpath add-watch agent agent-error agent-errors aget alength alias all-ns alter alter-meta! alter-var-root amap ancestors and apply areduce array-map aset aset-boolean aset-byte aset-char aset-double aset-float aset-int aset-long aset-short assert assoc assoc! assoc-in associative? atom await await-for await1 bases bean bigdec bigint biginteger binding bit-and bit-and-not bit-clear bit-flip bit-not bit-or bit-set bit-shift-left bit-shift-right bit-test bit-xor boolean boolean-array booleans bound-fn bound-fn* bound? butlast byte byte-array bytes case cast char char-array char-escape-string char-name-string char? chars chunk chunk-append chunk-buffer chunk-cons chunk-first chunk-next chunk-rest chunked-seq? class class? clear-agent-errors clojure-version coll? comment commute comp comparator compare compare-and-set! compile complement concat cond condp conj conj! cons constantly construct-proxy contains? count counted? create-ns create-struct cycle dec dec' decimal? declare default-data-readers definline definterface defmacro defmethod defmulti defn defn- defonce defprotocol defrecord defstruct deftype delay delay? deliver denominator deref derive descendants destructure disj disj! dissoc dissoc! distinct distinct? doall dorun doseq dosync dotimes doto double double-array doubles drop drop-last drop-while empty empty? ensure enumeration-seq error-handler error-mode eval even? every-pred every? ex-data ex-info extend extend-protocol extend-type extenders extends? false? ffirst file-seq filter filterv find find-keyword find-ns find-protocol-impl find-protocol-method find-var first flatten float float-array float? floats flush fn fn? fnext fnil for force format frequencies future future-call future-cancel future-cancelled? future-done? future? gen-class gen-interface gensym get get-in get-method get-proxy-class get-thread-bindings get-validator group-by hash hash-combine hash-map hash-set identical? identity if-let if-not ifn? import in-ns inc inc' init-proxy instance? int int-array integer? interleave intern interpose into into-array ints io! isa? iterate iterator-seq juxt keep keep-indexed key keys keyword keyword? last lazy-cat lazy-seq let letfn line-seq list list* list? load load-file load-reader load-string loaded-libs locking long long-array longs loop macroexpand macroexpand-1 make-array make-hierarchy map map-indexed map? mapcat mapv max max-key memfn memoize merge merge-with meta method-sig methods min min-key mod munge name namespace namespace-munge neg? newline next nfirst nil? nnext not not-any? not-empty not-every? not= ns ns-aliases ns-imports ns-interns ns-map ns-name ns-publics ns-refers ns-resolve ns-unalias ns-unmap nth nthnext nthrest num number? numerator object-array odd? or parents partial partition partition-all partition-by pcalls peek persistent! pmap pop pop! pop-thread-bindings pos? pr pr-str prefer-method prefers primitives-classnames print print-ctor print-dup print-method print-simple print-str printf println println-str prn prn-str promise proxy proxy-call-with-super proxy-mappings proxy-name proxy-super push-thread-bindings pvalues quot rand rand-int rand-nth range ratio? rational? rationalize re-find re-groups re-matcher re-matches re-pattern re-seq read read-line read-string realized? reduce reduce-kv reductions ref ref-history-count ref-max-history ref-min-history ref-set refer refer-clojure reify release-pending-sends rem remove remove-all-methods remove-method remove-ns remove-watch repeat repeatedly replace replicate require reset! reset-meta! resolve rest restart-agent resultset-seq reverse reversible? rseq rsubseq satisfies? second select-keys send send-off seq seq? seque sequence sequential? set set-error-handler! set-error-mode! set-validator! set? short short-array shorts shuffle shutdown-agents slurp some some-fn sort sort-by sorted-map sorted-map-by sorted-set sorted-set-by sorted? special-symbol? spit split-at split-with str string? struct struct-map subs subseq subvec supers swap! symbol symbol? sync take take-last take-nth take-while test the-ns thread-bound? time to-array to-array-2d trampoline transient tree-seq true? type unchecked-add unchecked-add-int unchecked-byte unchecked-char unchecked-dec unchecked-dec-int unchecked-divide-int unchecked-double unchecked-float unchecked-inc unchecked-inc-int unchecked-int unchecked-long unchecked-multiply unchecked-multiply-int unchecked-negate unchecked-negate-int unchecked-remainder-int unchecked-short unchecked-subtract unchecked-subtract-int underive unquote unquote-splicing update-in update-proxy use val vals var-get var-set var? vary-meta vec vector vector-of vector? when when-first when-let when-not while with-bindings with-bindings* with-in-str with-loading-context with-local-vars with-meta with-open with-out-str with-precision with-redefs with-redefs-fn xml-seq zero? zipmap *default-data-reader-fn* as-> cond-> cond->> reduced reduced? send-via set-agent-send-executor! set-agent-send-off-executor! some-> some->>"); + "* *' *1 *2 *3 *agent* *allow-unresolved-vars* *assert* *clojure-version* *command-line-args* *compile-files* " + + "*compile-path* *compiler-options* *data-readers* *e *err* *file* *flush-on-newline* *fn-loader* *in* " + + "*math-context* *ns* *out* *print-dup* *print-length* *print-level* *print-meta* *print-readably* *read-eval* " + + "*source-path* *unchecked-math* *use-context-classloader* *verbose-defrecords* *warn-on-reflection* + +' - -' -> " + + "->> ->ArrayChunk ->Vec ->VecNode ->VecSeq -cache-protocol-fn -reset-methods .. / < <= = == > >= EMPTY-NODE accessor " + + "aclone add-classpath add-watch agent agent-error agent-errors aget alength alias all-ns alter alter-meta! " + + "alter-var-root amap ancestors and apply areduce array-map aset aset-boolean aset-byte aset-char aset-double " + + "aset-float aset-int aset-long aset-short assert assoc assoc! assoc-in associative? atom await await-for await1 " + + "bases bean bigdec bigint biginteger binding bit-and bit-and-not bit-clear bit-flip bit-not bit-or bit-set " + + "bit-shift-left bit-shift-right bit-test bit-xor boolean boolean-array booleans bound-fn bound-fn* bound? butlast " + + "byte byte-array bytes case cat cast char char-array char-escape-string char-name-string char? chars chunk chunk-append " + + "chunk-buffer chunk-cons chunk-first chunk-next chunk-rest chunked-seq? class class? clear-agent-errors " + + "clojure-version coll? comment commute comp comparator compare compare-and-set! compile complement completing concat cond condp " + + "conj conj! cons constantly construct-proxy contains? count counted? create-ns create-struct cycle dec dec' decimal? " + + "declare dedupe default-data-readers definline definterface defmacro defmethod defmulti defn defn- defonce defprotocol " + + "defrecord defstruct deftype delay delay? deliver denominator deref derive descendants destructure disj disj! dissoc " + + "dissoc! distinct distinct? doall dorun doseq dosync dotimes doto double double-array doubles drop drop-last " + + "drop-while eduction empty empty? ensure enumeration-seq error-handler error-mode eval even? every-pred every? ex-data ex-info " + + "extend extend-protocol extend-type extenders extends? false? ffirst file-seq filter filterv find find-keyword " + + "find-ns find-protocol-impl find-protocol-method find-var first flatten float float-array float? floats flush fn fn? " + + "fnext fnil for force format frequencies future future-call future-cancel future-cancelled? future-done? future? " + + "gen-class gen-interface gensym get get-in get-method get-proxy-class get-thread-bindings get-validator group-by hash " + + "hash-combine hash-map hash-set identical? identity if-let if-not ifn? import in-ns inc inc' init-proxy instance? " + + "int int-array integer? interleave intern interpose into into-array ints io! isa? iterate iterator-seq juxt keep " + + "keep-indexed key keys keyword keyword? last lazy-cat lazy-seq let letfn line-seq list list* list? load load-file " + + "load-reader load-string loaded-libs locking long long-array longs loop macroexpand macroexpand-1 make-array " + + "make-hierarchy map map-indexed map? mapcat mapv max max-key memfn memoize merge merge-with meta method-sig methods " + + "min min-key mod munge name namespace namespace-munge neg? newline next nfirst nil? nnext not not-any? not-empty " + + "not-every? not= ns ns-aliases ns-imports ns-interns ns-map ns-name ns-publics ns-refers ns-resolve ns-unalias " + + "ns-unmap nth nthnext nthrest num number? numerator object-array odd? or parents partial partition partition-all " + + "partition-by pcalls peek persistent! pmap pop pop! pop-thread-bindings pos? pr pr-str prefer-method prefers " + + "primitives-classnames print print-ctor print-dup print-method print-simple print-str printf println println-str " + + "prn prn-str promise proxy proxy-call-with-super proxy-mappings proxy-name proxy-super push-thread-bindings pvalues " + + "quot rand rand-int rand-nth random-sample range ratio? rational? rationalize re-find re-groups re-matcher re-matches re-pattern " + + "re-seq read read-line read-string realized? reduce reduce-kv reductions ref ref-history-count ref-max-history " + + "ref-min-history ref-set refer refer-clojure reify release-pending-sends rem remove remove-all-methods " + + "remove-method remove-ns remove-watch repeat repeatedly replace replicate require reset! reset-meta! resolve rest " + + "restart-agent resultset-seq reverse reversible? rseq rsubseq satisfies? second select-keys send send-off seq seq? " + + "seque sequence sequential? set set-error-handler! set-error-mode! set-validator! set? short short-array shorts " + + "shuffle shutdown-agents slurp some some-fn sort sort-by sorted-map sorted-map-by sorted-set sorted-set-by sorted? " + + "special-symbol? spit split-at split-with str string? struct struct-map subs subseq subvec supers swap! symbol " + + "symbol? sync take take-last take-nth take-while test the-ns thread-bound? time to-array to-array-2d trampoline transduce " + + "transient tree-seq true? type unchecked-add unchecked-add-int unchecked-byte unchecked-char unchecked-dec " + + "unchecked-dec-int unchecked-divide-int unchecked-double unchecked-float unchecked-inc unchecked-inc-int " + + "unchecked-int unchecked-long unchecked-multiply unchecked-multiply-int unchecked-negate unchecked-negate-int "+ + "unchecked-remainder-int unchecked-short unchecked-subtract unchecked-subtract-int underive unquote " + + "unquote-splicing update update-in update-proxy use val vals var-get var-set var? vary-meta vec vector vector-of " + + "vector? volatile! volatile? vreset! vswap! when when-first when-let when-not while with-bindings with-bindings* with-in-str with-loading-context " + + "with-local-vars with-meta with-open with-out-str with-precision with-redefs with-redefs-fn xml-seq zero? zipmap " + + "*default-data-reader-fn* as-> cond-> cond->> reduced reduced? send-via set-agent-send-executor! " + + "set-agent-send-off-executor! some-> some->>"); var indentKeys = makeKeywords( // Built-ins - "ns fn def defn defmethod bound-fn if if-not case condp when while when-not when-first do future comment doto locking proxy with-open with-precision reify deftype defrecord defprotocol extend extend-protocol extend-type try catch " + + "ns fn def defn defmethod bound-fn if if-not case condp when while when-not when-first do future comment doto " + + "locking proxy with-open with-precision reify deftype defrecord defprotocol extend extend-protocol extend-type " + + "try catch " + // Binding forms "let letfn binding loop for doseq dotimes when-let if-let " + @@ -44,7 +115,8 @@ CodeMirror.defineMode("clojure", function () { sign: /[+-]/, exponent: /e/i, keyword_char: /[^\s\(\[\;\)\]]/, - symbol: /[\w*+!\-\._?:\/]/ + symbol: /[\w*+!\-\._?:<>\/\xa1-\uffff]/, + block_indent: /^(?:def|with)[^\/]+$|\/(?:def|with)/ }; function stateStack(indent, type, prev) { // represents a state stack object @@ -81,6 +153,9 @@ CodeMirror.defineMode("clojure", function () { if ( '.' == stream.peek() ) { stream.eat('.'); stream.eatWhile(tests.digit); + } else if ('/' == stream.peek() ) { + stream.eat('/'); + stream.eatWhile(tests.digit); } if ( stream.eat(tests.exponent) ) { @@ -99,7 +174,7 @@ CodeMirror.defineMode("clojure", function () { var first = stream.next(); // Read special literals: backspace, newline, space, return. // Just read all lowercase letters. - if (first.match(/[a-z]/) && stream.match(/[a-z]+/, true)) { + if (first && first.match(/[a-z]/) && stream.match(/[a-z]+/, true)) { return; } // Read unicode character: \u1000 \uA0a1 @@ -124,7 +199,7 @@ CodeMirror.defineMode("clojure", function () { } // skip spaces - if (stream.eatSpace()) { + if (state.mode != "string" && stream.eatSpace()) { return null; } var returnType = null; @@ -172,15 +247,15 @@ CodeMirror.defineMode("clojure", function () { } if (keyWord.length > 0 && (indentKeys.propertyIsEnumerable(keyWord) || - /^(?:def|with)/.test(keyWord))) { // indent-word + tests.block_indent.test(keyWord))) { // indent-word pushStack(state, indentTemp + INDENT_WORD_SKIP, ch); } else { // non-indent word // we continue eating the spaces stream.eatSpace(); if (stream.eol() || stream.peek() == ";") { // nothing significant after - // we restart indentation 1 space after - pushStack(state, indentTemp + 1, ch); + // we restart indentation the user defined spaces after + pushStack(state, indentTemp + NORMAL_INDENT_UNIT, ch); } else { pushStack(state, indentTemp + stream.current().length, ch); // else we match } @@ -205,7 +280,9 @@ CodeMirror.defineMode("clojure", function () { returnType = BUILTIN; } else if (atoms && atoms.propertyIsEnumerable(stream.current())) { returnType = ATOM; - } else returnType = null; + } else { + returnType = VAR; + } } } @@ -217,8 +294,13 @@ CodeMirror.defineMode("clojure", function () { return state.indentStack.indent; }, + closeBrackets: {pairs: "()[]{}\"\""}, lineComment: ";;" }; }); CodeMirror.defineMIME("text/x-clojure", "clojure"); +CodeMirror.defineMIME("text/x-clojurescript", "clojure"); +CodeMirror.defineMIME("application/edn", "clojure"); + +}); diff --git a/Source/WebInspectorUI/UserInterface/External/CodeMirror/closebrackets.js b/Source/WebInspectorUI/UserInterface/External/CodeMirror/closebrackets.js index 88718b772..7c47bcd09 100644 --- a/Source/WebInspectorUI/UserInterface/External/CodeMirror/closebrackets.js +++ b/Source/WebInspectorUI/UserInterface/External/CodeMirror/closebrackets.js @@ -1,82 +1,202 @@ -(function() { - var DEFAULT_BRACKETS = "()[]{}''\"\""; - var DEFAULT_EXPLODE_ON_ENTER = "[]{}"; - var SPACE_CHAR_REGEX = /\s/; +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + var defaults = { + pairs: "()[]{}''\"\"", + triples: "", + explode: "[]{}" + }; + + var Pos = CodeMirror.Pos; CodeMirror.defineOption("autoCloseBrackets", false, function(cm, val, old) { - if (old != CodeMirror.Init && old) - cm.removeKeyMap("autoCloseBrackets"); - if (!val) return; - var pairs = DEFAULT_BRACKETS, explode = DEFAULT_EXPLODE_ON_ENTER; - if (typeof val == "string") pairs = val; - else if (typeof val == "object") { - if (val.pairs != null) pairs = val.pairs; - if (val.explode != null) explode = val.explode; + if (old && old != CodeMirror.Init) { + cm.removeKeyMap(keyMap); + cm.state.closeBrackets = null; + } + if (val) { + cm.state.closeBrackets = val; + cm.addKeyMap(keyMap); } - var map = buildKeymap(pairs); - if (explode) map.Enter = buildExplodeHandler(explode); - cm.addKeyMap(map); }); - function charsAround(cm, pos) { - var str = cm.getRange(CodeMirror.Pos(pos.line, pos.ch - 1), - CodeMirror.Pos(pos.line, pos.ch + 1)); - return str.length == 2 ? str : null; + function getOption(conf, name) { + if (name == "pairs" && typeof conf == "string") return conf; + if (typeof conf == "object" && conf[name] != null) return conf[name]; + return defaults[name]; } - function buildKeymap(pairs) { - var map = { - name : "autoCloseBrackets", - Backspace: function(cm) { - if (cm.somethingSelected()) return CodeMirror.Pass; - var cur = cm.getCursor(), around = charsAround(cm, cur); - if (around && pairs.indexOf(around) % 2 == 0) - cm.replaceRange("", CodeMirror.Pos(cur.line, cur.ch - 1), CodeMirror.Pos(cur.line, cur.ch + 1)); - else - return CodeMirror.Pass; + var bind = defaults.pairs + "`"; + var keyMap = {Backspace: handleBackspace, Enter: handleEnter}; + for (var i = 0; i < bind.length; i++) + keyMap["'" + bind.charAt(i) + "'"] = handler(bind.charAt(i)); + + function handler(ch) { + return function(cm) { return handleChar(cm, ch); }; + } + + function getConfig(cm) { + var deflt = cm.state.closeBrackets; + if (!deflt) return null; + var mode = cm.getModeAt(cm.getCursor()); + return mode.closeBrackets || deflt; + } + + function handleBackspace(cm) { + var conf = getConfig(cm); + if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass; + + var pairs = getOption(conf, "pairs"); + var ranges = cm.listSelections(); + for (var i = 0; i < ranges.length; i++) { + if (!ranges[i].empty()) return CodeMirror.Pass; + var around = charsAround(cm, ranges[i].head); + if (!around || pairs.indexOf(around) % 2 != 0) return CodeMirror.Pass; + } + for (var i = ranges.length - 1; i >= 0; i--) { + var cur = ranges[i].head; + cm.replaceRange("", Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1), "+delete"); + } + } + + function handleEnter(cm) { + var conf = getConfig(cm); + var explode = conf && getOption(conf, "explode"); + if (!explode || cm.getOption("disableInput")) return CodeMirror.Pass; + + var ranges = cm.listSelections(); + for (var i = 0; i < ranges.length; i++) { + if (!ranges[i].empty()) return CodeMirror.Pass; + var around = charsAround(cm, ranges[i].head); + if (!around || explode.indexOf(around) % 2 != 0) return CodeMirror.Pass; + } + cm.operation(function() { + cm.replaceSelection("\n\n", null); + cm.execCommand("goCharLeft"); + ranges = cm.listSelections(); + for (var i = 0; i < ranges.length; i++) { + var line = ranges[i].head.line; + cm.indentLine(line, null, true); + cm.indentLine(line + 1, null, true); } - }; - var closingBrackets = ""; - for (var i = 0; i < pairs.length; i += 2) (function(left, right) { - if (left != right) closingBrackets += right; - function surround(cm) { - var selection = cm.getSelection(); - cm.replaceSelection(left + selection + right); + }); + } + + function contractSelection(sel) { + var inverted = CodeMirror.cmpPos(sel.anchor, sel.head) > 0; + return {anchor: new Pos(sel.anchor.line, sel.anchor.ch + (inverted ? -1 : 1)), + head: new Pos(sel.head.line, sel.head.ch + (inverted ? 1 : -1))}; + } + + function handleChar(cm, ch) { + var conf = getConfig(cm); + if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass; + + var pairs = getOption(conf, "pairs"); + var pos = pairs.indexOf(ch); + if (pos == -1) return CodeMirror.Pass; + var triples = getOption(conf, "triples"); + + var identical = pairs.charAt(pos + 1) == ch; + var ranges = cm.listSelections(); + var opening = pos % 2 == 0; + + var type; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i], cur = range.head, curType; + var next = cm.getRange(cur, Pos(cur.line, cur.ch + 1)); + if (opening && !range.empty()) { + curType = "surround"; + } else if ((identical || !opening) && next == ch) { + if (identical && stringStartsAfter(cm, cur)) + curType = "both"; + else if (triples.indexOf(ch) >= 0 && cm.getRange(cur, Pos(cur.line, cur.ch + 3)) == ch + ch + ch) + curType = "skipThree"; + else + curType = "skip"; + } else if (identical && cur.ch > 1 && triples.indexOf(ch) >= 0 && + cm.getRange(Pos(cur.line, cur.ch - 2), cur) == ch + ch && + (cur.ch <= 2 || cm.getRange(Pos(cur.line, cur.ch - 3), Pos(cur.line, cur.ch - 2)) != ch)) { + curType = "addFour"; + } else if (identical) { + if (!CodeMirror.isWordChar(next) && enteringString(cm, cur, ch)) curType = "both"; + else return CodeMirror.Pass; + } else if (opening && (cm.getLine(cur.line).length == cur.ch || + isClosingBracket(next, pairs) || + /\s/.test(next))) { + curType = "both"; + } else { + return CodeMirror.Pass; } - function maybeOverwrite(cm) { - var cur = cm.getCursor(), ahead = cm.getRange(cur, CodeMirror.Pos(cur.line, cur.ch + 1)); - if (ahead != right || cm.somethingSelected()) return CodeMirror.Pass; - else cm.execCommand("goCharRight"); + if (!type) type = curType; + else if (type != curType) return CodeMirror.Pass; + } + + var left = pos % 2 ? pairs.charAt(pos - 1) : ch; + var right = pos % 2 ? ch : pairs.charAt(pos + 1); + cm.operation(function() { + if (type == "skip") { + cm.execCommand("goCharRight"); + } else if (type == "skipThree") { + for (var i = 0; i < 3; i++) + cm.execCommand("goCharRight"); + } else if (type == "surround") { + var sels = cm.getSelections(); + for (var i = 0; i < sels.length; i++) + sels[i] = left + sels[i] + right; + cm.replaceSelections(sels, "around"); + sels = cm.listSelections().slice(); + for (var i = 0; i < sels.length; i++) + sels[i] = contractSelection(sels[i]); + cm.setSelections(sels); + } else if (type == "both") { + cm.replaceSelection(left + right, null); + cm.triggerElectric(left + right); + cm.execCommand("goCharLeft"); + } else if (type == "addFour") { + cm.replaceSelection(left + left + left + left, "before"); + cm.execCommand("goCharRight"); } - map["'" + left + "'"] = function(cm) { - if (left == "'" && cm.getTokenAt(cm.getCursor()).type == "comment") - return CodeMirror.Pass; - if (cm.somethingSelected()) return surround(cm); - if (left == right && maybeOverwrite(cm) != CodeMirror.Pass) return; - var cur = cm.getCursor(), ahead = CodeMirror.Pos(cur.line, cur.ch + 1); - var line = cm.getLine(cur.line), nextChar = line.charAt(cur.ch), curChar = cur.ch > 0 ? line.charAt(cur.ch - 1) : ""; - if (left == right && CodeMirror.isWordChar(curChar)) - return CodeMirror.Pass; - if (line.length == cur.ch || closingBrackets.indexOf(nextChar) >= 0 || SPACE_CHAR_REGEX.test(nextChar)) - cm.replaceSelection(left + right, {head: ahead, anchor: ahead}); - else - return CodeMirror.Pass; - }; - if (left != right) map["'" + right + "'"] = maybeOverwrite; - })(pairs.charAt(i), pairs.charAt(i + 1)); - return map; + }); } - function buildExplodeHandler(pairs) { - return function(cm) { - var cur = cm.getCursor(), around = charsAround(cm, cur); - if (!around || pairs.indexOf(around) % 2 != 0) return CodeMirror.Pass; - cm.operation(function() { - var newPos = CodeMirror.Pos(cur.line + 1, 0); - cm.replaceSelection("\n\n", {anchor: newPos, head: newPos}, "+input"); - cm.indentLine(cur.line + 1, null, true); - cm.indentLine(cur.line + 2, null, true); - }); - }; + function isClosingBracket(ch, pairs) { + var pos = pairs.lastIndexOf(ch); + return pos > -1 && pos % 2 == 1; + } + + function charsAround(cm, pos) { + var str = cm.getRange(Pos(pos.line, pos.ch - 1), + Pos(pos.line, pos.ch + 1)); + return str.length == 2 ? str : null; + } + + // Project the token type that will exists after the given char is + // typed, and use it to determine whether it would cause the start + // of a string token. + function enteringString(cm, pos, ch) { + var line = cm.getLine(pos.line); + var token = cm.getTokenAt(pos); + if (/\bstring2?\b/.test(token.type)) return false; + var stream = new CodeMirror.StringStream(line.slice(0, pos.ch) + ch + line.slice(pos.ch), 4); + stream.pos = stream.start = token.start; + for (;;) { + var type1 = cm.getMode().token(stream, token.state); + if (stream.pos >= pos.ch + 1) return /\bstring2?\b/.test(type1); + stream.start = stream.pos; + } + } + + function stringStartsAfter(cm, pos) { + var token = cm.getTokenAt(Pos(pos.line, pos.ch + 1)) + return /\bstring/.test(token.type) && token.start == pos.ch } -})(); +}); diff --git a/Source/WebInspectorUI/UserInterface/External/CodeMirror/codemirror.css b/Source/WebInspectorUI/UserInterface/External/CodeMirror/codemirror.css index 23eaf74d4..2a6a26228 100644 --- a/Source/WebInspectorUI/UserInterface/External/CodeMirror/codemirror.css +++ b/Source/WebInspectorUI/UserInterface/External/CodeMirror/codemirror.css @@ -4,10 +4,7 @@ /* Set height, width, borders, and global font properties here */ font-family: monospace; height: 300px; -} -.CodeMirror-scroll { - /* Set scrolling behaviour here */ - overflow: auto; + color: black; } /* PADDING */ @@ -36,40 +33,93 @@ min-width: 20px; text-align: right; color: #999; + white-space: nowrap; } +.CodeMirror-guttermarker { color: black; } +.CodeMirror-guttermarker-subtle { color: #999; } + /* CURSOR */ -.CodeMirror div.CodeMirror-cursor { +.CodeMirror-cursor { border-left: 1px solid black; - z-index: 3; + border-right: none; + width: 0; } /* Shown when moving in bi-directional text */ .CodeMirror div.CodeMirror-secondarycursor { border-left: 1px solid silver; } -.CodeMirror.cm-keymap-fat-cursor div.CodeMirror-cursor { +.cm-fat-cursor .CodeMirror-cursor { width: auto; - border: 0; + border: 0 !important; background: #7e7; +} +.cm-fat-cursor div.CodeMirror-cursors { z-index: 1; } + +.cm-animate-fat-cursor { + width: auto; + border: 0; + -webkit-animation: blink 1.06s steps(1) infinite; + -moz-animation: blink 1.06s steps(1) infinite; + animation: blink 1.06s steps(1) infinite; + background-color: #7e7; +} +@-moz-keyframes blink { + 0% {} + 50% { background-color: transparent; } + 100% {} +} +@-webkit-keyframes blink { + 0% {} + 50% { background-color: transparent; } + 100% {} +} +@keyframes blink { + 0% {} + 50% { background-color: transparent; } + 100% {} +} + /* Can style cursor different in overwrite (non-insert) mode */ -.CodeMirror div.CodeMirror-cursor.CodeMirror-overwrite {} +.CodeMirror-overwrite .CodeMirror-cursor {} -.cm-tab { display: inline-block; } +.cm-tab { display: inline-block; text-decoration: inherit; } + +.CodeMirror-rulers { + position: absolute; + left: 0; right: 0; top: -50px; bottom: -20px; + overflow: hidden; +} +.CodeMirror-ruler { + border-left: 1px solid #ccc; + top: 0; bottom: 0; + position: absolute; +} /* DEFAULT THEME */ +.cm-s-default .cm-header {color: blue;} +.cm-s-default .cm-quote {color: #090;} +.cm-negative {color: #d44;} +.cm-positive {color: #292;} +.cm-header, .cm-strong {font-weight: bold;} +.cm-em {font-style: italic;} +.cm-link {text-decoration: underline;} +.cm-strikethrough {text-decoration: line-through;} + .cm-s-default .cm-keyword {color: #708;} .cm-s-default .cm-atom {color: #219;} .cm-s-default .cm-number {color: #164;} .cm-s-default .cm-def {color: #00f;} -.cm-s-default .cm-variable {color: black;} +.cm-s-default .cm-variable, +.cm-s-default .cm-punctuation, +.cm-s-default .cm-property, +.cm-s-default .cm-operator {} .cm-s-default .cm-variable-2 {color: #05a;} .cm-s-default .cm-variable-3 {color: #085;} -.cm-s-default .cm-property {color: black;} -.cm-s-default .cm-operator {color: black;} .cm-s-default .cm-comment {color: #a50;} .cm-s-default .cm-string {color: #a11;} .cm-s-default .cm-string-2 {color: #f50;} @@ -79,22 +129,19 @@ .cm-s-default .cm-bracket {color: #997;} .cm-s-default .cm-tag {color: #170;} .cm-s-default .cm-attribute {color: #00c;} -.cm-s-default .cm-header {color: blue;} -.cm-s-default .cm-quote {color: #090;} .cm-s-default .cm-hr {color: #999;} .cm-s-default .cm-link {color: #00c;} -.cm-negative {color: #d44;} -.cm-positive {color: #292;} -.cm-header, .cm-strong {font-weight: bold;} -.cm-em {font-style: italic;} -.cm-link {text-decoration: underline;} - .cm-s-default .cm-error {color: #f00;} .cm-invalidchar {color: #f00;} +.CodeMirror-composing { border-bottom: 2px solid; } + +/* Default styles for common addons */ + div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;} div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;} +.CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); } .CodeMirror-activeline-background {background: #e8f2ff;} /* STOP */ @@ -103,30 +150,28 @@ div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;} the editor. You probably shouldn't touch them. */ .CodeMirror { - line-height: 1; position: relative; overflow: hidden; background: white; - color: black; } .CodeMirror-scroll { + overflow: scroll !important; /* Things will break if this is overridden */ /* 30px is the magic margin used to hide the element's real scrollbars */ /* See overflow: hidden in .CodeMirror */ margin-bottom: -30px; margin-right: -30px; - padding-bottom: 30px; padding-right: 30px; + padding-bottom: 30px; height: 100%; outline: none; /* Prevent dragging from highlighting the element */ position: relative; - -moz-box-sizing: content-box; - box-sizing: content-box; } .CodeMirror-sizer { position: relative; + border-right: 30px solid transparent; } /* The fake, visible scrollbars. Used to force redraw during scrolling - before actuall scrolling happens, thus preventing shaking and + before actual scrolling happens, thus preventing shaking and flickering artifacts. */ .CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler { position: absolute; @@ -152,29 +197,41 @@ div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;} .CodeMirror-gutters { position: absolute; left: 0; top: 0; - padding-bottom: 30px; + min-height: 100%; z-index: 3; } .CodeMirror-gutter { white-space: normal; height: 100%; - -moz-box-sizing: content-box; - box-sizing: content-box; - padding-bottom: 30px; - margin-bottom: -32px; display: inline-block; - /* Hack to make IE7 behave */ - *zoom:1; - *display:inline; + vertical-align: top; + margin-bottom: -30px; +} +.CodeMirror-gutter-wrapper { + position: absolute; + z-index: 4; + background: none !important; + border: none !important; +} +.CodeMirror-gutter-background { + position: absolute; + top: 0; bottom: 0; + z-index: 4; } .CodeMirror-gutter-elt { position: absolute; cursor: default; z-index: 4; } +.CodeMirror-gutter-wrapper { + -webkit-user-select: none; + -moz-user-select: none; + user-select: none; +} .CodeMirror-lines { cursor: text; + min-height: 1px; /* prevents collapsing before first draw */ } .CodeMirror pre { /* Reset some styles that the rest of the page might have set */ @@ -191,22 +248,16 @@ div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;} z-index: 2; position: relative; overflow: visible; + -webkit-tap-highlight-color: transparent; + -webkit-font-variant-ligatures: contextual; + font-variant-ligatures: contextual; } .CodeMirror-wrap pre { word-wrap: break-word; white-space: pre-wrap; word-break: normal; } -.CodeMirror-code pre { - border-right: 30px solid transparent; - width: -webkit-fit-content; - width: -moz-fit-content; - width: fit-content; -} -.CodeMirror-wrap .CodeMirror-code pre { - border-right: none; - width: auto; -} + .CodeMirror-linebackground { position: absolute; left: 0; right: 0; top: 0; bottom: 0; @@ -221,8 +272,18 @@ div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;} .CodeMirror-widget {} -.CodeMirror-wrap .CodeMirror-scroll { - overflow-x: hidden; +.CodeMirror-code { + outline: none; +} + +/* Force content-box sizing for the elements where we expect it */ +.CodeMirror-scroll, +.CodeMirror-sizer, +.CodeMirror-gutter, +.CodeMirror-gutters, +.CodeMirror-linenumber { + -moz-box-sizing: content-box; + box-sizing: content-box; } .CodeMirror-measure { @@ -232,32 +293,49 @@ div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;} overflow: hidden; visibility: hidden; } -.CodeMirror-measure pre { position: static; } -.CodeMirror div.CodeMirror-cursor { +.CodeMirror-cursor { position: absolute; + pointer-events: none; +} +.CodeMirror-measure pre { position: static; } + +div.CodeMirror-cursors { visibility: hidden; - border-right: none; - width: 0; + position: relative; + z-index: 3; } -.CodeMirror-focused div.CodeMirror-cursor { +div.CodeMirror-dragcursors { + visibility: visible; +} + +.CodeMirror-focused div.CodeMirror-cursors { visibility: visible; } .CodeMirror-selected { background: #d9d9d9; } .CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; } +.CodeMirror-crosshair { cursor: crosshair; } +.CodeMirror-line::selection, .CodeMirror-line > span::selection, .CodeMirror-line > span > span::selection { background: #d7d4f0; } +.CodeMirror-line::-moz-selection, .CodeMirror-line > span::-moz-selection, .CodeMirror-line > span > span::-moz-selection { background: #d7d4f0; } .cm-searching { background: #ffa; background: rgba(255, 255, 0, .4); } -/* IE7 hack to prevent it from returning funny offsetTops on the spans */ -.CodeMirror span { *vertical-align: text-bottom; } +/* Used to force a border model for a node */ +.cm-force-border { padding-right: .1px; } @media print { /* Hide the cursor when printing */ - .CodeMirror div.CodeMirror-cursor { + .CodeMirror div.CodeMirror-cursors { visibility: hidden; } } + +/* See issue #2901 */ +.cm-tab-wrap-hack:after { content: ''; } + +/* Help users use markselection to safely style text background */ +span.CodeMirror-selectedtext { background: none; } diff --git a/Source/WebInspectorUI/UserInterface/External/CodeMirror/codemirror.js b/Source/WebInspectorUI/UserInterface/External/CodeMirror/codemirror.js index 46373bfb7..84c881146 100644 --- a/Source/WebInspectorUI/UserInterface/External/CodeMirror/codemirror.js +++ b/Source/WebInspectorUI/UserInterface/External/CodeMirror/codemirror.js @@ -1,5944 +1,9111 @@ -// CodeMirror is the only global var we claim -window.CodeMirror = (function() { - "use strict"; - - // BROWSER SNIFFING - - // Crude, but necessary to handle a number of hard-to-feature-detect - // bugs and behavior differences. - var gecko = /gecko\/\d/i.test(navigator.userAgent); - // IE11 currently doesn't count as 'ie', since it has almost none of - // the same bugs as earlier versions. Use ie_gt10 to handle - // incompatibilities in that version. - var ie = /MSIE \d/.test(navigator.userAgent); - var ie_lt8 = ie && (document.documentMode == null || document.documentMode < 8); - var ie_lt9 = ie && (document.documentMode == null || document.documentMode < 9); - var ie_gt10 = /Trident\/([7-9]|\d{2,})\./.test(navigator.userAgent); - var webkit = /WebKit\//.test(navigator.userAgent); - var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent); - var chrome = /Chrome\//.test(navigator.userAgent); - var opera = /Opera\//.test(navigator.userAgent); - var safari = /Apple Computer/.test(navigator.vendor); - var khtml = /KHTML\//.test(navigator.userAgent); - var mac_geLion = /Mac OS X 1\d\D([7-9]|\d\d)\D/.test(navigator.userAgent); - var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent); - var phantom = /PhantomJS/.test(navigator.userAgent); - - var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent); - // This is woefully incomplete. Suggestions for alternative methods welcome. - var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent); - var mac = ios || /Mac/.test(navigator.platform); - var windows = /win/i.test(navigator.platform); - - var opera_version = opera && navigator.userAgent.match(/Version\/(\d*\.\d*)/); - if (opera_version) opera_version = Number(opera_version[1]); - if (opera_version && opera_version >= 15) { opera = false; webkit = true; } - // Some browsers use the wrong event properties to signal cmd/ctrl on OS X - var flipCtrlCmd = mac && (qtwebkit || opera && (opera_version == null || opera_version < 12.11)); - var captureMiddleClick = gecko || (ie && !ie_lt9); - - // Optimize some code when these features are not used - var sawReadOnlySpans = false, sawCollapsedSpans = false; - - // CONSTRUCTOR - - function CodeMirror(place, options) { - if (!(this instanceof CodeMirror)) return new CodeMirror(place, options); - - this.options = options = options || {}; - // Determine effective options based on given values and defaults. - for (var opt in defaults) if (!options.hasOwnProperty(opt) && defaults.hasOwnProperty(opt)) - options[opt] = defaults[opt]; - setGuttersForLineNumbers(options); - - var docStart = typeof options.value == "string" ? 0 : options.value.first; - var display = this.display = makeDisplay(place, docStart); - display.wrapper.CodeMirror = this; - updateGutters(this); - if (options.autofocus && !mobile) focusInput(this); - - this.state = {keyMaps: [], - overlays: [], - modeGen: 0, - overwrite: false, focused: false, - suppressEdits: false, pasteIncoming: false, - draggingText: false, - highlight: new Delayed()}; - - themeChanged(this); - if (options.lineWrapping) - this.display.wrapper.className += " CodeMirror-wrap"; - - var doc = options.value; - if (typeof doc == "string") doc = new Doc(options.value, options.mode); - operation(this, attachDoc)(this, doc); - - // Override magic textarea content restore that IE sometimes does - // on our hidden textarea on reload - if (ie) setTimeout(bind(resetInput, this, true), 20); - - registerEventHandlers(this); - // IE throws unspecified error in certain cases, when - // trying to access activeElement before onload - var hasFocus; try { hasFocus = (document.activeElement == display.input); } catch(e) { } - if (hasFocus || (options.autofocus && !mobile)) setTimeout(bind(onFocus, this), 20); - else onBlur(this); - - operation(this, function() { - for (var opt in optionHandlers) - if (optionHandlers.propertyIsEnumerable(opt)) - optionHandlers[opt](this, options[opt], Init); - for (var i = 0; i < initHooks.length; ++i) initHooks[i](this); - })(); - } - - // DISPLAY CONSTRUCTOR - - function makeDisplay(place, docStart) { - var d = {}; - - var input = d.input = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none; font-size: 4px;"); - if (webkit) input.style.width = "1000px"; - else input.setAttribute("wrap", "off"); - // if border: 0; -- iOS fails to open keyboard (issue #1287) - if (ios) input.style.border = "1px solid black"; - input.setAttribute("autocorrect", "off"); input.setAttribute("autocapitalize", "off"); input.setAttribute("spellcheck", "false"); - - // Wraps and hides input textarea - d.inputDiv = elt("div", [input], null, "overflow: hidden; position: relative; width: 3px; height: 0px;"); - // The actual fake scrollbars. - d.scrollbarH = elt("div", [elt("div", null, null, "height: 1px")], "CodeMirror-hscrollbar"); - d.scrollbarV = elt("div", [elt("div", null, null, "width: 1px")], "CodeMirror-vscrollbar"); - d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler"); - d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler"); - // DIVs containing the selection and the actual code - d.lineDiv = elt("div", null, "CodeMirror-code"); - d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1"); - // Blinky cursor, and element used to ensure cursor fits at the end of a line - d.cursor = elt("div", "\u00a0", "CodeMirror-cursor"); - // Secondary cursor, shown when on a 'jump' in bi-directional text - d.otherCursor = elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"); - // Used to measure text size - d.measure = elt("div", null, "CodeMirror-measure"); - // Wraps everything that needs to exist inside the vertically-padded coordinate system - d.lineSpace = elt("div", [d.measure, d.selectionDiv, d.lineDiv, d.cursor, d.otherCursor], - null, "position: relative; outline: none"); - // Moved around its parent to cover visible view - d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative"); - // Set to the height of the text, causes scrolling - d.sizer = elt("div", [d.mover], "CodeMirror-sizer"); - // D is needed because behavior of elts with overflow: auto and padding is inconsistent across browsers - d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerCutOff + "px; width: 1px;"); - // Will contain the gutters, if any - d.gutters = elt("div", null, "CodeMirror-gutters"); - d.lineGutter = null; - // Provides scrolling - d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll"); - d.scroller.setAttribute("tabIndex", "-1"); - // The element in which the editor lives. - d.wrapper = elt("div", [d.inputDiv, d.scrollbarH, d.scrollbarV, - d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror"); - // Work around IE7 z-index bug - if (ie_lt8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; } - if (place.appendChild) place.appendChild(d.wrapper); else place(d.wrapper); - - // Needed to hide big blue blinking cursor on Mobile Safari - if (ios) input.style.width = "0px"; - if (!webkit) d.scroller.draggable = true; - // Needed to handle Tab key in KHTML - if (khtml) { d.inputDiv.style.height = "1px"; d.inputDiv.style.position = "absolute"; } - // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). - else if (ie_lt8) d.scrollbarH.style.minWidth = d.scrollbarV.style.minWidth = "18px"; - - // Current visible range (may be bigger than the view window). - d.viewOffset = d.lastSizeC = 0; - d.showingFrom = d.showingTo = docStart; - - // Used to only resize the line number gutter when necessary (when - // the amount of lines crosses a boundary that makes its width change) - d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null; - // See readInput and resetInput - d.prevInput = ""; - // Set to true when a non-horizontal-scrolling widget is added. As - // an optimization, widget aligning is skipped when d is false. - d.alignWidgets = false; - // Flag that indicates whether we currently expect input to appear - // (after some event like 'keypress' or 'input') and are polling - // intensively. - d.pollingFast = false; - // Self-resetting timeout for the poller - d.poll = new Delayed(); - - d.cachedCharWidth = d.cachedTextHeight = null; - d.measureLineCache = []; - d.measureLineCachePos = 0; - - // Tracks when resetInput has punted to just putting a short - // string instead of the (large) selection. - d.inaccurateSelection = false; - - // Tracks the maximum line length so that the horizontal scrollbar - // can be kept static when scrolling. - d.maxLine = null; - d.maxLineLength = 0; - d.maxLineChanged = false; - - // Used for measuring wheel scrolling granularity - d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null; - - return d; - } - - // STATE UPDATES - - // Used to get the editor into a consistent state again when options change. - - function loadMode(cm) { - cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption); - cm.doc.iter(function(line) { - if (line.stateAfter) line.stateAfter = null; - if (line.styles) line.styles = null; - }); - cm.doc.frontier = cm.doc.first; - startWorker(cm, 100); - cm.state.modeGen++; - if (cm.curOp) regChange(cm); - } - - function wrappingChanged(cm) { - if (cm.options.lineWrapping) { - cm.display.wrapper.className += " CodeMirror-wrap"; - cm.display.sizer.style.minWidth = ""; - } else { - cm.display.wrapper.className = cm.display.wrapper.className.replace(" CodeMirror-wrap", ""); - computeMaxLength(cm); - } - estimateLineHeights(cm); - regChange(cm); - clearCaches(cm); - setTimeout(function(){updateScrollbars(cm);}, 100); - } - - function estimateHeight(cm) { - var th = textHeight(cm.display), wrapping = cm.options.lineWrapping; - var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3); - return function(line) { - if (lineIsHidden(cm.doc, line)) - return 0; - else if (wrapping) - return (Math.ceil(line.text.length / perLine) || 1) * th; - else - return th; - }; - } - - function estimateLineHeights(cm) { - var doc = cm.doc, est = estimateHeight(cm); - doc.iter(function(line) { - var estHeight = est(line); - if (estHeight != line.height) updateLineHeight(line, estHeight); - }); - } - - function keyMapChanged(cm) { - var map = keyMap[cm.options.keyMap], style = map.style; - cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-keymap-\S+/g, "") + - (style ? " cm-keymap-" + style : ""); - cm.state.disableInput = map.disableInput; - } - - function themeChanged(cm) { - cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + - cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-"); - clearCaches(cm); - } - - function guttersChanged(cm) { - updateGutters(cm); - regChange(cm); - setTimeout(function(){alignHorizontally(cm);}, 20); - } - - function updateGutters(cm) { - var gutters = cm.display.gutters, specs = cm.options.gutters; - removeChildren(gutters); - for (var i = 0; i < specs.length; ++i) { - var gutterClass = specs[i]; - var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass)); - if (gutterClass == "CodeMirror-linenumbers") { - cm.display.lineGutter = gElt; - gElt.style.width = (cm.display.lineNumWidth || 1) + "px"; +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +// This is CodeMirror (http://codemirror.net), a code editor +// implemented in JavaScript on top of the browser's DOM. +// +// You can find some technical background for some of the code below +// at http://marijnhaverbeke.nl/blog/#cm-internals . + +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global.CodeMirror = factory()); +}(this, (function () { 'use strict'; + +// Kludges for bugs and behavior differences that can't be feature +// detected are enabled based on userAgent etc sniffing. +var userAgent = navigator.userAgent +var platform = navigator.platform + +var gecko = /gecko\/\d/i.test(userAgent) +var ie_upto10 = /MSIE \d/.test(userAgent) +var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent) +var ie = ie_upto10 || ie_11up +var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : ie_11up[1]) +var webkit = /WebKit\//.test(userAgent) +var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent) +var chrome = /Chrome\//.test(userAgent) +var presto = /Opera\//.test(userAgent) +var safari = /Apple Computer/.test(navigator.vendor) +var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent) +var phantom = /PhantomJS/.test(userAgent) + +var ios = /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent) +// This is woefully incomplete. Suggestions for alternative methods welcome. +var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent) +var mac = ios || /Mac/.test(platform) +var chromeOS = /\bCrOS\b/.test(userAgent) +var windows = /win/i.test(platform) + +var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/) +if (presto_version) { presto_version = Number(presto_version[1]) } +if (presto_version && presto_version >= 15) { presto = false; webkit = true } +// Some browsers use the wrong event properties to signal cmd/ctrl on OS X +var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11)) +var captureRightClick = gecko || (ie && ie_version >= 9) + +function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") } + +var rmClass = function(node, cls) { + var current = node.className + var match = classTest(cls).exec(current) + if (match) { + var after = current.slice(match.index + match[0].length) + node.className = current.slice(0, match.index) + (after ? match[1] + after : "") + } +} + +function removeChildren(e) { + for (var count = e.childNodes.length; count > 0; --count) + { e.removeChild(e.firstChild) } + return e +} + +function removeChildrenAndAdd(parent, e) { + return removeChildren(parent).appendChild(e) +} + +function elt(tag, content, className, style) { + var e = document.createElement(tag) + if (className) { e.className = className } + if (style) { e.style.cssText = style } + if (typeof content == "string") { e.appendChild(document.createTextNode(content)) } + else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]) } } + return e +} + +var range +if (document.createRange) { range = function(node, start, end, endNode) { + var r = document.createRange() + r.setEnd(endNode || node, end) + r.setStart(node, start) + return r +} } +else { range = function(node, start, end) { + var r = document.body.createTextRange() + try { r.moveToElementText(node.parentNode) } + catch(e) { return r } + r.collapse(true) + r.moveEnd("character", end) + r.moveStart("character", start) + return r +} } + +function contains(parent, child) { + if (child.nodeType == 3) // Android browser always returns false when child is a textnode + { child = child.parentNode } + if (parent.contains) + { return parent.contains(child) } + do { + if (child.nodeType == 11) { child = child.host } + if (child == parent) { return true } + } while (child = child.parentNode) +} + +function activeElt() { + // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement. + // IE < 10 will throw when accessed while the page is loading or in an iframe. + // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable. + var activeElement + try { + activeElement = document.activeElement + } catch(e) { + activeElement = document.body || null + } + while (activeElement && activeElement.root && activeElement.root.activeElement) + { activeElement = activeElement.root.activeElement } + return activeElement +} + +function addClass(node, cls) { + var current = node.className + if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls } +} +function joinClasses(a, b) { + var as = a.split(" ") + for (var i = 0; i < as.length; i++) + { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i] } } + return b +} + +var selectInput = function(node) { node.select() } +if (ios) // Mobile Safari apparently has a bug where select() is broken. + { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length } } +else if (ie) // Suppress mysterious IE10 errors + { selectInput = function(node) { try { node.select() } catch(_e) {} } } + +function bind(f) { + var args = Array.prototype.slice.call(arguments, 1) + return function(){return f.apply(null, args)} +} + +function copyObj(obj, target, overwrite) { + if (!target) { target = {} } + for (var prop in obj) + { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop))) + { target[prop] = obj[prop] } } + return target +} + +// Counts the column offset in a string, taking tabs into account. +// Used mostly to find indentation. +function countColumn(string, end, tabSize, startIndex, startValue) { + if (end == null) { + end = string.search(/[^\s\u00a0]/) + if (end == -1) { end = string.length } + } + for (var i = startIndex || 0, n = startValue || 0;;) { + var nextTab = string.indexOf("\t", i) + if (nextTab < 0 || nextTab >= end) + { return n + (end - i) } + n += nextTab - i + n += tabSize - (n % tabSize) + i = nextTab + 1 + } +} + +function Delayed() {this.id = null} +Delayed.prototype.set = function(ms, f) { + clearTimeout(this.id) + this.id = setTimeout(f, ms) +} + +function indexOf(array, elt) { + for (var i = 0; i < array.length; ++i) + { if (array[i] == elt) { return i } } + return -1 +} + +// Number of pixels added to scroller and sizer to hide scrollbar +var scrollerGap = 30 + +// Returned or thrown by various protocols to signal 'I'm not +// handling this'. +var Pass = {toString: function(){return "CodeMirror.Pass"}} + +// Reused option objects for setSelection & friends +var sel_dontScroll = {scroll: false}; +var sel_mouse = {origin: "*mouse"}; +var sel_move = {origin: "+move"}; +// The inverse of countColumn -- find the offset that corresponds to +// a particular column. +function findColumn(string, goal, tabSize) { + for (var pos = 0, col = 0;;) { + var nextTab = string.indexOf("\t", pos) + if (nextTab == -1) { nextTab = string.length } + var skipped = nextTab - pos + if (nextTab == string.length || col + skipped >= goal) + { return pos + Math.min(skipped, goal - col) } + col += nextTab - pos + col += tabSize - (col % tabSize) + pos = nextTab + 1 + if (col >= goal) { return pos } + } +} + +var spaceStrs = [""] +function spaceStr(n) { + while (spaceStrs.length <= n) + { spaceStrs.push(lst(spaceStrs) + " ") } + return spaceStrs[n] +} + +function lst(arr) { return arr[arr.length-1] } + +function map(array, f) { + var out = [] + for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i) } + return out +} + +function insertSorted(array, value, score) { + var pos = 0, priority = score(value) + while (pos < array.length && score(array[pos]) <= priority) { pos++ } + array.splice(pos, 0, value) +} + +function nothing() {} + +function createObj(base, props) { + var inst + if (Object.create) { + inst = Object.create(base) + } else { + nothing.prototype = base + inst = new nothing() + } + if (props) { copyObj(props, inst) } + return inst +} + +var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; +function isWordCharBasic(ch) { + return /\w/.test(ch) || ch > "\x80" && + (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)) +} +function isWordChar(ch, helper) { + if (!helper) { return isWordCharBasic(ch) } + if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true } + return helper.test(ch) +} + +function isEmpty(obj) { + for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } } + return true +} + +// Extending unicode characters. A series of a non-extending char + +// any number of extending chars is treated as a single unit as far +// as editing and measuring is concerned. This is not fully correct, +// since some scripts/fonts/browsers also treat other configurations +// of code points as a group. +var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/; +function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) } + +// The display handles the DOM integration, both for input reading +// and content drawing. It holds references to DOM nodes and +// display-related state. + +function Display(place, doc, input) { + var d = this + this.input = input + + // Covers bottom-right square when both scrollbars are present. + d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler") + d.scrollbarFiller.setAttribute("cm-not-content", "true") + // Covers bottom of gutter when coverGutterNextToScrollbar is on + // and h scrollbar is present. + d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler") + d.gutterFiller.setAttribute("cm-not-content", "true") + // Will contain the actual code, positioned to cover the viewport. + d.lineDiv = elt("div", null, "CodeMirror-code") + // Elements are added to these to represent selection and cursors. + d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1") + d.cursorDiv = elt("div", null, "CodeMirror-cursors") + // A visibility: hidden element used to find the size of things. + d.measure = elt("div", null, "CodeMirror-measure") + // When lines outside of the viewport are measured, they are drawn in this. + d.lineMeasure = elt("div", null, "CodeMirror-measure") + // Wraps everything that needs to exist inside the vertically-padded coordinate system + d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv], + null, "position: relative; outline: none") + // Moved around its parent to cover visible view. + d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative") + // Set to the height of the document, allowing scrolling. + d.sizer = elt("div", [d.mover], "CodeMirror-sizer") + d.sizerWidth = null + // Behavior of elts with overflow: auto and padding is + // inconsistent across browsers. This is used to ensure the + // scrollable area is big enough. + d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;") + // Will contain the gutters, if any. + d.gutters = elt("div", null, "CodeMirror-gutters") + d.lineGutter = null + // Actual scrollable element. + d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll") + d.scroller.setAttribute("tabIndex", "-1") + // The element in which the editor lives. + d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror") + + // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported) + if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0 } + if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true } + + if (place) { + if (place.appendChild) { place.appendChild(d.wrapper) } + else { place(d.wrapper) } + } + + // Current rendered range (may be bigger than the view window). + d.viewFrom = d.viewTo = doc.first + d.reportedViewFrom = d.reportedViewTo = doc.first + // Information about the rendered lines. + d.view = [] + d.renderedView = null + // Holds info about a single rendered line when it was rendered + // for measurement, while not in view. + d.externalMeasured = null + // Empty space (in pixels) above the view + d.viewOffset = 0 + d.lastWrapHeight = d.lastWrapWidth = 0 + d.updateLineNumbers = null + + d.nativeBarWidth = d.barHeight = d.barWidth = 0 + d.scrollbarsClipped = false + + // Used to only resize the line number gutter when necessary (when + // the amount of lines crosses a boundary that makes its width change) + d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null + // Set to true when a non-horizontal-scrolling line widget is + // added. As an optimization, line widget aligning is skipped when + // this is false. + d.alignWidgets = false + + d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null + + // Tracks the maximum line length so that the horizontal scrollbar + // can be kept static when scrolling. + d.maxLine = null + d.maxLineLength = 0 + d.maxLineChanged = false + + // Used for measuring wheel scrolling granularity + d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null + + // True when shift is held down. + d.shift = false + + // Used to track whether anything happened since the context menu + // was opened. + d.selForContextMenu = null + + d.activeTouch = null + + input.init(d) +} + +// Find the line object corresponding to the given line number. +function getLine(doc, n) { + n -= doc.first + if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") } + var chunk = doc + while (!chunk.lines) { + for (var i = 0;; ++i) { + var child = chunk.children[i], sz = child.chunkSize() + if (n < sz) { chunk = child; break } + n -= sz + } + } + return chunk.lines[n] +} + +// Get the part of a document between two positions, as an array of +// strings. +function getBetween(doc, start, end) { + var out = [], n = start.line + doc.iter(start.line, end.line + 1, function (line) { + var text = line.text + if (n == end.line) { text = text.slice(0, end.ch) } + if (n == start.line) { text = text.slice(start.ch) } + out.push(text) + ++n + }) + return out +} +// Get the lines between from and to, as array of strings. +function getLines(doc, from, to) { + var out = [] + doc.iter(from, to, function (line) { out.push(line.text) }) // iter aborts when callback returns truthy value + return out +} + +// Update the height of a line, propagating the height change +// upwards to parent nodes. +function updateLineHeight(line, height) { + var diff = height - line.height + if (diff) { for (var n = line; n; n = n.parent) { n.height += diff } } +} + +// Given a line object, find its line number by walking up through +// its parent links. +function lineNo(line) { + if (line.parent == null) { return null } + var cur = line.parent, no = indexOf(cur.lines, line) + for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { + for (var i = 0;; ++i) { + if (chunk.children[i] == cur) { break } + no += chunk.children[i].chunkSize() + } + } + return no + cur.first +} + +// Find the line at the given vertical position, using the height +// information in the document tree. +function lineAtHeight(chunk, h) { + var n = chunk.first + outer: do { + for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) { + var child = chunk.children[i$1], ch = child.height + if (h < ch) { chunk = child; continue outer } + h -= ch + n += child.chunkSize() + } + return n + } while (!chunk.lines) + var i = 0 + for (; i < chunk.lines.length; ++i) { + var line = chunk.lines[i], lh = line.height + if (h < lh) { break } + h -= lh + } + return n + i +} + +function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size} + +function lineNumberFor(options, i) { + return String(options.lineNumberFormatter(i + options.firstLineNumber)) +} + +// A Pos instance represents a position within the text. +function Pos (line, ch) { + if (!(this instanceof Pos)) { return new Pos(line, ch) } + this.line = line; this.ch = ch +} + +// Compare two positions, return 0 if they are the same, a negative +// number when a is less, and a positive number otherwise. +function cmp(a, b) { return a.line - b.line || a.ch - b.ch } + +function copyPos(x) {return Pos(x.line, x.ch)} +function maxPos(a, b) { return cmp(a, b) < 0 ? b : a } +function minPos(a, b) { return cmp(a, b) < 0 ? a : b } + +// Most of the external API clips given positions to make sure they +// actually exist within the document. +function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))} +function clipPos(doc, pos) { + if (pos.line < doc.first) { return Pos(doc.first, 0) } + var last = doc.first + doc.size - 1 + if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) } + return clipToLen(pos, getLine(doc, pos.line).text.length) +} +function clipToLen(pos, linelen) { + var ch = pos.ch + if (ch == null || ch > linelen) { return Pos(pos.line, linelen) } + else if (ch < 0) { return Pos(pos.line, 0) } + else { return pos } +} +function clipPosArray(doc, array) { + var out = [] + for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]) } + return out +} + +// Optimize some code when these features are not used. +var sawReadOnlySpans = false; +var sawCollapsedSpans = false; +function seeReadOnlySpans() { + sawReadOnlySpans = true +} + +function seeCollapsedSpans() { + sawCollapsedSpans = true +} + +// TEXTMARKER SPANS + +function MarkedSpan(marker, from, to) { + this.marker = marker + this.from = from; this.to = to +} + +// Search an array of spans for a span matching the given marker. +function getMarkedSpanFor(spans, marker) { + if (spans) { for (var i = 0; i < spans.length; ++i) { + var span = spans[i] + if (span.marker == marker) { return span } + } } +} +// Remove a span from an array, returning undefined if no spans are +// left (we don't store arrays for lines without spans). +function removeMarkedSpan(spans, span) { + var r + for (var i = 0; i < spans.length; ++i) + { if (spans[i] != span) { (r || (r = [])).push(spans[i]) } } + return r +} +// Add a span to a line. +function addMarkedSpan(line, span) { + line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span] + span.marker.attachLine(line) +} + +// Used for the algorithm that adjusts markers for a change in the +// document. These functions cut an array of spans at a given +// character position, returning an array of remaining chunks (or +// undefined if nothing remains). +function markedSpansBefore(old, startCh, isInsert) { + var nw + if (old) { for (var i = 0; i < old.length; ++i) { + var span = old[i], marker = span.marker + var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh) + if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) { + var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh) + ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to)) + } + } } + return nw +} +function markedSpansAfter(old, endCh, isInsert) { + var nw + if (old) { for (var i = 0; i < old.length; ++i) { + var span = old[i], marker = span.marker + var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh) + if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) { + var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh) + ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh, + span.to == null ? null : span.to - endCh)) + } + } } + return nw +} + +// Given a change object, compute the new set of marker spans that +// cover the line in which the change took place. Removes spans +// entirely within the change, reconnects spans belonging to the +// same marker that appear on both sides of the change, and cuts off +// spans partially within the change. Returns an array of span +// arrays with one element for each line in (after) the change. +function stretchSpansOverChange(doc, change) { + if (change.full) { return null } + var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans + var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans + if (!oldFirst && !oldLast) { return null } + + var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0 + // Get the spans that 'stick out' on both sides + var first = markedSpansBefore(oldFirst, startCh, isInsert) + var last = markedSpansAfter(oldLast, endCh, isInsert) + + // Next, merge those two ends + var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0) + if (first) { + // Fix up .to properties of first + for (var i = 0; i < first.length; ++i) { + var span = first[i] + if (span.to == null) { + var found = getMarkedSpanFor(last, span.marker) + if (!found) { span.to = startCh } + else if (sameLine) { span.to = found.to == null ? null : found.to + offset } } } - gutters.style.display = i ? "" : "none"; - } - - function lineLength(doc, line) { - if (line.height == 0) return 0; - var len = line.text.length, merged, cur = line; - while (merged = collapsedSpanAtStart(cur)) { - var found = merged.find(); - cur = getLine(doc, found.from.line); - len += found.from.ch - found.to.ch; - } - cur = line; - while (merged = collapsedSpanAtEnd(cur)) { - var found = merged.find(); - len -= cur.text.length - found.from.ch; - cur = getLine(doc, found.to.line); - len += cur.text.length - found.to.ch; - } - return len; - } - - function computeMaxLength(cm) { - var d = cm.display, doc = cm.doc; - d.maxLine = getLine(doc, doc.first); - d.maxLineLength = lineLength(doc, d.maxLine); - d.maxLineChanged = true; - doc.iter(function(line) { - var len = lineLength(doc, line); - if (len > d.maxLineLength) { - d.maxLineLength = len; - d.maxLine = line; + } + if (last) { + // Fix up .from in last (or move them into first in case of sameLine) + for (var i$1 = 0; i$1 < last.length; ++i$1) { + var span$1 = last[i$1] + if (span$1.to != null) { span$1.to += offset } + if (span$1.from == null) { + var found$1 = getMarkedSpanFor(first, span$1.marker) + if (!found$1) { + span$1.from = offset + if (sameLine) { (first || (first = [])).push(span$1) } + } + } else { + span$1.from += offset + if (sameLine) { (first || (first = [])).push(span$1) } } - }); - } - - // Make sure the gutters options contains the element - // "CodeMirror-linenumbers" when the lineNumbers option is true. - function setGuttersForLineNumbers(options) { - var found = indexOf(options.gutters, "CodeMirror-linenumbers"); - if (found == -1 && options.lineNumbers) { - options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]); - } else if (found > -1 && !options.lineNumbers) { - options.gutters = options.gutters.slice(0); - options.gutters.splice(found, 1); - } - } - - // SCROLLBARS - - // Re-synchronize the fake scrollbars with the actual size of the - // content. Optionally force a scrollTop. - function updateScrollbars(cm) { - var d = cm.display, docHeight = cm.doc.height; - var totalHeight = docHeight + paddingVert(d); - d.sizer.style.minHeight = d.heightForcer.style.top = totalHeight + "px"; - d.gutters.style.height = Math.max(totalHeight, d.scroller.clientHeight - scrollerCutOff) + "px"; - var scrollHeight = Math.max(totalHeight, d.scroller.scrollHeight); - var needsH = d.scroller.scrollWidth > (d.scroller.clientWidth + 1); - var needsV = scrollHeight > (d.scroller.clientHeight + 1); - if (needsV) { - d.scrollbarV.style.display = "block"; - d.scrollbarV.style.bottom = needsH ? scrollbarWidth(d.measure) + "px" : "0"; - d.scrollbarV.firstChild.style.height = - (scrollHeight - d.scroller.clientHeight + d.scrollbarV.clientHeight) + "px"; - } else { - d.scrollbarV.style.display = ""; - d.scrollbarV.firstChild.style.height = "0"; - } - if (needsH) { - d.scrollbarH.style.display = "block"; - d.scrollbarH.style.right = needsV ? scrollbarWidth(d.measure) + "px" : "0"; - d.scrollbarH.firstChild.style.width = - (d.scroller.scrollWidth - d.scroller.clientWidth + d.scrollbarH.clientWidth) + "px"; - } else { - d.scrollbarH.style.display = ""; - d.scrollbarH.firstChild.style.width = "0"; - } - if (needsH && needsV) { - d.scrollbarFiller.style.display = "block"; - d.scrollbarFiller.style.height = d.scrollbarFiller.style.width = scrollbarWidth(d.measure) + "px"; - } else d.scrollbarFiller.style.display = ""; - if (needsH && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) { - d.gutterFiller.style.display = "block"; - d.gutterFiller.style.height = scrollbarWidth(d.measure) + "px"; - d.gutterFiller.style.width = d.gutters.offsetWidth + "px"; - } else d.gutterFiller.style.display = ""; - - if (mac_geLion && scrollbarWidth(d.measure) === 0) { - d.scrollbarV.style.minWidth = d.scrollbarH.style.minHeight = mac_geMountainLion ? "18px" : "12px"; - d.scrollbarV.style.pointerEvents = d.scrollbarH.style.pointerEvents = "none"; } } - - function visibleLines(display, doc, viewPort) { - var top = display.scroller.scrollTop, height = display.wrapper.clientHeight; - if (typeof viewPort == "number") top = viewPort; - else if (viewPort) {top = viewPort.top; height = viewPort.bottom - viewPort.top;} - top = Math.floor(top - paddingTop(display)); - var bottom = Math.ceil(top + height); - return {from: lineAtHeight(doc, top), to: lineAtHeight(doc, bottom)}; - } - - // LINE NUMBERS - - function alignHorizontally(cm) { - var display = cm.display; - if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return; - var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft; - var gutterW = display.gutters.offsetWidth, l = comp + "px"; - for (var n = display.lineDiv.firstChild; n; n = n.nextSibling) if (n.alignable) { - for (var i = 0, a = n.alignable; i < a.length; ++i) a[i].style.left = l; + // Make sure we didn't create any zero-length spans + if (first) { first = clearEmptySpans(first) } + if (last && last != first) { last = clearEmptySpans(last) } + + var newMarkers = [first] + if (!sameLine) { + // Fill gap with whole-line-spans + var gap = change.text.length - 2, gapMarkers + if (gap > 0 && first) + { for (var i$2 = 0; i$2 < first.length; ++i$2) + { if (first[i$2].to == null) + { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)) } } } + for (var i$3 = 0; i$3 < gap; ++i$3) + { newMarkers.push(gapMarkers) } + newMarkers.push(last) + } + return newMarkers +} + +// Remove spans that are empty and don't have a clearWhenEmpty +// option of false. +function clearEmptySpans(spans) { + for (var i = 0; i < spans.length; ++i) { + var span = spans[i] + if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) + { spans.splice(i--, 1) } + } + if (!spans.length) { return null } + return spans +} + +// Used to 'clip' out readOnly ranges when making a change. +function removeReadOnlyRanges(doc, from, to) { + var markers = null + doc.iter(from.line, to.line + 1, function (line) { + if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) { + var mark = line.markedSpans[i].marker + if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) + { (markers || (markers = [])).push(mark) } + } } + }) + if (!markers) { return null } + var parts = [{from: from, to: to}] + for (var i = 0; i < markers.length; ++i) { + var mk = markers[i], m = mk.find(0) + for (var j = 0; j < parts.length; ++j) { + var p = parts[j] + if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue } + var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to) + if (dfrom < 0 || !mk.inclusiveLeft && !dfrom) + { newParts.push({from: p.from, to: m.from}) } + if (dto > 0 || !mk.inclusiveRight && !dto) + { newParts.push({from: m.to, to: p.to}) } + parts.splice.apply(parts, newParts) + j += newParts.length - 1 + } + } + return parts +} + +// Connect or disconnect spans from a line. +function detachMarkedSpans(line) { + var spans = line.markedSpans + if (!spans) { return } + for (var i = 0; i < spans.length; ++i) + { spans[i].marker.detachLine(line) } + line.markedSpans = null +} +function attachMarkedSpans(line, spans) { + if (!spans) { return } + for (var i = 0; i < spans.length; ++i) + { spans[i].marker.attachLine(line) } + line.markedSpans = spans +} + +// Helpers used when computing which overlapping collapsed span +// counts as the larger one. +function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 } +function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 } + +// Returns a number indicating which of two overlapping collapsed +// spans is larger (and thus includes the other). Falls back to +// comparing ids when the spans cover exactly the same range. +function compareCollapsedMarkers(a, b) { + var lenDiff = a.lines.length - b.lines.length + if (lenDiff != 0) { return lenDiff } + var aPos = a.find(), bPos = b.find() + var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b) + if (fromCmp) { return -fromCmp } + var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b) + if (toCmp) { return toCmp } + return b.id - a.id +} + +// Find out whether a line ends or starts in a collapsed span. If +// so, return the marker for that span. +function collapsedSpanAtSide(line, start) { + var sps = sawCollapsedSpans && line.markedSpans, found + if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) { + sp = sps[i] + if (sp.marker.collapsed && (start ? sp.from : sp.to) == null && + (!found || compareCollapsedMarkers(found, sp.marker) < 0)) + { found = sp.marker } + } } + return found +} +function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) } +function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) } + +// Test whether there exists a collapsed span that partially +// overlaps (covers the start or end, but not both) of a new span. +// Such overlap is not allowed. +function conflictingCollapsedRange(doc, lineNo, from, to, marker) { + var line = getLine(doc, lineNo) + var sps = sawCollapsedSpans && line.markedSpans + if (sps) { for (var i = 0; i < sps.length; ++i) { + var sp = sps[i] + if (!sp.marker.collapsed) { continue } + var found = sp.marker.find(0) + var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker) + var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker) + if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue } + if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) || + fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0)) + { return true } + } } +} + +// A visual line is a line as drawn on the screen. Folding, for +// example, can cause multiple logical lines to appear on the same +// visual line. This finds the start of the visual line that the +// given line is part of (usually that is the line itself). +function visualLine(line) { + var merged + while (merged = collapsedSpanAtStart(line)) + { line = merged.find(-1, true).line } + return line +} + +// Returns an array of logical lines that continue the visual line +// started by the argument, or undefined if there are no such lines. +function visualLineContinued(line) { + var merged, lines + while (merged = collapsedSpanAtEnd(line)) { + line = merged.find(1, true).line + ;(lines || (lines = [])).push(line) + } + return lines +} + +// Get the line number of the start of the visual line that the +// given line number is part of. +function visualLineNo(doc, lineN) { + var line = getLine(doc, lineN), vis = visualLine(line) + if (line == vis) { return lineN } + return lineNo(vis) +} + +// Get the line number of the start of the next visual line after +// the given line. +function visualLineEndNo(doc, lineN) { + if (lineN > doc.lastLine()) { return lineN } + var line = getLine(doc, lineN), merged + if (!lineIsHidden(doc, line)) { return lineN } + while (merged = collapsedSpanAtEnd(line)) + { line = merged.find(1, true).line } + return lineNo(line) + 1 +} + +// Compute whether a line is hidden. Lines count as hidden when they +// are part of a visual line that starts with another line, or when +// they are entirely covered by collapsed, non-widget span. +function lineIsHidden(doc, line) { + var sps = sawCollapsedSpans && line.markedSpans + if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) { + sp = sps[i] + if (!sp.marker.collapsed) { continue } + if (sp.from == null) { return true } + if (sp.marker.widgetNode) { continue } + if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) + { return true } + } } +} +function lineIsHiddenInner(doc, line, span) { + if (span.to == null) { + var end = span.marker.find(1, true) + return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker)) + } + if (span.marker.inclusiveRight && span.to == line.text.length) + { return true } + for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) { + sp = line.markedSpans[i] + if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to && + (sp.to == null || sp.to != span.from) && + (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && + lineIsHiddenInner(doc, line, sp)) { return true } + } +} + +// Find the height above the given line. +function heightAtLine(lineObj) { + lineObj = visualLine(lineObj) + + var h = 0, chunk = lineObj.parent + for (var i = 0; i < chunk.lines.length; ++i) { + var line = chunk.lines[i] + if (line == lineObj) { break } + else { h += line.height } + } + for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { + for (var i$1 = 0; i$1 < p.children.length; ++i$1) { + var cur = p.children[i$1] + if (cur == chunk) { break } + else { h += cur.height } + } + } + return h +} + +// Compute the character length of a line, taking into account +// collapsed ranges (see markText) that might hide parts, and join +// other lines onto it. +function lineLength(line) { + if (line.height == 0) { return 0 } + var len = line.text.length, merged, cur = line + while (merged = collapsedSpanAtStart(cur)) { + var found = merged.find(0, true) + cur = found.from.line + len += found.from.ch - found.to.ch + } + cur = line + while (merged = collapsedSpanAtEnd(cur)) { + var found$1 = merged.find(0, true) + len -= cur.text.length - found$1.from.ch + cur = found$1.to.line + len += cur.text.length - found$1.to.ch + } + return len +} + +// Find the longest line in the document. +function findMaxLine(cm) { + var d = cm.display, doc = cm.doc + d.maxLine = getLine(doc, doc.first) + d.maxLineLength = lineLength(d.maxLine) + d.maxLineChanged = true + doc.iter(function (line) { + var len = lineLength(line) + if (len > d.maxLineLength) { + d.maxLineLength = len + d.maxLine = line + } + }) +} + +// BIDI HELPERS + +function iterateBidiSections(order, from, to, f) { + if (!order) { return f(from, to, "ltr") } + var found = false + for (var i = 0; i < order.length; ++i) { + var part = order[i] + if (part.from < to && part.to > from || from == to && part.to == from) { + f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr") + found = true + } + } + if (!found) { f(from, to, "ltr") } +} + +function bidiLeft(part) { return part.level % 2 ? part.to : part.from } +function bidiRight(part) { return part.level % 2 ? part.from : part.to } + +function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0 } +function lineRight(line) { + var order = getOrder(line) + if (!order) { return line.text.length } + return bidiRight(lst(order)) +} + +function compareBidiLevel(order, a, b) { + var linedir = order[0].level + if (a == linedir) { return true } + if (b == linedir) { return false } + return a < b +} + +var bidiOther = null +function getBidiPartAt(order, pos) { + var found + bidiOther = null + for (var i = 0; i < order.length; ++i) { + var cur = order[i] + if (cur.from < pos && cur.to > pos) { return i } + if ((cur.from == pos || cur.to == pos)) { + if (found == null) { + found = i + } else if (compareBidiLevel(order, cur.level, order[found].level)) { + if (cur.from != cur.to) { bidiOther = found } + return i + } else { + if (cur.from != cur.to) { bidiOther = i } + return found + } } - if (cm.options.fixedGutter) - display.gutters.style.left = (comp + gutterW) + "px"; } - - function maybeUpdateLineNumberWidth(cm) { - if (!cm.options.lineNumbers) return false; - var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display; - if (last.length != display.lineNumChars) { - var test = display.measure.appendChild(elt("div", [elt("div", last)], - "CodeMirror-linenumber CodeMirror-gutter-elt")); - var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW; - display.lineGutter.style.width = ""; - display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding); - display.lineNumWidth = display.lineNumInnerWidth + padding; - display.lineNumChars = display.lineNumInnerWidth ? last.length : -1; - display.lineGutter.style.width = display.lineNumWidth + "px"; - return true; + return found +} + +function moveInLine(line, pos, dir, byUnit) { + if (!byUnit) { return pos + dir } + do { pos += dir } + while (pos > 0 && isExtendingChar(line.text.charAt(pos))) + return pos +} + +// This is needed in order to move 'visually' through bi-directional +// text -- i.e., pressing left should make the cursor go left, even +// when in RTL text. The tricky part is the 'jumps', where RTL and +// LTR text touch each other. This often requires the cursor offset +// to move more than one unit, in order to visually move one unit. +function moveVisually(line, start, dir, byUnit) { + var bidi = getOrder(line) + if (!bidi) { return moveLogically(line, start, dir, byUnit) } + var pos = getBidiPartAt(bidi, start), part = bidi[pos] + var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit) + + for (;;) { + if (target > part.from && target < part.to) { return target } + if (target == part.from || target == part.to) { + if (getBidiPartAt(bidi, target) == pos) { return target } + part = bidi[pos += dir] + return (dir > 0) == part.level % 2 ? part.to : part.from + } else { + part = bidi[pos += dir] + if (!part) { return null } + if ((dir > 0) == part.level % 2) + { target = moveInLine(line, part.to, -1, byUnit) } + else + { target = moveInLine(line, part.from, 1, byUnit) } + } + } +} + +function moveLogically(line, start, dir, byUnit) { + var target = start + dir + if (byUnit) { while (target > 0 && isExtendingChar(line.text.charAt(target))) { target += dir } } + return target < 0 || target > line.text.length ? null : target +} + +// Bidirectional ordering algorithm +// See http://unicode.org/reports/tr9/tr9-13.html for the algorithm +// that this (partially) implements. + +// One-char codes used for character types: +// L (L): Left-to-Right +// R (R): Right-to-Left +// r (AL): Right-to-Left Arabic +// 1 (EN): European Number +// + (ES): European Number Separator +// % (ET): European Number Terminator +// n (AN): Arabic Number +// , (CS): Common Number Separator +// m (NSM): Non-Spacing Mark +// b (BN): Boundary Neutral +// s (B): Paragraph Separator +// t (S): Segment Separator +// w (WS): Whitespace +// N (ON): Other Neutrals + +// Returns null if characters are ordered as they appear +// (left-to-right), or an array of sections ({from, to, level} +// objects) in the order in which they occur visually. +var bidiOrdering = (function() { + // Character types for codepoints 0 to 0xff + var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN" + // Character types for codepoints 0x600 to 0x6f9 + var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111" + function charType(code) { + if (code <= 0xf7) { return lowTypes.charAt(code) } + else if (0x590 <= code && code <= 0x5f4) { return "R" } + else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) } + else if (0x6ee <= code && code <= 0x8ac) { return "r" } + else if (0x2000 <= code && code <= 0x200b) { return "w" } + else if (code == 0x200c) { return "b" } + else { return "L" } + } + + var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; + var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/; + // Browsers seem to always treat the boundaries of block elements as being L. + var outerType = "L" + + function BidiSpan(level, from, to) { + this.level = level + this.from = from; this.to = to + } + + return function(str) { + if (!bidiRE.test(str)) { return false } + var len = str.length, types = [] + for (var i = 0; i < len; ++i) + { types.push(charType(str.charCodeAt(i))) } + + // W1. Examine each non-spacing mark (NSM) in the level run, and + // change the type of the NSM to the type of the previous + // character. If the NSM is at the start of the level run, it will + // get the type of sor. + for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) { + var type = types[i$1] + if (type == "m") { types[i$1] = prev } + else { prev = type } + } + + // W2. Search backwards from each instance of a European number + // until the first strong type (R, L, AL, or sor) is found. If an + // AL is found, change the type of the European number to Arabic + // number. + // W3. Change all ALs to R. + for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) { + var type$1 = types[i$2] + if (type$1 == "1" && cur == "r") { types[i$2] = "n" } + else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R" } } + } + + // W4. A single European separator between two European numbers + // changes to a European number. A single common separator between + // two numbers of the same type changes to that type. + for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) { + var type$2 = types[i$3] + if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1" } + else if (type$2 == "," && prev$1 == types[i$3+1] && + (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1 } + prev$1 = type$2 + } + + // W5. A sequence of European terminators adjacent to European + // numbers changes to all European numbers. + // W6. Otherwise, separators and terminators change to Other + // Neutral. + for (var i$4 = 0; i$4 < len; ++i$4) { + var type$3 = types[i$4] + if (type$3 == ",") { types[i$4] = "N" } + else if (type$3 == "%") { + var end = (void 0) + for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {} + var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N" + for (var j = i$4; j < end; ++j) { types[j] = replace } + i$4 = end - 1 + } } - return false; - } - - function lineNumberFor(options, i) { - return String(options.lineNumberFormatter(i + options.firstLineNumber)); - } - function compensateForHScroll(display) { - return getRect(display.scroller).left - getRect(display.sizer).left; - } - // DISPLAY DRAWING - - function updateDisplay(cm, changes, viewPort, forced) { - var oldFrom = cm.display.showingFrom, oldTo = cm.display.showingTo, updated; - var visible = visibleLines(cm.display, cm.doc, viewPort); - for (var first = true;; first = false) { - var oldWidth = cm.display.scroller.clientWidth; - if (!updateDisplayInner(cm, changes, visible, forced)) break; - updated = true; - changes = []; - updateSelection(cm); - updateScrollbars(cm); - if (first && cm.options.lineWrapping && oldWidth != cm.display.scroller.clientWidth) { - forced = true; - continue; + // W7. Search backwards from each instance of a European number + // until the first strong type (R, L, or sor) is found. If an L is + // found, then change the type of the European number to L. + for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) { + var type$4 = types[i$5] + if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L" } + else if (isStrong.test(type$4)) { cur$1 = type$4 } + } + + // N1. A sequence of neutrals takes the direction of the + // surrounding strong text if the text on both sides has the same + // direction. European and Arabic numbers act as if they were R in + // terms of their influence on neutrals. Start-of-level-run (sor) + // and end-of-level-run (eor) are used at level run boundaries. + // N2. Any remaining neutrals take the embedding direction. + for (var i$6 = 0; i$6 < len; ++i$6) { + if (isNeutral.test(types[i$6])) { + var end$1 = (void 0) + for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {} + var before = (i$6 ? types[i$6-1] : outerType) == "L" + var after = (end$1 < len ? types[end$1] : outerType) == "L" + var replace$1 = before || after ? "L" : "R" + for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1 } + i$6 = end$1 - 1 } - forced = false; - - // Clip forced viewport to actual scrollable area - if (viewPort) - viewPort = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, - typeof viewPort == "number" ? viewPort : viewPort.top); - visible = visibleLines(cm.display, cm.doc, viewPort); - if (visible.from >= cm.display.showingFrom && visible.to <= cm.display.showingTo) - break; - } - - if (updated) { - signalLater(cm, "update", cm); - if (cm.display.showingFrom != oldFrom || cm.display.showingTo != oldTo) - signalLater(cm, "viewportChange", cm, cm.display.showingFrom, cm.display.showingTo); - } - return updated; - } - - // Uses a set of changes plus the current scroll position to - // determine which DOM updates have to be made, and makes the - // updates. - function updateDisplayInner(cm, changes, visible, forced) { - var display = cm.display, doc = cm.doc; - if (!display.wrapper.clientWidth) { - display.showingFrom = display.showingTo = doc.first; - display.viewOffset = 0; - return; - } - - // Bail out if the visible area is already rendered and nothing changed. - if (!forced && changes.length == 0 && - visible.from > display.showingFrom && visible.to < display.showingTo) - return; - - if (maybeUpdateLineNumberWidth(cm)) - changes = [{from: doc.first, to: doc.first + doc.size}]; - var gutterW = display.sizer.style.marginLeft = display.gutters.offsetWidth + "px"; - display.scrollbarH.style.left = cm.options.fixedGutter ? gutterW : "0"; - - // Used to determine which lines need their line numbers updated - var positionsChangedFrom = Infinity; - if (cm.options.lineNumbers) - for (var i = 0; i < changes.length; ++i) - if (changes[i].diff && changes[i].from < positionsChangedFrom) { positionsChangedFrom = changes[i].from; } - - var end = doc.first + doc.size; - var from = Math.max(visible.from - cm.options.viewportMargin, doc.first); - var to = Math.min(end, visible.to + cm.options.viewportMargin); - if (display.showingFrom < from && from - display.showingFrom < 20) from = Math.max(doc.first, display.showingFrom); - if (display.showingTo > to && display.showingTo - to < 20) to = Math.min(end, display.showingTo); - if (sawCollapsedSpans) { - from = lineNo(visualLine(doc, getLine(doc, from))); - while (to < end && lineIsHidden(doc, getLine(doc, to))) ++to; - } - - // Create a range of theoretically intact lines, and punch holes - // in that using the change info. - var intact = [{from: Math.max(display.showingFrom, doc.first), - to: Math.min(display.showingTo, end)}]; - if (intact[0].from >= intact[0].to) intact = []; - else intact = computeIntact(intact, changes); - // When merged lines are present, we might have to reduce the - // intact ranges because changes in continued fragments of the - // intact lines do require the lines to be redrawn. - if (sawCollapsedSpans) - for (var i = 0; i < intact.length; ++i) { - var range = intact[i], merged; - while (merged = collapsedSpanAtEnd(getLine(doc, range.to - 1))) { - var newTo = merged.find().from.line; - if (newTo > range.from) range.to = newTo; - else { intact.splice(i--, 1); break; } - } - } - - // Clip off the parts that won't be visible - var intactLines = 0; - for (var i = 0; i < intact.length; ++i) { - var range = intact[i]; - if (range.from < from) range.from = from; - if (range.to > to) range.to = to; - if (range.from >= range.to) intact.splice(i--, 1); - else intactLines += range.to - range.from; - } - if (!forced && intactLines == to - from && from == display.showingFrom && to == display.showingTo) { - updateViewOffset(cm); - return; } - intact.sort(function(a, b) {return a.from - b.from;}); - // Avoid crashing on IE's "unspecified error" when in iframes - try { - var focused = document.activeElement; - } catch(e) {} - if (intactLines < (to - from) * .7) display.lineDiv.style.display = "none"; - patchDisplay(cm, from, to, intact, positionsChangedFrom); - display.lineDiv.style.display = ""; - if (focused && document.activeElement != focused && focused.offsetHeight) focused.focus(); - - var different = from != display.showingFrom || to != display.showingTo || - display.lastSizeC != display.wrapper.clientHeight; - // This is just a bogus formula that detects when the editor is - // resized or the font size changes. - if (different) { - display.lastSizeC = display.wrapper.clientHeight; - startWorker(cm, 400); - } - display.showingFrom = from; display.showingTo = to; - - updateHeightsInViewport(cm); - updateViewOffset(cm); - - return true; - } - - function updateHeightsInViewport(cm) { - var display = cm.display; - var prevBottom = display.lineDiv.offsetTop; - for (var node = display.lineDiv.firstChild, height; node; node = node.nextSibling) if (node.lineObj) { - if (ie_lt8) { - var bot = node.offsetTop + node.offsetHeight; - height = bot - prevBottom; - prevBottom = bot; + // Here we depart from the documented algorithm, in order to avoid + // building up an actual levels array. Since there are only three + // levels (0, 1, 2) in an implementation that doesn't take + // explicit embedding into account, we can build up the order on + // the fly, without following the level-based algorithm. + var order = [], m + for (var i$7 = 0; i$7 < len;) { + if (countsAsLeft.test(types[i$7])) { + var start = i$7 + for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {} + order.push(new BidiSpan(0, start, i$7)) } else { - var box = getRect(node); - height = box.bottom - box.top; - } - var diff = node.lineObj.height - height; - if (height < 2) height = textHeight(display); - if (diff > .001 || diff < -.001) { - updateLineHeight(node.lineObj, height); - var widgets = node.lineObj.widgets; - if (widgets) for (var i = 0; i < widgets.length; ++i) - widgets[i].height = widgets[i].node.offsetHeight; + var pos = i$7, at = order.length + for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {} + for (var j$2 = pos; j$2 < i$7;) { + if (countsAsNum.test(types[j$2])) { + if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)) } + var nstart = j$2 + for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {} + order.splice(at, 0, new BidiSpan(2, nstart, j$2)) + pos = j$2 + } else { ++j$2 } + } + if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)) } } } - } - - function updateViewOffset(cm) { - var off = cm.display.viewOffset = heightAtLine(cm, getLine(cm.doc, cm.display.showingFrom)); - // Position the mover div to align with the current virtual scroll position - cm.display.mover.style.top = off + "px"; - } - - function computeIntact(intact, changes) { - for (var i = 0, l = changes.length || 0; i < l; ++i) { - var change = changes[i], intact2 = [], diff = change.diff || 0; - for (var j = 0, l2 = intact.length; j < l2; ++j) { - var range = intact[j]; - if (change.to <= range.from && change.diff) { - intact2.push({from: range.from + diff, to: range.to + diff}); - } else if (change.to <= range.from || change.from >= range.to) { - intact2.push(range); - } else { - if (change.from > range.from) - intact2.push({from: range.from, to: change.from}); - if (change.to < range.to) - intact2.push({from: change.to + diff, to: range.to + diff}); + if (order[0].level == 1 && (m = str.match(/^\s+/))) { + order[0].from = m[0].length + order.unshift(new BidiSpan(0, 0, m[0].length)) + } + if (lst(order).level == 1 && (m = str.match(/\s+$/))) { + lst(order).to -= m[0].length + order.push(new BidiSpan(0, len - m[0].length, len)) + } + if (order[0].level == 2) + { order.unshift(new BidiSpan(1, order[0].to, order[0].to)) } + if (order[0].level != lst(order).level) + { order.push(new BidiSpan(order[0].level, len, len)) } + + return order + } +})() + +// Get the bidi ordering for the given line (and cache it). Returns +// false for lines that are fully left-to-right, and an array of +// BidiSpan objects otherwise. +function getOrder(line) { + var order = line.order + if (order == null) { order = line.order = bidiOrdering(line.text) } + return order +} + +// EVENT HANDLING + +// Lightweight event framework. on/off also work on DOM nodes, +// registering native DOM handlers. + +var noHandlers = [] + +var on = function(emitter, type, f) { + if (emitter.addEventListener) { + emitter.addEventListener(type, f, false) + } else if (emitter.attachEvent) { + emitter.attachEvent("on" + type, f) + } else { + var map = emitter._handlers || (emitter._handlers = {}) + map[type] = (map[type] || noHandlers).concat(f) + } +} + +function getHandlers(emitter, type) { + return emitter._handlers && emitter._handlers[type] || noHandlers +} + +function off(emitter, type, f) { + if (emitter.removeEventListener) { + emitter.removeEventListener(type, f, false) + } else if (emitter.detachEvent) { + emitter.detachEvent("on" + type, f) + } else { + var map = emitter._handlers, arr = map && map[type] + if (arr) { + var index = indexOf(arr, f) + if (index > -1) + { map[type] = arr.slice(0, index).concat(arr.slice(index + 1)) } + } + } +} + +function signal(emitter, type /*, values...*/) { + var handlers = getHandlers(emitter, type) + if (!handlers.length) { return } + var args = Array.prototype.slice.call(arguments, 2) + for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args) } +} + +// The DOM events that CodeMirror handles can be overridden by +// registering a (non-DOM) handler on the editor for the event name, +// and preventDefault-ing the event in that handler. +function signalDOMEvent(cm, e, override) { + if (typeof e == "string") + { e = {type: e, preventDefault: function() { this.defaultPrevented = true }} } + signal(cm, override || e.type, cm, e) + return e_defaultPrevented(e) || e.codemirrorIgnore +} + +function signalCursorActivity(cm) { + var arr = cm._handlers && cm._handlers.cursorActivity + if (!arr) { return } + var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []) + for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1) + { set.push(arr[i]) } } +} + +function hasHandler(emitter, type) { + return getHandlers(emitter, type).length > 0 +} + +// Add on and off methods to a constructor's prototype, to make +// registering events on such objects more convenient. +function eventMixin(ctor) { + ctor.prototype.on = function(type, f) {on(this, type, f)} + ctor.prototype.off = function(type, f) {off(this, type, f)} +} + +// Due to the fact that we still support jurassic IE versions, some +// compatibility wrappers are needed. + +function e_preventDefault(e) { + if (e.preventDefault) { e.preventDefault() } + else { e.returnValue = false } +} +function e_stopPropagation(e) { + if (e.stopPropagation) { e.stopPropagation() } + else { e.cancelBubble = true } +} +function e_defaultPrevented(e) { + return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false +} +function e_stop(e) {e_preventDefault(e); e_stopPropagation(e)} + +function e_target(e) {return e.target || e.srcElement} +function e_button(e) { + var b = e.which + if (b == null) { + if (e.button & 1) { b = 1 } + else if (e.button & 2) { b = 3 } + else if (e.button & 4) { b = 2 } + } + if (mac && e.ctrlKey && b == 1) { b = 3 } + return b +} + +// Detect drag-and-drop +var dragAndDrop = function() { + // There is *some* kind of drag-and-drop support in IE6-8, but I + // couldn't get it to work yet. + if (ie && ie_version < 9) { return false } + var div = elt('div') + return "draggable" in div || "dragDrop" in div +}() + +var zwspSupported +function zeroWidthElement(measure) { + if (zwspSupported == null) { + var test = elt("span", "\u200b") + removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])) + if (measure.firstChild.offsetHeight != 0) + { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8) } + } + var node = zwspSupported ? elt("span", "\u200b") : + elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px") + node.setAttribute("cm-text", "") + return node +} + +// Feature-detect IE's crummy client rect reporting for bidi text +var badBidiRects +function hasBadBidiRects(measure) { + if (badBidiRects != null) { return badBidiRects } + var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA")) + var r0 = range(txt, 0, 1).getBoundingClientRect() + var r1 = range(txt, 1, 2).getBoundingClientRect() + removeChildren(measure) + if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780) + return badBidiRects = (r1.right - r0.right < 3) +} + +// See if "".split is the broken IE version, if so, provide an +// alternative way to split lines. +var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) { + var pos = 0, result = [], l = string.length + while (pos <= l) { + var nl = string.indexOf("\n", pos) + if (nl == -1) { nl = string.length } + var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl) + var rt = line.indexOf("\r") + if (rt != -1) { + result.push(line.slice(0, rt)) + pos += rt + 1 + } else { + result.push(line) + pos = nl + 1 + } + } + return result +} : function (string) { return string.split(/\r\n?|\n/); } + +var hasSelection = window.getSelection ? function (te) { + try { return te.selectionStart != te.selectionEnd } + catch(e) { return false } +} : function (te) { + var range + try {range = te.ownerDocument.selection.createRange()} + catch(e) {} + if (!range || range.parentElement() != te) { return false } + return range.compareEndPoints("StartToEnd", range) != 0 +} + +var hasCopyEvent = (function () { + var e = elt("div") + if ("oncopy" in e) { return true } + e.setAttribute("oncopy", "return;") + return typeof e.oncopy == "function" +})() + +var badZoomedRects = null +function hasBadZoomedRects(measure) { + if (badZoomedRects != null) { return badZoomedRects } + var node = removeChildrenAndAdd(measure, elt("span", "x")) + var normal = node.getBoundingClientRect() + var fromRange = range(node, 0, 1).getBoundingClientRect() + return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1 +} + +var modes = {}; +var mimeModes = {}; +// Extra arguments are stored as the mode's dependencies, which is +// used by (legacy) mechanisms like loadmode.js to automatically +// load a mode. (Preferred mechanism is the require/define calls.) +function defineMode(name, mode) { + if (arguments.length > 2) + { mode.dependencies = Array.prototype.slice.call(arguments, 2) } + modes[name] = mode +} + +function defineMIME(mime, spec) { + mimeModes[mime] = spec +} + +// Given a MIME type, a {name, ...options} config object, or a name +// string, return a mode config object. +function resolveMode(spec) { + if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { + spec = mimeModes[spec] + } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) { + var found = mimeModes[spec.name] + if (typeof found == "string") { found = {name: found} } + spec = createObj(found, spec) + spec.name = found.name + } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) { + return resolveMode("application/xml") + } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) { + return resolveMode("application/json") + } + if (typeof spec == "string") { return {name: spec} } + else { return spec || {name: "null"} } +} + +// Given a mode spec (anything that resolveMode accepts), find and +// initialize an actual mode object. +function getMode(options, spec) { + spec = resolveMode(spec) + var mfactory = modes[spec.name] + if (!mfactory) { return getMode(options, "text/plain") } + var modeObj = mfactory(options, spec) + if (modeExtensions.hasOwnProperty(spec.name)) { + var exts = modeExtensions[spec.name] + for (var prop in exts) { + if (!exts.hasOwnProperty(prop)) { continue } + if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop] } + modeObj[prop] = exts[prop] + } + } + modeObj.name = spec.name + if (spec.helperType) { modeObj.helperType = spec.helperType } + if (spec.modeProps) { for (var prop$1 in spec.modeProps) + { modeObj[prop$1] = spec.modeProps[prop$1] } } + + return modeObj +} + +// This can be used to attach properties to mode objects from +// outside the actual mode definition. +var modeExtensions = {} +function extendMode(mode, properties) { + var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}) + copyObj(properties, exts) +} + +function copyState(mode, state) { + if (state === true) { return state } + if (mode.copyState) { return mode.copyState(state) } + var nstate = {} + for (var n in state) { + var val = state[n] + if (val instanceof Array) { val = val.concat([]) } + nstate[n] = val + } + return nstate +} + +// Given a mode and a state (for that mode), find the inner mode and +// state at the position that the state refers to. +function innerMode(mode, state) { + var info + while (mode.innerMode) { + info = mode.innerMode(state) + if (!info || info.mode == mode) { break } + state = info.state + mode = info.mode + } + return info || {mode: mode, state: state} +} + +function startState(mode, a1, a2) { + return mode.startState ? mode.startState(a1, a2) : true +} + +// STRING STREAM + +// Fed to the mode parsers, provides helper functions to make +// parsers more succinct. + +var StringStream = function(string, tabSize) { + this.pos = this.start = 0 + this.string = string + this.tabSize = tabSize || 8 + this.lastColumnPos = this.lastColumnValue = 0 + this.lineStart = 0 +} + +StringStream.prototype = { + eol: function() {return this.pos >= this.string.length}, + sol: function() {return this.pos == this.lineStart}, + peek: function() {return this.string.charAt(this.pos) || undefined}, + next: function() { + if (this.pos < this.string.length) + { return this.string.charAt(this.pos++) } + }, + eat: function(match) { + var ch = this.string.charAt(this.pos) + var ok + if (typeof match == "string") { ok = ch == match } + else { ok = ch && (match.test ? match.test(ch) : match(ch)) } + if (ok) {++this.pos; return ch} + }, + eatWhile: function(match) { + var start = this.pos + while (this.eat(match)){} + return this.pos > start + }, + eatSpace: function() { + var this$1 = this; + + var start = this.pos + while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this$1.pos } + return this.pos > start + }, + skipToEnd: function() {this.pos = this.string.length}, + skipTo: function(ch) { + var found = this.string.indexOf(ch, this.pos) + if (found > -1) {this.pos = found; return true} + }, + backUp: function(n) {this.pos -= n}, + column: function() { + if (this.lastColumnPos < this.start) { + this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue) + this.lastColumnPos = this.start + } + return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0) + }, + indentation: function() { + return countColumn(this.string, null, this.tabSize) - + (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0) + }, + match: function(pattern, consume, caseInsensitive) { + if (typeof pattern == "string") { + var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; } + var substr = this.string.substr(this.pos, pattern.length) + if (cased(substr) == cased(pattern)) { + if (consume !== false) { this.pos += pattern.length } + return true + } + } else { + var match = this.string.slice(this.pos).match(pattern) + if (match && match.index > 0) { return null } + if (match && consume !== false) { this.pos += match[0].length } + return match + } + }, + current: function(){return this.string.slice(this.start, this.pos)}, + hideFirstChars: function(n, inner) { + this.lineStart += n + try { return inner() } + finally { this.lineStart -= n } + } +} + +// Compute a style array (an array starting with a mode generation +// -- for invalidation -- followed by pairs of end positions and +// style strings), which is used to highlight the tokens on the +// line. +function highlightLine(cm, line, state, forceToEnd) { + // A styles array always starts with a number identifying the + // mode/overlays that it is based on (for easy invalidation). + var st = [cm.state.modeGen], lineClasses = {} + // Compute the base array of styles + runMode(cm, line.text, cm.doc.mode, state, function (end, style) { return st.push(end, style); }, + lineClasses, forceToEnd) + + // Run overlays, adjust style array. + var loop = function ( o ) { + var overlay = cm.state.overlays[o], i = 1, at = 0 + runMode(cm, line.text, overlay.mode, true, function (end, style) { + var start = i + // Ensure there's a token end at the current position, and that i points at it + while (at < end) { + var i_end = st[i] + if (i_end > end) + { st.splice(i, 1, end, st[i+1], i_end) } + i += 2 + at = Math.min(end, i_end) + } + if (!style) { return } + if (overlay.opaque) { + st.splice(start, i - start, end, "overlay " + style) + i = start + 2 + } else { + for (; start < i; start += 2) { + var cur = st[start+1] + st[start+1] = (cur ? cur + " " : "") + "overlay " + style } } - intact = intact2; - } - return intact; - } + }, lineClasses) + }; - function getDimensions(cm) { - var d = cm.display, left = {}, width = {}; - for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) { - left[cm.options.gutters[i]] = n.offsetLeft; - width[cm.options.gutters[i]] = n.offsetWidth; + for (var o = 0; o < cm.state.overlays.length; ++o) loop( o ); + + return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null} +} + +function getLineStyles(cm, line, updateFrontier) { + if (!line.styles || line.styles[0] != cm.state.modeGen) { + var state = getStateBefore(cm, lineNo(line)) + var result = highlightLine(cm, line, line.text.length > cm.options.maxHighlightLength ? copyState(cm.doc.mode, state) : state) + line.stateAfter = state + line.styles = result.styles + if (result.classes) { line.styleClasses = result.classes } + else if (line.styleClasses) { line.styleClasses = null } + if (updateFrontier === cm.doc.frontier) { cm.doc.frontier++ } + } + return line.styles +} + +function getStateBefore(cm, n, precise) { + var doc = cm.doc, display = cm.display + if (!doc.mode.startState) { return true } + var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter + if (!state) { state = startState(doc.mode) } + else { state = copyState(doc.mode, state) } + doc.iter(pos, n, function (line) { + processLine(cm, line.text, state) + var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo + line.stateAfter = save ? copyState(doc.mode, state) : null + ++pos + }) + if (precise) { doc.frontier = pos } + return state +} + +// Lightweight form of highlight -- proceed over this line and +// update state, but don't save a style array. Used for lines that +// aren't currently visible. +function processLine(cm, text, state, startAt) { + var mode = cm.doc.mode + var stream = new StringStream(text, cm.options.tabSize) + stream.start = stream.pos = startAt || 0 + if (text == "") { callBlankLine(mode, state) } + while (!stream.eol()) { + readToken(mode, stream, state) + stream.start = stream.pos + } +} + +function callBlankLine(mode, state) { + if (mode.blankLine) { return mode.blankLine(state) } + if (!mode.innerMode) { return } + var inner = innerMode(mode, state) + if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) } +} + +function readToken(mode, stream, state, inner) { + for (var i = 0; i < 10; i++) { + if (inner) { inner[0] = innerMode(mode, state).mode } + var style = mode.token(stream, state) + if (stream.pos > stream.start) { return style } + } + throw new Error("Mode " + mode.name + " failed to advance stream.") +} + +// Utility for getTokenAt and getLineTokens +function takeToken(cm, pos, precise, asArray) { + var getObj = function (copy) { return ({ + start: stream.start, end: stream.pos, + string: stream.current(), + type: style || null, + state: copy ? copyState(doc.mode, state) : state + }); } + + var doc = cm.doc, mode = doc.mode, style + pos = clipPos(doc, pos) + var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise) + var stream = new StringStream(line.text, cm.options.tabSize), tokens + if (asArray) { tokens = [] } + while ((asArray || stream.pos < pos.ch) && !stream.eol()) { + stream.start = stream.pos + style = readToken(mode, stream, state) + if (asArray) { tokens.push(getObj(true)) } + } + return asArray ? tokens : getObj() +} + +function extractLineClasses(type, output) { + if (type) { for (;;) { + var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/) + if (!lineClass) { break } + type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length) + var prop = lineClass[1] ? "bgClass" : "textClass" + if (output[prop] == null) + { output[prop] = lineClass[2] } + else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop])) + { output[prop] += " " + lineClass[2] } + } } + return type +} + +// Run the given mode's parser over a line, calling f for each token. +function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) { + var flattenSpans = mode.flattenSpans + if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans } + var curStart = 0, curStyle = null + var stream = new StringStream(text, cm.options.tabSize), style + var inner = cm.options.addModeClass && [null] + if (text == "") { extractLineClasses(callBlankLine(mode, state), lineClasses) } + while (!stream.eol()) { + if (stream.pos > cm.options.maxHighlightLength) { + flattenSpans = false + if (forceToEnd) { processLine(cm, text, state, stream.pos) } + stream.pos = text.length + style = null + } else { + style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses) } - return {fixedPos: compensateForHScroll(d), - gutterTotalWidth: d.gutters.offsetWidth, - gutterLeft: left, - gutterWidth: width, - wrapperWidth: d.wrapper.clientWidth}; - } - - function patchDisplay(cm, from, to, intact, updateNumbersFrom) { - var dims = getDimensions(cm); - var display = cm.display, lineNumbers = cm.options.lineNumbers; - if (!intact.length && (!webkit || !cm.display.currentWheelTarget)) - removeChildren(display.lineDiv); - var container = display.lineDiv, cur = container.firstChild; - - function rm(node) { - var next = node.nextSibling; - if (webkit && mac && cm.display.currentWheelTarget == node) { - node.style.display = "none"; - node.lineObj = null; - } else { - node.parentNode.removeChild(node); + if (inner) { + var mName = inner[0].name + if (mName) { style = "m-" + (style ? mName + " " + style : mName) } + } + if (!flattenSpans || curStyle != style) { + while (curStart < stream.start) { + curStart = Math.min(stream.start, curStart + 5000) + f(curStart, curStyle) } - return next; - } - - var nextIntact = intact.shift(), lineN = from; - cm.doc.iter(from, to, function(line) { - if (nextIntact && nextIntact.to == lineN) nextIntact = intact.shift(); - if (lineIsHidden(cm.doc, line)) { - if (line.height != 0) updateLineHeight(line, 0); - if (line.widgets && cur && cur.previousSibling) for (var i = 0; i < line.widgets.length; ++i) { - var w = line.widgets[i]; - if (w.showIfHidden) { - var prev = cur.previousSibling; - if (/pre/i.test(prev.nodeName)) { - var wrap = elt("div", null, null, "position: relative"); - prev.parentNode.replaceChild(wrap, prev); - wrap.appendChild(prev); - prev = wrap; - } - var wnode = prev.appendChild(elt("div", [w.node], "CodeMirror-linewidget")); - if (!w.handleMouseEvents) wnode.ignoreEvents = true; - positionLineWidget(w, wnode, prev, dims); - } - } - } else if (nextIntact && nextIntact.from <= lineN && nextIntact.to > lineN) { - // This line is intact. Skip to the actual node. Update its - // line number if needed. - while (cur.lineObj != line) cur = rm(cur); - if (lineNumbers && updateNumbersFrom <= lineN && cur.lineNumber) - setTextContent(cur.lineNumber, lineNumberFor(cm.options, lineN)); - cur = cur.nextSibling; + curStyle = style + } + stream.start = stream.pos + } + while (curStart < stream.pos) { + // Webkit seems to refuse to render text nodes longer than 57444 + // characters, and returns inaccurate measurements in nodes + // starting around 5000 chars. + var pos = Math.min(stream.pos, curStart + 5000) + f(pos, curStyle) + curStart = pos + } +} + +// Finds the line to start with when starting a parse. Tries to +// find a line with a stateAfter, so that it can start with a +// valid state. If that fails, it returns the line with the +// smallest indentation, which tends to need the least context to +// parse correctly. +function findStartLine(cm, n, precise) { + var minindent, minline, doc = cm.doc + var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100) + for (var search = n; search > lim; --search) { + if (search <= doc.first) { return doc.first } + var line = getLine(doc, search - 1) + if (line.stateAfter && (!precise || search <= doc.frontier)) { return search } + var indented = countColumn(line.text, null, cm.options.tabSize) + if (minline == null || minindent > indented) { + minline = search - 1 + minindent = indented + } + } + return minline +} + +// LINE DATA STRUCTURE + +// Line objects. These hold state related to a line, including +// highlighting info (the styles array). +function Line(text, markedSpans, estimateHeight) { + this.text = text + attachMarkedSpans(this, markedSpans) + this.height = estimateHeight ? estimateHeight(this) : 1 +} +eventMixin(Line) +Line.prototype.lineNo = function() { return lineNo(this) } + +// Change the content (text, markers) of a line. Automatically +// invalidates cached information and tries to re-estimate the +// line's height. +function updateLine(line, text, markedSpans, estimateHeight) { + line.text = text + if (line.stateAfter) { line.stateAfter = null } + if (line.styles) { line.styles = null } + if (line.order != null) { line.order = null } + detachMarkedSpans(line) + attachMarkedSpans(line, markedSpans) + var estHeight = estimateHeight ? estimateHeight(line) : 1 + if (estHeight != line.height) { updateLineHeight(line, estHeight) } +} + +// Detach a line from the document tree and its markers. +function cleanUpLine(line) { + line.parent = null + detachMarkedSpans(line) +} + +// Convert a style as returned by a mode (either null, or a string +// containing one or more styles) to a CSS style. This is cached, +// and also looks for line-wide styles. +var styleToClassCache = {}; +var styleToClassCacheWithMode = {}; +function interpretTokenStyle(style, options) { + if (!style || /^\s*$/.test(style)) { return null } + var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache + return cache[style] || + (cache[style] = style.replace(/\S+/g, "cm-$&")) +} + +// Render the DOM representation of the text of a line. Also builds +// up a 'line map', which points at the DOM nodes that represent +// specific stretches of text, and is used by the measuring code. +// The returned object contains the DOM node, this map, and +// information about line-wide styles that were set by the mode. +function buildLineContent(cm, lineView) { + // The padding-right forces the element to have a 'border', which + // is needed on Webkit to be able to get line-level bounding + // rectangles for it (in measureChar). + var content = elt("span", null, null, webkit ? "padding-right: .1px" : null) + var builder = {pre: elt("pre", [content], "CodeMirror-line"), content: content, + col: 0, pos: 0, cm: cm, + trailingSpace: false, + splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")} + lineView.measure = {} + + // Iterate over the logical lines that make up this visual line. + for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) { + var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0) + builder.pos = 0 + builder.addToken = buildToken + // Optionally wire in some hacks into the token-rendering + // algorithm, to deal with browser quirks. + if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line))) + { builder.addToken = buildTokenBadBidi(builder.addToken, order) } + builder.map = [] + var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line) + insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate)) + if (line.styleClasses) { + if (line.styleClasses.bgClass) + { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "") } + if (line.styleClasses.textClass) + { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "") } + } + + // Ensure at least a single node is present, for measuring. + if (builder.map.length == 0) + { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))) } + + // Store the map and a cache object for the current logical line + if (i == 0) { + lineView.measure.map = builder.map + lineView.measure.cache = {} + } else { + ;(lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map) + ;(lineView.measure.caches || (lineView.measure.caches = [])).push({}) + } + } + + // See issue #2901 + if (webkit) { + var last = builder.content.lastChild + if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab"))) + { builder.content.className = "cm-tab-wrap-hack" } + } + + signal(cm, "renderLine", cm, lineView.line, builder.pre) + if (builder.pre.className) + { builder.textClass = joinClasses(builder.pre.className, builder.textClass || "") } + + return builder +} + +function defaultSpecialCharPlaceholder(ch) { + var token = elt("span", "\u2022", "cm-invalidchar") + token.title = "\\u" + ch.charCodeAt(0).toString(16) + token.setAttribute("aria-label", token.title) + return token +} + +// Build up the DOM representation for a single token, and add it to +// the line map. Takes care to render special characters separately. +function buildToken(builder, text, style, startStyle, endStyle, title, css) { + if (!text) { return } + var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text + var special = builder.cm.state.specialChars, mustWrap = false + var content + if (!special.test(text)) { + builder.col += text.length + content = document.createTextNode(displayText) + builder.map.push(builder.pos, builder.pos + text.length, content) + if (ie && ie_version < 9) { mustWrap = true } + builder.pos += text.length + } else { + content = document.createDocumentFragment() + var pos = 0 + while (true) { + special.lastIndex = pos + var m = special.exec(text) + var skipped = m ? m.index - pos : text.length - pos + if (skipped) { + var txt = document.createTextNode(displayText.slice(pos, pos + skipped)) + if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])) } + else { content.appendChild(txt) } + builder.map.push(builder.pos, builder.pos + skipped, txt) + builder.col += skipped + builder.pos += skipped + } + if (!m) { break } + pos += skipped + 1 + var txt$1 = (void 0) + if (m[0] == "\t") { + var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize + txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")) + txt$1.setAttribute("role", "presentation") + txt$1.setAttribute("cm-text", "\t") + builder.col += tabWidth + } else if (m[0] == "\r" || m[0] == "\n") { + txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar")) + txt$1.setAttribute("cm-text", m[0]) + builder.col += 1 } else { - // For lines with widgets, make an attempt to find and reuse - // the existing element, so that widgets aren't needlessly - // removed and re-inserted into the dom - if (line.widgets) for (var j = 0, search = cur, reuse; search && j < 20; ++j, search = search.nextSibling) - if (search.lineObj == line && /div/i.test(search.nodeName)) { reuse = search; break; } - // This line needs to be generated. - var lineNode = buildLineElement(cm, line, lineN, dims, reuse); - if (lineNode != reuse) { - container.insertBefore(lineNode, cur); - } else { - while (cur != reuse) cur = rm(cur); - cur = cur.nextSibling; - } - - lineNode.lineObj = line; + txt$1 = builder.cm.options.specialCharPlaceholder(m[0]) + txt$1.setAttribute("cm-text", m[0]) + if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])) } + else { content.appendChild(txt$1) } + builder.col += 1 } - ++lineN; - }); - while (cur) cur = rm(cur); - } - - function buildLineElement(cm, line, lineNo, dims, reuse) { - var built = buildLineContent(cm, line), lineElement = built.pre; - var markers = line.gutterMarkers, display = cm.display, wrap; - - var bgClass = built.bgClass ? built.bgClass + " " + (line.bgClass || "") : line.bgClass; - if (!cm.options.lineNumbers && !markers && !bgClass && !line.wrapClass && !line.widgets) - return lineElement; - - // Lines with gutter elements, widgets or a background class need - // to be wrapped again, and have the extra elements added to the - // wrapper div - - if (reuse) { - reuse.alignable = null; - var isOk = true, widgetsSeen = 0, insertBefore = null; - for (var n = reuse.firstChild, next; n; n = next) { - next = n.nextSibling; - if (!/\bCodeMirror-linewidget\b/.test(n.className)) { - reuse.removeChild(n); - } else { - for (var i = 0; i < line.widgets.length; ++i) { - var widget = line.widgets[i]; - if (widget.node == n.firstChild) { - if (!widget.above && !insertBefore) insertBefore = n; - positionLineWidget(widget, n, reuse, dims); - ++widgetsSeen; - break; - } + builder.map.push(builder.pos, builder.pos + 1, txt$1) + builder.pos++ + } + } + builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32 + if (style || startStyle || endStyle || mustWrap || css) { + var fullStyle = style || "" + if (startStyle) { fullStyle += startStyle } + if (endStyle) { fullStyle += endStyle } + var token = elt("span", [content], fullStyle, css) + if (title) { token.title = title } + return builder.content.appendChild(token) + } + builder.content.appendChild(content) +} + +function splitSpaces(text, trailingBefore) { + if (text.length > 1 && !/ /.test(text)) { return text } + var spaceBefore = trailingBefore, result = "" + for (var i = 0; i < text.length; i++) { + var ch = text.charAt(i) + if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32)) + { ch = "\u00a0" } + result += ch + spaceBefore = ch == " " + } + return result +} + +// Work around nonsense dimensions being reported for stretches of +// right-to-left text. +function buildTokenBadBidi(inner, order) { + return function (builder, text, style, startStyle, endStyle, title, css) { + style = style ? style + " cm-force-border" : "cm-force-border" + var start = builder.pos, end = start + text.length + for (;;) { + // Find the part that overlaps with the start of this text + var part = (void 0) + for (var i = 0; i < order.length; i++) { + part = order[i] + if (part.to > start && part.from <= start) { break } + } + if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, title, css) } + inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css) + startStyle = null + text = text.slice(part.to - start) + start = part.to + } + } +} + +function buildCollapsedSpan(builder, size, marker, ignoreWidget) { + var widget = !ignoreWidget && marker.widgetNode + if (widget) { builder.map.push(builder.pos, builder.pos + size, widget) } + if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) { + if (!widget) + { widget = builder.content.appendChild(document.createElement("span")) } + widget.setAttribute("cm-marker", marker.id) + } + if (widget) { + builder.cm.display.input.setUneditable(widget) + builder.content.appendChild(widget) + } + builder.pos += size + builder.trailingSpace = false +} + +// Outputs a number of spans to make up a line, taking highlighting +// and marked text into account. +function insertLineContent(line, builder, styles) { + var spans = line.markedSpans, allText = line.text, at = 0 + if (!spans) { + for (var i$1 = 1; i$1 < styles.length; i$1+=2) + { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)) } + return + } + + var len = allText.length, pos = 0, i = 1, text = "", style, css + var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed + for (;;) { + if (nextChange == pos) { // Update current marker set + spanStyle = spanEndStyle = spanStartStyle = title = css = "" + collapsed = null; nextChange = Infinity + var foundBookmarks = [], endStyles = (void 0) + for (var j = 0; j < spans.length; ++j) { + var sp = spans[j], m = sp.marker + if (m.type == "bookmark" && sp.from == pos && m.widgetNode) { + foundBookmarks.push(m) + } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) { + if (sp.to != null && sp.to != pos && nextChange > sp.to) { + nextChange = sp.to + spanEndStyle = "" } - if (i == line.widgets.length) { isOk = false; break; } + if (m.className) { spanStyle += " " + m.className } + if (m.css) { css = (css ? css + ";" : "") + m.css } + if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle } + if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to) } + if (m.title && !title) { title = m.title } + if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0)) + { collapsed = sp } + } else if (sp.from > pos && nextChange > sp.from) { + nextChange = sp.from } } - reuse.insertBefore(lineElement, insertBefore); - if (isOk && widgetsSeen == line.widgets.length) { - wrap = reuse; - reuse.className = line.wrapClass || ""; + if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2) + { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1] } } } + + if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2) + { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]) } } + if (collapsed && (collapsed.from || 0) == pos) { + buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos, + collapsed.marker, collapsed.from == null) + if (collapsed.to == null) { return } + if (collapsed.to == pos) { collapsed = false } } } - if (!wrap) { - wrap = elt("div", null, line.wrapClass, "position: relative"); - wrap.appendChild(lineElement); - } - // Kludge to make sure the styled element lies behind the selection (by z-index) - if (bgClass) - wrap.insertBefore(elt("div", null, bgClass + " CodeMirror-linebackground"), wrap.firstChild); - if (cm.options.lineNumbers || markers) { - var gutterWrap = wrap.insertBefore(elt("div", null, null, "position: absolute; left: " + - (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"), - wrap.firstChild); - if (cm.options.fixedGutter) (wrap.alignable || (wrap.alignable = [])).push(gutterWrap); - if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) - wrap.lineNumber = gutterWrap.appendChild( - elt("div", lineNumberFor(cm.options, lineNo), - "CodeMirror-linenumber CodeMirror-gutter-elt", - "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: " - + display.lineNumInnerWidth + "px")); - if (markers) - for (var k = 0; k < cm.options.gutters.length; ++k) { - var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id]; - if (found) - gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " + - dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px")); + if (pos >= len) { break } + + var upto = Math.min(len, nextChange) + while (true) { + if (text) { + var end = pos + text.length + if (!collapsed) { + var tokenText = end > upto ? text.slice(0, upto - pos) : text + builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, + spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css) } - } - if (ie_lt8) wrap.style.zIndex = 2; - if (line.widgets && wrap != reuse) for (var i = 0, ws = line.widgets; i < ws.length; ++i) { - var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget"); - if (!widget.handleMouseEvents) node.ignoreEvents = true; - positionLineWidget(widget, node, wrap, dims); - if (widget.above) - wrap.insertBefore(node, cm.options.lineNumbers && line.height != 0 ? gutterWrap : lineElement); - else - wrap.appendChild(node); - signalLater(widget, "redraw"); - } - return wrap; - } + if (end >= upto) {text = text.slice(upto - pos); pos = upto; break} + pos = end + spanStartStyle = "" + } + text = allText.slice(at, at = styles[i++]) + style = interpretTokenStyle(styles[i++], builder.cm.options) + } + } +} + + +// These objects are used to represent the visible (currently drawn) +// part of the document. A LineView may correspond to multiple +// logical lines, if those are connected by collapsed ranges. +function LineView(doc, line, lineN) { + // The starting line + this.line = line + // Continuing lines, if any + this.rest = visualLineContinued(line) + // Number of logical lines in this visual line + this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1 + this.node = this.text = null + this.hidden = lineIsHidden(doc, line) +} + +// Create a range of LineView objects for the given lines. +function buildViewArray(cm, from, to) { + var array = [], nextPos + for (var pos = from; pos < to; pos = nextPos) { + var view = new LineView(cm.doc, getLine(cm.doc, pos), pos) + nextPos = pos + view.size + array.push(view) + } + return array +} + +var operationGroup = null + +function pushOperation(op) { + if (operationGroup) { + operationGroup.ops.push(op) + } else { + op.ownsGroup = operationGroup = { + ops: [op], + delayedCallbacks: [] + } + } +} + +function fireCallbacksForOps(group) { + // Calls delayed callbacks and cursorActivity handlers until no + // new ones appear + var callbacks = group.delayedCallbacks, i = 0 + do { + for (; i < callbacks.length; i++) + { callbacks[i].call(null) } + for (var j = 0; j < group.ops.length; j++) { + var op = group.ops[j] + if (op.cursorActivityHandlers) + { while (op.cursorActivityCalled < op.cursorActivityHandlers.length) + { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm) } } + } + } while (i < callbacks.length) +} + +function finishOperation(op, endCb) { + var group = op.ownsGroup + if (!group) { return } + + try { fireCallbacksForOps(group) } + finally { + operationGroup = null + endCb(group) + } +} + +var orphanDelayedCallbacks = null + +// Often, we want to signal events at a point where we are in the +// middle of some work, but don't want the handler to start calling +// other methods on the editor, which might be in an inconsistent +// state or simply not expect any other events to happen. +// signalLater looks whether there are any handlers, and schedules +// them to be executed when the last operation ends, or, if no +// operation is active, when a timeout fires. +function signalLater(emitter, type /*, values...*/) { + var arr = getHandlers(emitter, type) + if (!arr.length) { return } + var args = Array.prototype.slice.call(arguments, 2), list + if (operationGroup) { + list = operationGroup.delayedCallbacks + } else if (orphanDelayedCallbacks) { + list = orphanDelayedCallbacks + } else { + list = orphanDelayedCallbacks = [] + setTimeout(fireOrphanDelayed, 0) + } + var loop = function ( i ) { + list.push(function () { return arr[i].apply(null, args); }) + }; - function positionLineWidget(widget, node, wrap, dims) { - if (widget.noHScroll) { - (wrap.alignable || (wrap.alignable = [])).push(node); - var width = dims.wrapperWidth; - node.style.left = dims.fixedPos + "px"; - if (!widget.coverGutter) { - width -= dims.gutterTotalWidth; - node.style.paddingLeft = dims.gutterTotalWidth + "px"; + for (var i = 0; i < arr.length; ++i) + loop( i ); +} + +function fireOrphanDelayed() { + var delayed = orphanDelayedCallbacks + orphanDelayedCallbacks = null + for (var i = 0; i < delayed.length; ++i) { delayed[i]() } +} + +// When an aspect of a line changes, a string is added to +// lineView.changes. This updates the relevant part of the line's +// DOM structure. +function updateLineForChanges(cm, lineView, lineN, dims) { + for (var j = 0; j < lineView.changes.length; j++) { + var type = lineView.changes[j] + if (type == "text") { updateLineText(cm, lineView) } + else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims) } + else if (type == "class") { updateLineClasses(lineView) } + else if (type == "widget") { updateLineWidgets(cm, lineView, dims) } + } + lineView.changes = null +} + +// Lines with gutter elements, widgets or a background class need to +// be wrapped, and have the extra elements added to the wrapper div +function ensureLineWrapped(lineView) { + if (lineView.node == lineView.text) { + lineView.node = elt("div", null, null, "position: relative") + if (lineView.text.parentNode) + { lineView.text.parentNode.replaceChild(lineView.node, lineView.text) } + lineView.node.appendChild(lineView.text) + if (ie && ie_version < 8) { lineView.node.style.zIndex = 2 } + } + return lineView.node +} + +function updateLineBackground(lineView) { + var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass + if (cls) { cls += " CodeMirror-linebackground" } + if (lineView.background) { + if (cls) { lineView.background.className = cls } + else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null } + } else if (cls) { + var wrap = ensureLineWrapped(lineView) + lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild) + } +} + +// Wrapper around buildLineContent which will reuse the structure +// in display.externalMeasured when possible. +function getLineContent(cm, lineView) { + var ext = cm.display.externalMeasured + if (ext && ext.line == lineView.line) { + cm.display.externalMeasured = null + lineView.measure = ext.measure + return ext.built + } + return buildLineContent(cm, lineView) +} + +// Redraw the line's text. Interacts with the background and text +// classes because the mode may output tokens that influence these +// classes. +function updateLineText(cm, lineView) { + var cls = lineView.text.className + var built = getLineContent(cm, lineView) + if (lineView.text == lineView.node) { lineView.node = built.pre } + lineView.text.parentNode.replaceChild(built.pre, lineView.text) + lineView.text = built.pre + if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) { + lineView.bgClass = built.bgClass + lineView.textClass = built.textClass + updateLineClasses(lineView) + } else if (cls) { + lineView.text.className = cls + } +} + +function updateLineClasses(lineView) { + updateLineBackground(lineView) + if (lineView.line.wrapClass) + { ensureLineWrapped(lineView).className = lineView.line.wrapClass } + else if (lineView.node != lineView.text) + { lineView.node.className = "" } + var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass + lineView.text.className = textClass || "" +} + +function updateLineGutter(cm, lineView, lineN, dims) { + if (lineView.gutter) { + lineView.node.removeChild(lineView.gutter) + lineView.gutter = null + } + if (lineView.gutterBackground) { + lineView.node.removeChild(lineView.gutterBackground) + lineView.gutterBackground = null + } + if (lineView.line.gutterClass) { + var wrap = ensureLineWrapped(lineView) + lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass, + ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px")) + wrap.insertBefore(lineView.gutterBackground, lineView.text) + } + var markers = lineView.line.gutterMarkers + if (cm.options.lineNumbers || markers) { + var wrap$1 = ensureLineWrapped(lineView) + var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px")) + cm.display.input.setUneditable(gutterWrap) + wrap$1.insertBefore(gutterWrap, lineView.text) + if (lineView.line.gutterClass) + { gutterWrap.className += " " + lineView.line.gutterClass } + if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) + { lineView.lineNumber = gutterWrap.appendChild( + elt("div", lineNumberFor(cm.options, lineN), + "CodeMirror-linenumber CodeMirror-gutter-elt", + ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))) } + if (markers) { for (var k = 0; k < cm.options.gutters.length; ++k) { + var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id] + if (found) + { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", + ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))) } + } } + } +} + +function updateLineWidgets(cm, lineView, dims) { + if (lineView.alignable) { lineView.alignable = null } + for (var node = lineView.node.firstChild, next = (void 0); node; node = next) { + next = node.nextSibling + if (node.className == "CodeMirror-linewidget") + { lineView.node.removeChild(node) } + } + insertLineWidgets(cm, lineView, dims) +} + +// Build a line's DOM representation from scratch +function buildLineElement(cm, lineView, lineN, dims) { + var built = getLineContent(cm, lineView) + lineView.text = lineView.node = built.pre + if (built.bgClass) { lineView.bgClass = built.bgClass } + if (built.textClass) { lineView.textClass = built.textClass } + + updateLineClasses(lineView) + updateLineGutter(cm, lineView, lineN, dims) + insertLineWidgets(cm, lineView, dims) + return lineView.node +} + +// A lineView may contain multiple logical lines (when merged by +// collapsed spans). The widgets for all of them need to be drawn. +function insertLineWidgets(cm, lineView, dims) { + insertLineWidgetsFor(cm, lineView.line, lineView, dims, true) + if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++) + { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false) } } +} + +function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) { + if (!line.widgets) { return } + var wrap = ensureLineWrapped(lineView) + for (var i = 0, ws = line.widgets; i < ws.length; ++i) { + var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget") + if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true") } + positionLineWidget(widget, node, lineView, dims) + cm.display.input.setUneditable(node) + if (allowAbove && widget.above) + { wrap.insertBefore(node, lineView.gutter || lineView.text) } + else + { wrap.appendChild(node) } + signalLater(widget, "redraw") + } +} + +function positionLineWidget(widget, node, lineView, dims) { + if (widget.noHScroll) { + ;(lineView.alignable || (lineView.alignable = [])).push(node) + var width = dims.wrapperWidth + node.style.left = dims.fixedPos + "px" + if (!widget.coverGutter) { + width -= dims.gutterTotalWidth + node.style.paddingLeft = dims.gutterTotalWidth + "px" + } + node.style.width = width + "px" + } + if (widget.coverGutter) { + node.style.zIndex = 5 + node.style.position = "relative" + if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px" } + } +} + +function widgetHeight(widget) { + if (widget.height != null) { return widget.height } + var cm = widget.doc.cm + if (!cm) { return 0 } + if (!contains(document.body, widget.node)) { + var parentStyle = "position: relative;" + if (widget.coverGutter) + { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;" } + if (widget.noHScroll) + { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;" } + removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle)) + } + return widget.height = widget.node.parentNode.offsetHeight +} + +// Return true when the given mouse event happened in a widget +function eventInWidget(display, e) { + for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { + if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") || + (n.parentNode == display.sizer && n != display.mover)) + { return true } + } +} + +// POSITION MEASUREMENT + +function paddingTop(display) {return display.lineSpace.offsetTop} +function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight} +function paddingH(display) { + if (display.cachedPaddingH) { return display.cachedPaddingH } + var e = removeChildrenAndAdd(display.measure, elt("pre", "x")) + var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle + var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)} + if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data } + return data +} + +function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth } +function displayWidth(cm) { + return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth +} +function displayHeight(cm) { + return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight +} + +// Ensure the lineView.wrapping.heights array is populated. This is +// an array of bottom offsets for the lines that make up a drawn +// line. When lineWrapping is on, there might be more than one +// height. +function ensureLineHeights(cm, lineView, rect) { + var wrapping = cm.options.lineWrapping + var curWidth = wrapping && displayWidth(cm) + if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) { + var heights = lineView.measure.heights = [] + if (wrapping) { + lineView.measure.width = curWidth + var rects = lineView.text.firstChild.getClientRects() + for (var i = 0; i < rects.length - 1; i++) { + var cur = rects[i], next = rects[i + 1] + if (Math.abs(cur.bottom - next.bottom) > 2) + { heights.push((cur.bottom + next.top) / 2 - rect.top) } } - node.style.width = width + "px"; - } - if (widget.coverGutter) { - node.style.zIndex = 5; - node.style.position = "relative"; - if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px"; } + heights.push(rect.bottom - rect.top) + } +} + +// Find a line map (mapping character offsets to text nodes) and a +// measurement cache for the given line number. (A line view might +// contain multiple lines when collapsed ranges are present.) +function mapFromLineView(lineView, line, lineN) { + if (lineView.line == line) + { return {map: lineView.measure.map, cache: lineView.measure.cache} } + for (var i = 0; i < lineView.rest.length; i++) + { if (lineView.rest[i] == line) + { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } } + for (var i$1 = 0; i$1 < lineView.rest.length; i$1++) + { if (lineNo(lineView.rest[i$1]) > lineN) + { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } } +} + +// Render a line into the hidden node display.externalMeasured. Used +// when measurement is needed for a line that's not in the viewport. +function updateExternalMeasurement(cm, line) { + line = visualLine(line) + var lineN = lineNo(line) + var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN) + view.lineN = lineN + var built = view.built = buildLineContent(cm, view) + view.text = built.pre + removeChildrenAndAdd(cm.display.lineMeasure, built.pre) + return view +} + +// Get a {top, bottom, left, right} box (in line-local coordinates) +// for a given character. +function measureChar(cm, line, ch, bias) { + return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias) +} + +// Find a line view that corresponds to the given line number. +function findViewForLine(cm, lineN) { + if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) + { return cm.display.view[findViewIndex(cm, lineN)] } + var ext = cm.display.externalMeasured + if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) + { return ext } +} + +// Measurement can be split in two steps, the set-up work that +// applies to the whole line, and the measurement of the actual +// character. Functions like coordsChar, that need to do a lot of +// measurements in a row, can thus ensure that the set-up work is +// only done once. +function prepareMeasureForLine(cm, line) { + var lineN = lineNo(line) + var view = findViewForLine(cm, lineN) + if (view && !view.text) { + view = null + } else if (view && view.changes) { + updateLineForChanges(cm, view, lineN, getDimensions(cm)) + cm.curOp.forceUpdate = true + } + if (!view) + { view = updateExternalMeasurement(cm, line) } + + var info = mapFromLineView(view, line, lineN) + return { + line: line, view: view, rect: null, + map: info.map, cache: info.cache, before: info.before, + hasHeights: false + } +} + +// Given a prepared measurement object, measures the position of an +// actual character (or fetches it from the cache). +function measureCharPrepared(cm, prepared, ch, bias, varHeight) { + if (prepared.before) { ch = -1 } + var key = ch + (bias || ""), found + if (prepared.cache.hasOwnProperty(key)) { + found = prepared.cache[key] + } else { + if (!prepared.rect) + { prepared.rect = prepared.view.text.getBoundingClientRect() } + if (!prepared.hasHeights) { + ensureLineHeights(cm, prepared.view, prepared.rect) + prepared.hasHeights = true + } + found = measureCharInner(cm, prepared, ch, bias) + if (!found.bogus) { prepared.cache[key] = found } + } + return {left: found.left, right: found.right, + top: varHeight ? found.rtop : found.top, + bottom: varHeight ? found.rbottom : found.bottom} +} + +var nullRect = {left: 0, right: 0, top: 0, bottom: 0} + +function nodeAndOffsetInLineMap(map, ch, bias) { + var node, start, end, collapse, mStart, mEnd + // First, search the line map for the text node corresponding to, + // or closest to, the target character. + for (var i = 0; i < map.length; i += 3) { + mStart = map[i] + mEnd = map[i + 1] + if (ch < mStart) { + start = 0; end = 1 + collapse = "left" + } else if (ch < mEnd) { + start = ch - mStart + end = start + 1 + } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) { + end = mEnd - mStart + start = end - 1 + if (ch >= mEnd) { collapse = "right" } + } + if (start != null) { + node = map[i + 2] + if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right")) + { collapse = bias } + if (bias == "left" && start == 0) + { while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) { + node = map[(i -= 3) + 2] + collapse = "left" + } } + if (bias == "right" && start == mEnd - mStart) + { while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) { + node = map[(i += 3) + 2] + collapse = "right" + } } + break + } + } + return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd} +} + +function getUsefulRect(rects, bias) { + var rect = nullRect + if (bias == "left") { for (var i = 0; i < rects.length; i++) { + if ((rect = rects[i]).left != rect.right) { break } + } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) { + if ((rect = rects[i$1]).left != rect.right) { break } + } } + return rect +} + +function measureCharInner(cm, prepared, ch, bias) { + var place = nodeAndOffsetInLineMap(prepared.map, ch, bias) + var node = place.node, start = place.start, end = place.end, collapse = place.collapse + + var rect + if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates. + for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned + while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start } + while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end } + if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) + { rect = node.parentNode.getBoundingClientRect() } + else + { rect = getUsefulRect(range(node, start, end).getClientRects(), bias) } + if (rect.left || rect.right || start == 0) { break } + end = start + start = start - 1 + collapse = "right" + } + if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect) } + } else { // If it is a widget, simply get the box for the whole widget. + if (start > 0) { collapse = bias = "right" } + var rects + if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) + { rect = rects[bias == "right" ? rects.length - 1 : 0] } + else + { rect = node.getBoundingClientRect() } } - - // SELECTION / CURSOR - - function updateSelection(cm) { - var display = cm.display; - var collapsed = posEq(cm.doc.sel.from, cm.doc.sel.to); - if (collapsed || cm.options.showCursorWhenSelecting) - updateSelectionCursor(cm); + if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) { + var rSpan = node.parentNode.getClientRects()[0] + if (rSpan) + { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom} } else - display.cursor.style.display = display.otherCursor.style.display = "none"; - if (!collapsed) - updateSelectionRange(cm); + { rect = nullRect } + } + + var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top + var mid = (rtop + rbot) / 2 + var heights = prepared.view.measure.heights + var i = 0 + for (; i < heights.length - 1; i++) + { if (mid < heights[i]) { break } } + var top = i ? heights[i - 1] : 0, bot = heights[i] + var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left, + right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left, + top: top, bottom: bot} + if (!rect.left && !rect.right) { result.bogus = true } + if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot } + + return result +} + +// Work around problem with bounding client rects on ranges being +// returned incorrectly when zoomed on IE10 and below. +function maybeUpdateRectForZooming(measure, rect) { + if (!window.screen || screen.logicalXDPI == null || + screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure)) + { return rect } + var scaleX = screen.logicalXDPI / screen.deviceXDPI + var scaleY = screen.logicalYDPI / screen.deviceYDPI + return {left: rect.left * scaleX, right: rect.right * scaleX, + top: rect.top * scaleY, bottom: rect.bottom * scaleY} +} + +function clearLineMeasurementCacheFor(lineView) { + if (lineView.measure) { + lineView.measure.cache = {} + lineView.measure.heights = null + if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++) + { lineView.measure.caches[i] = {} } } + } +} + +function clearLineMeasurementCache(cm) { + cm.display.externalMeasure = null + removeChildren(cm.display.lineMeasure) + for (var i = 0; i < cm.display.view.length; i++) + { clearLineMeasurementCacheFor(cm.display.view[i]) } +} + +function clearCaches(cm) { + clearLineMeasurementCache(cm) + cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null + if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true } + cm.display.lineNumChars = null +} + +function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft } +function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop } + +// Converts a {top, bottom, left, right} box from line-local +// coordinates into another coordinate system. Context may be one of +// "line", "div" (display.lineDiv), "local"./null (editor), "window", +// or "page". +function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) { + if (!includeWidgets && lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above) { + var size = widgetHeight(lineObj.widgets[i]) + rect.top += size; rect.bottom += size + } } } + if (context == "line") { return rect } + if (!context) { context = "local" } + var yOff = heightAtLine(lineObj) + if (context == "local") { yOff += paddingTop(cm.display) } + else { yOff -= cm.display.viewOffset } + if (context == "page" || context == "window") { + var lOff = cm.display.lineSpace.getBoundingClientRect() + yOff += lOff.top + (context == "window" ? 0 : pageScrollY()) + var xOff = lOff.left + (context == "window" ? 0 : pageScrollX()) + rect.left += xOff; rect.right += xOff + } + rect.top += yOff; rect.bottom += yOff + return rect +} + +// Coverts a box from "div" coords to another coordinate system. +// Context may be "window", "page", "div", or "local"./null. +function fromCoordSystem(cm, coords, context) { + if (context == "div") { return coords } + var left = coords.left, top = coords.top + // First move into "page" coordinate system + if (context == "page") { + left -= pageScrollX() + top -= pageScrollY() + } else if (context == "local" || !context) { + var localBox = cm.display.sizer.getBoundingClientRect() + left += localBox.left + top += localBox.top + } + + var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect() + return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top} +} + +function charCoords(cm, pos, context, lineObj, bias) { + if (!lineObj) { lineObj = getLine(cm.doc, pos.line) } + return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context) +} + +// Returns a box for a given cursor position, which may have an +// 'other' property containing the position of the secondary cursor +// on a bidi boundary. +function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) { + lineObj = lineObj || getLine(cm.doc, pos.line) + if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj) } + function get(ch, right) { + var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight) + if (right) { m.left = m.right; } else { m.right = m.left } + return intoCoordSystem(cm, lineObj, m, context) + } + function getBidi(ch, partPos) { + var part = order[partPos], right = part.level % 2 + if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) { + part = order[--partPos] + ch = bidiRight(part) - (part.level % 2 ? 0 : 1) + right = true + } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) { + part = order[++partPos] + ch = bidiLeft(part) - part.level % 2 + right = false + } + if (right && ch == part.to && ch > part.from) { return get(ch - 1) } + return get(ch, right) + } + var order = getOrder(lineObj), ch = pos.ch + if (!order) { return get(ch) } + var partPos = getBidiPartAt(order, ch) + var val = getBidi(ch, partPos) + if (bidiOther != null) { val.other = getBidi(ch, bidiOther) } + return val +} + +// Used to cheaply estimate the coordinates for a position. Used for +// intermediate scroll updates. +function estimateCoords(cm, pos) { + var left = 0 + pos = clipPos(cm.doc, pos) + if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch } + var lineObj = getLine(cm.doc, pos.line) + var top = heightAtLine(lineObj) + paddingTop(cm.display) + return {left: left, right: left, top: top, bottom: top + lineObj.height} +} + +// Positions returned by coordsChar contain some extra information. +// xRel is the relative x position of the input coordinates compared +// to the found position (so xRel > 0 means the coordinates are to +// the right of the character position, for example). When outside +// is true, that means the coordinates lie outside the line's +// vertical range. +function PosWithInfo(line, ch, outside, xRel) { + var pos = Pos(line, ch) + pos.xRel = xRel + if (outside) { pos.outside = true } + return pos +} + +// Compute the character position closest to the given coordinates. +// Input must be lineSpace-local ("div" coordinate system). +function coordsChar(cm, x, y) { + var doc = cm.doc + y += cm.display.viewOffset + if (y < 0) { return PosWithInfo(doc.first, 0, true, -1) } + var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1 + if (lineN > last) + { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1) } + if (x < 0) { x = 0 } + + var lineObj = getLine(doc, lineN) + for (;;) { + var found = coordsCharInner(cm, lineObj, lineN, x, y) + var merged = collapsedSpanAtEnd(lineObj) + var mergedPos = merged && merged.find(0, true) + if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0)) + { lineN = lineNo(lineObj = mergedPos.to.line) } else - display.selectionDiv.style.display = "none"; - - // Move the hidden textarea near the cursor to prevent scrolling artifacts - if (cm.options.moveInputWithCursor) { - var headPos = cursorCoords(cm, cm.doc.sel.head, "div"); - var wrapOff = getRect(display.wrapper), lineOff = getRect(display.lineDiv); - display.inputDiv.style.top = Math.max(0, Math.min(display.wrapper.clientHeight - 10, - headPos.top + lineOff.top - wrapOff.top)) + "px"; - display.inputDiv.style.left = Math.max(0, Math.min(display.wrapper.clientWidth - 10, - headPos.left + lineOff.left - wrapOff.left)) + "px"; - } - } - - // No selection, plain cursor - function updateSelectionCursor(cm) { - var display = cm.display, pos = cursorCoords(cm, cm.doc.sel.head, "div"); - display.cursor.style.left = pos.left + "px"; - display.cursor.style.top = pos.top + "px"; - display.cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"; - display.cursor.style.display = ""; - - if (pos.other) { - display.otherCursor.style.display = ""; - display.otherCursor.style.left = pos.other.left + "px"; - display.otherCursor.style.top = pos.other.top + "px"; - display.otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"; - } else { display.otherCursor.style.display = "none"; } - } - - // Highlight selection - function updateSelectionRange(cm) { - var display = cm.display, doc = cm.doc, sel = cm.doc.sel; - var fragment = document.createDocumentFragment(); - var clientWidth = display.lineSpace.offsetWidth, pl = paddingLeft(cm.display); - - function add(left, top, width, bottom) { - if (top < 0) top = 0; - fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left + - "px; top: " + top + "px; width: " + (width == null ? clientWidth - left : width) + - "px; height: " + (bottom - top) + "px")); - } - - function drawForLine(line, fromArg, toArg) { - var lineObj = getLine(doc, line); - var lineLen = lineObj.text.length; - var start, end; - function coords(ch, bias) { - return charCoords(cm, Pos(line, ch), "div", lineObj, bias); - } - - iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) { - var leftPos = coords(from, "left"), rightPos, left, right; - if (from == to) { - rightPos = leftPos; - left = right = leftPos.left; - } else { - rightPos = coords(to - 1, "right"); - if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; } - left = leftPos.left; - right = rightPos.right; - } - if (fromArg == null && from == 0) left = pl; - if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part - add(left, leftPos.top, null, leftPos.bottom); - left = pl; - if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top); - } - if (toArg == null && to == lineLen) right = clientWidth; - if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left) - start = leftPos; - if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right) - end = rightPos; - if (left < pl + 1) left = pl; - add(left, rightPos.top, right - left, rightPos.bottom); - }); - return {start: start, end: end}; - } - - if (sel.from.line == sel.to.line) { - drawForLine(sel.from.line, sel.from.ch, sel.to.ch); - } else { - var fromLine = getLine(doc, sel.from.line), toLine = getLine(doc, sel.to.line); - var singleVLine = visualLine(doc, fromLine) == visualLine(doc, toLine); - var leftEnd = drawForLine(sel.from.line, sel.from.ch, singleVLine ? fromLine.text.length : null).end; - var rightStart = drawForLine(sel.to.line, singleVLine ? 0 : null, sel.to.ch).start; - if (singleVLine) { - if (leftEnd.top < rightStart.top - 2) { - add(leftEnd.right, leftEnd.top, null, leftEnd.bottom); - add(pl, rightStart.top, rightStart.left, rightStart.bottom); - } else { - add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom); + { return found } + } +} + +function coordsCharInner(cm, lineObj, lineNo, x, y) { + var innerOff = y - heightAtLine(lineObj) + var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth + var preparedMeasure = prepareMeasureForLine(cm, lineObj) + + function getX(ch) { + var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure) + wrongLine = true + if (innerOff > sp.bottom) { return sp.left - adjust } + else if (innerOff < sp.top) { return sp.left + adjust } + else { wrongLine = false } + return sp.left + } + + var bidi = getOrder(lineObj), dist = lineObj.text.length + var from = lineLeft(lineObj), to = lineRight(lineObj) + var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine + + if (x > toX) { return PosWithInfo(lineNo, to, toOutside, 1) } + // Do a binary search between these bounds. + for (;;) { + if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) { + var ch = x < fromX || x - fromX <= toX - x ? from : to + var outside = ch == from ? fromOutside : toOutside + var xDiff = x - (ch == from ? fromX : toX) + // This is a kludge to handle the case where the coordinates + // are after a line-wrapped line. We should replace it with a + // more general handling of cursor positions around line + // breaks. (Issue #4078) + if (toOutside && !bidi && !/\s/.test(lineObj.text.charAt(ch)) && xDiff > 0 && + ch < lineObj.text.length && preparedMeasure.view.measure.heights.length > 1) { + var charSize = measureCharPrepared(cm, preparedMeasure, ch, "right") + if (innerOff <= charSize.bottom && innerOff >= charSize.top && Math.abs(x - charSize.right) < xDiff) { + outside = false + ch++ + xDiff = x - charSize.right } } - if (leftEnd.bottom < rightStart.top) - add(pl, leftEnd.bottom, null, rightStart.top); - } - - removeChildrenAndAdd(display.selectionDiv, fragment); - display.selectionDiv.style.display = ""; - } - - // Cursor-blinking - function restartBlink(cm) { - if (!cm.state.focused) return; - var display = cm.display; - clearInterval(display.blinker); - var on = true; - display.cursor.style.visibility = display.otherCursor.style.visibility = ""; - if (cm.options.cursorBlinkRate > 0) - display.blinker = setInterval(function() { - display.cursor.style.visibility = display.otherCursor.style.visibility = (on = !on) ? "" : "hidden"; - }, cm.options.cursorBlinkRate); - } - - // HIGHLIGHT WORKER - - function startWorker(cm, time) { - if (cm.doc.mode.startState && cm.doc.frontier < cm.display.showingTo) - cm.state.highlight.set(time, bind(highlightWorker, cm)); - } - - function highlightWorker(cm) { - var doc = cm.doc; - if (doc.frontier < doc.first) doc.frontier = doc.first; - if (doc.frontier >= cm.display.showingTo) return; - var end = +new Date + cm.options.workTime; - var state = copyState(doc.mode, getStateBefore(cm, doc.frontier)); - var changed = [], prevChange; - doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.showingTo + 500), function(line) { - if (doc.frontier >= cm.display.showingFrom) { // Visible - var oldStyles = line.styles; - line.styles = highlightLine(cm, line, state, true); - var ischange = !oldStyles || oldStyles.length != line.styles.length; - for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i]; - if (ischange) { - if (prevChange && prevChange.end == doc.frontier) prevChange.end++; - else changed.push(prevChange = {start: doc.frontier, end: doc.frontier + 1}); - } - line.stateAfter = copyState(doc.mode, state); + while (isExtendingChar(lineObj.text.charAt(ch))) { ++ch } + var pos = PosWithInfo(lineNo, ch, outside, xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0) + return pos + } + var step = Math.ceil(dist / 2), middle = from + step + if (bidi) { + middle = from + for (var i = 0; i < step; ++i) { middle = moveVisually(lineObj, middle, 1) } + } + var middleX = getX(middle) + if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) { toX += 1000; } dist = step} + else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step} + } +} + +var measureText +// Compute the default text height. +function textHeight(display) { + if (display.cachedTextHeight != null) { return display.cachedTextHeight } + if (measureText == null) { + measureText = elt("pre") + // Measure a bunch of lines, for browsers that compute + // fractional heights. + for (var i = 0; i < 49; ++i) { + measureText.appendChild(document.createTextNode("x")) + measureText.appendChild(elt("br")) + } + measureText.appendChild(document.createTextNode("x")) + } + removeChildrenAndAdd(display.measure, measureText) + var height = measureText.offsetHeight / 50 + if (height > 3) { display.cachedTextHeight = height } + removeChildren(display.measure) + return height || 1 +} + +// Compute the default character width. +function charWidth(display) { + if (display.cachedCharWidth != null) { return display.cachedCharWidth } + var anchor = elt("span", "xxxxxxxxxx") + var pre = elt("pre", [anchor]) + removeChildrenAndAdd(display.measure, pre) + var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10 + if (width > 2) { display.cachedCharWidth = width } + return width || 10 +} + +// Do a bulk-read of the DOM positions and sizes needed to draw the +// view, so that we don't interleave reading and writing to the DOM. +function getDimensions(cm) { + var d = cm.display, left = {}, width = {} + var gutterLeft = d.gutters.clientLeft + for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) { + left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft + width[cm.options.gutters[i]] = n.clientWidth + } + return {fixedPos: compensateForHScroll(d), + gutterTotalWidth: d.gutters.offsetWidth, + gutterLeft: left, + gutterWidth: width, + wrapperWidth: d.wrapper.clientWidth} +} + +// Computes display.scroller.scrollLeft + display.gutters.offsetWidth, +// but using getBoundingClientRect to get a sub-pixel-accurate +// result. +function compensateForHScroll(display) { + return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left +} + +// Returns a function that estimates the height of a line, to use as +// first approximation until the line becomes visible (and is thus +// properly measurable). +function estimateHeight(cm) { + var th = textHeight(cm.display), wrapping = cm.options.lineWrapping + var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3) + return function (line) { + if (lineIsHidden(cm.doc, line)) { return 0 } + + var widgetsHeight = 0 + if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) { + if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height } + } } + + if (wrapping) + { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th } + else + { return widgetsHeight + th } + } +} + +function estimateLineHeights(cm) { + var doc = cm.doc, est = estimateHeight(cm) + doc.iter(function (line) { + var estHeight = est(line) + if (estHeight != line.height) { updateLineHeight(line, estHeight) } + }) +} + +// Given a mouse event, find the corresponding position. If liberal +// is false, it checks whether a gutter or scrollbar was clicked, +// and returns null if it was. forRect is used by rectangular +// selections, and tries to estimate a character position even for +// coordinates beyond the right of the text. +function posFromMouse(cm, e, liberal, forRect) { + var display = cm.display + if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null } + + var x, y, space = display.lineSpace.getBoundingClientRect() + // Fails unpredictably on IE[67] when mouse is dragged around quickly. + try { x = e.clientX - space.left; y = e.clientY - space.top } + catch (e) { return null } + var coords = coordsChar(cm, x, y), line + if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) { + var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length + coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff)) + } + return coords +} + +// Find the view element corresponding to a given line. Return null +// when the line isn't visible. +function findViewIndex(cm, n) { + if (n >= cm.display.viewTo) { return null } + n -= cm.display.viewFrom + if (n < 0) { return null } + var view = cm.display.view + for (var i = 0; i < view.length; i++) { + n -= view[i].size + if (n < 0) { return i } + } +} + +function updateSelection(cm) { + cm.display.input.showSelection(cm.display.input.prepareSelection()) +} + +function prepareSelection(cm, primary) { + var doc = cm.doc, result = {} + var curFragment = result.cursors = document.createDocumentFragment() + var selFragment = result.selection = document.createDocumentFragment() + + for (var i = 0; i < doc.sel.ranges.length; i++) { + if (primary === false && i == doc.sel.primIndex) { continue } + var range = doc.sel.ranges[i] + if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) { continue } + var collapsed = range.empty() + if (collapsed || cm.options.showCursorWhenSelecting) + { drawSelectionCursor(cm, range.head, curFragment) } + if (!collapsed) + { drawSelectionRange(cm, range, selFragment) } + } + return result +} + +// Draws a cursor for the given range +function drawSelectionCursor(cm, head, output) { + var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine) + + var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor")) + cursor.style.left = pos.left + "px" + cursor.style.top = pos.top + "px" + cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px" + + if (pos.other) { + // Secondary cursor, shown when on a 'jump' in bi-directional text + var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor")) + otherCursor.style.display = "" + otherCursor.style.left = pos.other.left + "px" + otherCursor.style.top = pos.other.top + "px" + otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px" + } +} + +// Draws the given range as a highlighted selection +function drawSelectionRange(cm, range, output) { + var display = cm.display, doc = cm.doc + var fragment = document.createDocumentFragment() + var padding = paddingH(cm.display), leftSide = padding.left + var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right + + function add(left, top, width, bottom) { + if (top < 0) { top = 0 } + top = Math.round(top) + bottom = Math.round(bottom) + fragment.appendChild(elt("div", null, "CodeMirror-selected", ("position: absolute; left: " + left + "px;\n top: " + top + "px; width: " + (width == null ? rightSide - left : width) + "px;\n height: " + (bottom - top) + "px"))) + } + + function drawForLine(line, fromArg, toArg) { + var lineObj = getLine(doc, line) + var lineLen = lineObj.text.length + var start, end + function coords(ch, bias) { + return charCoords(cm, Pos(line, ch), "div", lineObj, bias) + } + + iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir) { + var leftPos = coords(from, "left"), rightPos, left, right + if (from == to) { + rightPos = leftPos + left = right = leftPos.left } else { - processLine(cm, line.text, state); - line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null; + rightPos = coords(to - 1, "right") + if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp } + left = leftPos.left + right = rightPos.right } - ++doc.frontier; - if (+new Date > end) { - startWorker(cm, cm.options.workDelay); - return true; + if (fromArg == null && from == 0) { left = leftSide } + if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part + add(left, leftPos.top, null, leftPos.bottom) + left = leftSide + if (leftPos.bottom < rightPos.top) { add(left, leftPos.bottom, null, rightPos.top) } } - }); - if (changed.length) - operation(cm, function() { - for (var i = 0; i < changed.length; ++i) - regChange(this, changed[i].start, changed[i].end); - })(); - } - - // Finds the line to start with when starting a parse. Tries to - // find a line with a stateAfter, so that it can start with a - // valid state. If that fails, it returns the line with the - // smallest indentation, which tends to need the least context to - // parse correctly. - function findStartLine(cm, n, precise) { - var minindent, minline, doc = cm.doc; - var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100); - for (var search = n; search > lim; --search) { - if (search <= doc.first) return doc.first; - var line = getLine(doc, search - 1); - if (line.stateAfter && (!precise || search <= doc.frontier)) return search; - var indented = countColumn(line.text, null, cm.options.tabSize); - if (minline == null || minindent > indented) { - minline = search - 1; - minindent = indented; + if (toArg == null && to == lineLen) { right = rightSide } + if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left) + { start = leftPos } + if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right) + { end = rightPos } + if (left < leftSide + 1) { left = leftSide } + add(left, rightPos.top, right - left, rightPos.bottom) + }) + return {start: start, end: end} + } + + var sFrom = range.from(), sTo = range.to() + if (sFrom.line == sTo.line) { + drawForLine(sFrom.line, sFrom.ch, sTo.ch) + } else { + var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line) + var singleVLine = visualLine(fromLine) == visualLine(toLine) + var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end + var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start + if (singleVLine) { + if (leftEnd.top < rightStart.top - 2) { + add(leftEnd.right, leftEnd.top, null, leftEnd.bottom) + add(leftSide, rightStart.top, rightStart.left, rightStart.bottom) + } else { + add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom) } } - return minline; - } - - function getStateBefore(cm, n, precise) { - var doc = cm.doc, display = cm.display; - if (!doc.mode.startState) return true; - var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter; - if (!state) state = startState(doc.mode); - else state = copyState(doc.mode, state); - doc.iter(pos, n, function(line) { - processLine(cm, line.text, state); - var save = pos == n - 1 || pos % 5 == 0 || pos >= display.showingFrom && pos < display.showingTo; - line.stateAfter = save ? copyState(doc.mode, state) : null; - ++pos; - }); - if (precise) doc.frontier = pos; - return state; - } - - // POSITION MEASUREMENT - - function paddingTop(display) {return display.lineSpace.offsetTop;} - function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;} - function paddingLeft(display) { - var e = removeChildrenAndAdd(display.measure, elt("pre", null, null, "text-align: left")).appendChild(elt("span", "x")); - return e.offsetLeft; - } - - function measureChar(cm, line, ch, data, bias) { - var dir = -1; - data = data || measureLine(cm, line); - if (data.crude) { - var left = data.left + ch * data.width; - return {left: left, right: left + data.width, top: data.top, bottom: data.bottom}; - } - - for (var pos = ch;; pos += dir) { - var r = data[pos]; - if (r) break; - if (dir < 0 && pos == 0) dir = 1; - } - bias = pos > ch ? "left" : pos < ch ? "right" : bias; - if (bias == "left" && r.leftSide) r = r.leftSide; - else if (bias == "right" && r.rightSide) r = r.rightSide; - return {left: pos < ch ? r.right : r.left, - right: pos > ch ? r.left : r.right, - top: r.top, - bottom: r.bottom}; - } - - function findCachedMeasurement(cm, line) { - var cache = cm.display.measureLineCache; - for (var i = 0; i < cache.length; ++i) { - var memo = cache[i]; - if (memo.text == line.text && memo.markedSpans == line.markedSpans && - cm.display.scroller.clientWidth == memo.width && - memo.classes == line.textClass + "|" + line.wrapClass) - return memo; - } - } - - function clearCachedMeasurement(cm, line) { - var exists = findCachedMeasurement(cm, line); - if (exists) exists.text = exists.measure = exists.markedSpans = null; - } - - function measureLine(cm, line) { - // First look in the cache - var cached = findCachedMeasurement(cm, line); - if (cached) return cached.measure; - - // Failing that, recompute and store result in cache - var measure = measureLineInner(cm, line); - var cache = cm.display.measureLineCache; - var memo = {text: line.text, width: cm.display.scroller.clientWidth, - markedSpans: line.markedSpans, measure: measure, - classes: line.textClass + "|" + line.wrapClass}; - if (cache.length == 16) cache[++cm.display.measureLineCachePos % 16] = memo; - else cache.push(memo); - return measure; - } - - function measureLineInner(cm, line) { - if (!cm.options.lineWrapping && line.text.length >= cm.options.crudeMeasuringFrom) - return crudelyMeasureLine(cm, line); - - var display = cm.display, measure = emptyArray(line.text.length); - var pre = buildLineContent(cm, line, measure, true).pre; - - // IE does not cache element positions of inline elements between - // calls to getBoundingClientRect. This makes the loop below, - // which gathers the positions of all the characters on the line, - // do an amount of layout work quadratic to the number of - // characters. When line wrapping is off, we try to improve things - // by first subdividing the line into a bunch of inline blocks, so - // that IE can reuse most of the layout information from caches - // for those blocks. This does interfere with line wrapping, so it - // doesn't work when wrapping is on, but in that case the - // situation is slightly better, since IE does cache line-wrapping - // information and only recomputes per-line. - if (ie && !ie_lt8 && !cm.options.lineWrapping && pre.childNodes.length > 100) { - var fragment = document.createDocumentFragment(); - var chunk = 10, n = pre.childNodes.length; - for (var i = 0, chunks = Math.ceil(n / chunk); i < chunks; ++i) { - var wrap = elt("div", null, null, "display: inline-block"); - for (var j = 0; j < chunk && n; ++j) { - wrap.appendChild(pre.firstChild); - --n; - } - fragment.appendChild(wrap); - } - pre.appendChild(fragment); - } - - removeChildrenAndAdd(display.measure, pre); - - var outer = getRect(display.lineDiv); - var vranges = [], data = emptyArray(line.text.length), maxBot = pre.offsetHeight; - // Work around an IE7/8 bug where it will sometimes have randomly - // replaced our pre with a clone at this point. - if (ie_lt9 && display.measure.first != pre) - removeChildrenAndAdd(display.measure, pre); - - function measureRect(rect) { - var top = rect.top - outer.top, bot = rect.bottom - outer.top; - if (bot > maxBot) bot = maxBot; - if (top < 0) top = 0; - for (var i = vranges.length - 2; i >= 0; i -= 2) { - var rtop = vranges[i], rbot = vranges[i+1]; - if (rtop > bot || rbot < top) continue; - if (rtop <= top && rbot >= bot || - top <= rtop && bot >= rbot || - Math.min(bot, rbot) - Math.max(top, rtop) >= (bot - top) >> 1) { - vranges[i] = Math.min(top, rtop); - vranges[i+1] = Math.max(bot, rbot); - break; - } - } - if (i < 0) { i = vranges.length; vranges.push(top, bot); } - return {left: rect.left - outer.left, - right: rect.right - outer.left, - top: i, bottom: null}; - } - function finishRect(rect) { - rect.bottom = vranges[rect.top+1]; - rect.top = vranges[rect.top]; - } - - for (var i = 0, cur; i < measure.length; ++i) if (cur = measure[i]) { - var node = cur, rect = null; - // A widget might wrap, needs special care - if (/\bCodeMirror-widget\b/.test(cur.className) && cur.getClientRects) { - if (cur.firstChild.nodeType == 1) node = cur.firstChild; - var rects = node.getClientRects(); - if (rects.length > 1) { - rect = data[i] = measureRect(rects[0]); - rect.rightSide = measureRect(rects[rects.length - 1]); + if (leftEnd.bottom < rightStart.top) + { add(leftSide, leftEnd.bottom, null, rightStart.top) } + } + + output.appendChild(fragment) +} + +// Cursor-blinking +function restartBlink(cm) { + if (!cm.state.focused) { return } + var display = cm.display + clearInterval(display.blinker) + var on = true + display.cursorDiv.style.visibility = "" + if (cm.options.cursorBlinkRate > 0) + { display.blinker = setInterval(function () { return display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; }, + cm.options.cursorBlinkRate) } + else if (cm.options.cursorBlinkRate < 0) + { display.cursorDiv.style.visibility = "hidden" } +} + +function ensureFocus(cm) { + if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm) } +} + +function delayBlurEvent(cm) { + cm.state.delayingBlurEvent = true + setTimeout(function () { if (cm.state.delayingBlurEvent) { + cm.state.delayingBlurEvent = false + onBlur(cm) + } }, 100) +} + +function onFocus(cm, e) { + if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false } + + if (cm.options.readOnly == "nocursor") { return } + if (!cm.state.focused) { + signal(cm, "focus", cm, e) + cm.state.focused = true + addClass(cm.display.wrapper, "CodeMirror-focused") + // This test prevents this from firing when a context + // menu is closed (since the input reset would kill the + // select-all detection hack) + if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) { + cm.display.input.reset() + if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20) } // Issue #1730 + } + cm.display.input.receivedFocus() + } + restartBlink(cm) +} +function onBlur(cm, e) { + if (cm.state.delayingBlurEvent) { return } + + if (cm.state.focused) { + signal(cm, "blur", cm, e) + cm.state.focused = false + rmClass(cm.display.wrapper, "CodeMirror-focused") + } + clearInterval(cm.display.blinker) + setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false } }, 150) +} + +// Re-align line numbers and gutter marks to compensate for +// horizontal scrolling. +function alignHorizontally(cm) { + var display = cm.display, view = display.view + if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return } + var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft + var gutterW = display.gutters.offsetWidth, left = comp + "px" + for (var i = 0; i < view.length; i++) { if (!view[i].hidden) { + if (cm.options.fixedGutter) { + if (view[i].gutter) + { view[i].gutter.style.left = left } + if (view[i].gutterBackground) + { view[i].gutterBackground.style.left = left } + } + var align = view[i].alignable + if (align) { for (var j = 0; j < align.length; j++) + { align[j].style.left = left } } + } } + if (cm.options.fixedGutter) + { display.gutters.style.left = (comp + gutterW) + "px" } +} + +// Used to ensure that the line number gutter is still the right +// size for the current document size. Returns true when an update +// is needed. +function maybeUpdateLineNumberWidth(cm) { + if (!cm.options.lineNumbers) { return false } + var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display + if (last.length != display.lineNumChars) { + var test = display.measure.appendChild(elt("div", [elt("div", last)], + "CodeMirror-linenumber CodeMirror-gutter-elt")) + var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW + display.lineGutter.style.width = "" + display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1 + display.lineNumWidth = display.lineNumInnerWidth + padding + display.lineNumChars = display.lineNumInnerWidth ? last.length : -1 + display.lineGutter.style.width = display.lineNumWidth + "px" + updateGutterSpace(cm) + return true + } + return false +} + +// Read the actual heights of the rendered lines, and update their +// stored heights to match. +function updateHeightsInViewport(cm) { + var display = cm.display + var prevBottom = display.lineDiv.offsetTop + for (var i = 0; i < display.view.length; i++) { + var cur = display.view[i], height = (void 0) + if (cur.hidden) { continue } + if (ie && ie_version < 8) { + var bot = cur.node.offsetTop + cur.node.offsetHeight + height = bot - prevBottom + prevBottom = bot + } else { + var box = cur.node.getBoundingClientRect() + height = box.bottom - box.top + } + var diff = cur.line.height - height + if (height < 2) { height = textHeight(display) } + if (diff > .001 || diff < -.001) { + updateLineHeight(cur.line, height) + updateWidgetHeight(cur.line) + if (cur.rest) { for (var j = 0; j < cur.rest.length; j++) + { updateWidgetHeight(cur.rest[j]) } } + } + } +} + +// Read and store the height of line widgets associated with the +// given line. +function updateWidgetHeight(line) { + if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) + { line.widgets[i].height = line.widgets[i].node.parentNode.offsetHeight } } +} + +// Compute the lines that are visible in a given viewport (defaults +// the the current scroll position). viewport may contain top, +// height, and ensure (see op.scrollToPos) properties. +function visibleLines(display, doc, viewport) { + var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop + top = Math.floor(top - paddingTop(display)) + var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight + + var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom) + // Ensure is a {from: {line, ch}, to: {line, ch}} object, and + // forces those lines into the viewport (if possible). + if (viewport && viewport.ensure) { + var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line + if (ensureFrom < from) { + from = ensureFrom + to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight) + } else if (Math.min(ensureTo, doc.lastLine()) >= to) { + from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight) + to = ensureTo + } + } + return {from: from, to: Math.max(to, from + 1)} +} + +// Sync the scrollable area and scrollbars, ensure the viewport +// covers the visible area. +function setScrollTop(cm, val) { + if (Math.abs(cm.doc.scrollTop - val) < 2) { return } + cm.doc.scrollTop = val + if (!gecko) { updateDisplaySimple(cm, {top: val}) } + if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val } + cm.display.scrollbars.setScrollTop(val) + if (gecko) { updateDisplaySimple(cm) } + startWorker(cm, 100) +} +// Sync scroller and scrollbar, ensure the gutter elements are +// aligned. +function setScrollLeft(cm, val, isScroller) { + if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) { return } + val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth) + cm.doc.scrollLeft = val + alignHorizontally(cm) + if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val } + cm.display.scrollbars.setScrollLeft(val) +} + +// Since the delta values reported on mouse wheel events are +// unstandardized between browsers and even browser versions, and +// generally horribly unpredictable, this code starts by measuring +// the scroll effect that the first few mouse wheel events have, +// and, from that, detects the way it can convert deltas to pixel +// offsets afterwards. +// +// The reason we want to know the amount a wheel event will scroll +// is that it gives us a chance to update the display before the +// actual scrolling happens, reducing flickering. + +var wheelSamples = 0; +var wheelPixelsPerUnit = null; +// Fill in a browser-detected starting value on browsers where we +// know one. These don't have to be accurate -- the result of them +// being wrong would just be a slight flicker on the first wheel +// scroll (if it is large enough). +if (ie) { wheelPixelsPerUnit = -.53 } +else if (gecko) { wheelPixelsPerUnit = 15 } +else if (chrome) { wheelPixelsPerUnit = -.7 } +else if (safari) { wheelPixelsPerUnit = -1/3 } + +function wheelEventDelta(e) { + var dx = e.wheelDeltaX, dy = e.wheelDeltaY + if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail } + if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail } + else if (dy == null) { dy = e.wheelDelta } + return {x: dx, y: dy} +} +function wheelEventPixels(e) { + var delta = wheelEventDelta(e) + delta.x *= wheelPixelsPerUnit + delta.y *= wheelPixelsPerUnit + return delta +} + +function onScrollWheel(cm, e) { + var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y + + var display = cm.display, scroll = display.scroller + // Quit if there's nothing to scroll here + var canScrollX = scroll.scrollWidth > scroll.clientWidth + var canScrollY = scroll.scrollHeight > scroll.clientHeight + if (!(dx && canScrollX || dy && canScrollY)) { return } + + // Webkit browsers on OS X abort momentum scrolls when the target + // of the scroll event is removed from the scrollable element. + // This hack (see related code in patchDisplay) makes sure the + // element is kept around. + if (dy && mac && webkit) { + outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) { + for (var i = 0; i < view.length; i++) { + if (view[i].node == cur) { + cm.display.currentWheelTarget = cur + break outer } } - if (!rect) rect = data[i] = measureRect(getRect(node)); - if (cur.measureRight) rect.right = getRect(cur.measureRight).left; - if (cur.leftSide) rect.leftSide = measureRect(getRect(cur.leftSide)); - } - removeChildren(cm.display.measure); - for (var i = 0, cur; i < data.length; ++i) if (cur = data[i]) { - finishRect(cur); - if (cur.leftSide) finishRect(cur.leftSide); - if (cur.rightSide) finishRect(cur.rightSide); - } - return data; - } - - function crudelyMeasureLine(cm, line) { - var copy = new Line(line.text.slice(0, 100), null); - if (line.textClass) copy.textClass = line.textClass; - var measure = measureLineInner(cm, copy); - var left = measureChar(cm, copy, 0, measure, "left"); - var right = measureChar(cm, copy, 99, measure, "right"); - return {crude: true, top: left.top, left: left.left, bottom: left.bottom, width: (right.right - left.left) / 100}; - } - - function measureLineWidth(cm, line) { - var hasBadSpan = false; - if (line.markedSpans) for (var i = 0; i < line.markedSpans; ++i) { - var sp = line.markedSpans[i]; - if (sp.collapsed && (sp.to == null || sp.to == line.text.length)) hasBadSpan = true; - } - var cached = !hasBadSpan && findCachedMeasurement(cm, line); - if (cached || line.text.length >= cm.options.crudeMeasuringFrom) - return measureChar(cm, line, line.text.length, cached && cached.measure, "right").right; - - var pre = buildLineContent(cm, line, null, true).pre; - var end = pre.appendChild(zeroWidthElement(cm.display.measure)); - removeChildrenAndAdd(cm.display.measure, pre); - return getRect(end).right - getRect(cm.display.lineDiv).left; - } - - function clearCaches(cm) { - cm.display.measureLineCache.length = cm.display.measureLineCachePos = 0; - cm.display.cachedCharWidth = cm.display.cachedTextHeight = null; - if (!cm.options.lineWrapping) cm.display.maxLineChanged = true; - cm.display.lineNumChars = null; - } - - function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; } - function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; } - - // Context is one of "line", "div" (display.lineDiv), "local"/null (editor), or "page" - function intoCoordSystem(cm, lineObj, rect, context) { - if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) { - var size = widgetHeight(lineObj.widgets[i]); - rect.top += size; rect.bottom += size; - } - if (context == "line") return rect; - if (!context) context = "local"; - var yOff = heightAtLine(cm, lineObj); - if (context == "local") yOff += paddingTop(cm.display); - else yOff -= cm.display.viewOffset; - if (context == "page" || context == "window") { - var lOff = getRect(cm.display.lineSpace); - yOff += lOff.top + (context == "window" ? 0 : pageScrollY()); - var xOff = lOff.left + (context == "window" ? 0 : pageScrollX()); - rect.left += xOff; rect.right += xOff; - } - rect.top += yOff; rect.bottom += yOff; - return rect; - } - - // Context may be "window", "page", "div", or "local"/null - // Result is in "div" coords - function fromCoordSystem(cm, coords, context) { - if (context == "div") return coords; - var left = coords.left, top = coords.top; - // First move into "page" coordinate system - if (context == "page") { - left -= pageScrollX(); - top -= pageScrollY(); - } else if (context == "local" || !context) { - var localBox = getRect(cm.display.sizer); - left += localBox.left; - top += localBox.top; - } - - var lineSpaceBox = getRect(cm.display.lineSpace); - return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}; - } - - function charCoords(cm, pos, context, lineObj, bias) { - if (!lineObj) lineObj = getLine(cm.doc, pos.line); - return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, null, bias), context); - } - - function cursorCoords(cm, pos, context, lineObj, measurement) { - lineObj = lineObj || getLine(cm.doc, pos.line); - if (!measurement) measurement = measureLine(cm, lineObj); - function get(ch, right) { - var m = measureChar(cm, lineObj, ch, measurement, right ? "right" : "left"); - if (right) m.left = m.right; else m.right = m.left; - return intoCoordSystem(cm, lineObj, m, context); - } - function getBidi(ch, partPos) { - var part = order[partPos], right = part.level % 2; - if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) { - part = order[--partPos]; - ch = bidiRight(part) - (part.level % 2 ? 0 : 1); - right = true; - } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) { - part = order[++partPos]; - ch = bidiLeft(part) - part.level % 2; - right = false; - } - if (right && ch == part.to && ch > part.from) return get(ch - 1); - return get(ch, right); - } - var order = getOrder(lineObj), ch = pos.ch; - if (!order) return get(ch); - var partPos = getBidiPartAt(order, ch); - var val = getBidi(ch, partPos); - if (bidiOther != null) val.other = getBidi(ch, bidiOther); - return val; - } - - function PosWithInfo(line, ch, outside, xRel) { - var pos = new Pos(line, ch); - pos.xRel = xRel; - if (outside) pos.outside = true; - return pos; - } - - // Coords must be lineSpace-local - function coordsChar(cm, x, y) { - var doc = cm.doc; - y += cm.display.viewOffset; - if (y < 0) return PosWithInfo(doc.first, 0, true, -1); - var lineNo = lineAtHeight(doc, y), last = doc.first + doc.size - 1; - if (lineNo > last) - return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1); - if (x < 0) x = 0; - - for (;;) { - var lineObj = getLine(doc, lineNo); - var found = coordsCharInner(cm, lineObj, lineNo, x, y); - var merged = collapsedSpanAtEnd(lineObj); - var mergedPos = merged && merged.find(); - if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0)) - lineNo = mergedPos.to.line; - else - return found; } } - function coordsCharInner(cm, lineObj, lineNo, x, y) { - var innerOff = y - heightAtLine(cm, lineObj); - var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth; - var measurement = measureLine(cm, lineObj); - - function getX(ch) { - var sp = cursorCoords(cm, Pos(lineNo, ch), "line", - lineObj, measurement); - wrongLine = true; - if (innerOff > sp.bottom) return sp.left - adjust; - else if (innerOff < sp.top) return sp.left + adjust; - else wrongLine = false; - return sp.left; + // On some browsers, horizontal scrolling will cause redraws to + // happen before the gutter has been realigned, causing it to + // wriggle around in a most unseemly way. When we have an + // estimated pixels/delta value, we just handle horizontal + // scrolling entirely here. It'll be slightly off from native, but + // better than glitching out. + if (dx && !gecko && !presto && wheelPixelsPerUnit != null) { + if (dy && canScrollY) + { setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight))) } + setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth))) + // Only prevent default scrolling if vertical scrolling is + // actually possible. Otherwise, it causes vertical scroll + // jitter on OSX trackpads when deltaX is small and deltaY + // is large (issue #3579) + if (!dy || (dy && canScrollY)) + { e_preventDefault(e) } + display.wheelStartX = null // Abort measurement, if in progress + return + } + + // 'Project' the visible viewport to cover the area that is being + // scrolled into view (if we know enough to estimate it). + if (dy && wheelPixelsPerUnit != null) { + var pixels = dy * wheelPixelsPerUnit + var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight + if (pixels < 0) { top = Math.max(0, top + pixels - 50) } + else { bot = Math.min(cm.doc.height, bot + pixels + 50) } + updateDisplaySimple(cm, {top: top, bottom: bot}) + } + + if (wheelSamples < 20) { + if (display.wheelStartX == null) { + display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop + display.wheelDX = dx; display.wheelDY = dy + setTimeout(function () { + if (display.wheelStartX == null) { return } + var movedX = scroll.scrollLeft - display.wheelStartX + var movedY = scroll.scrollTop - display.wheelStartY + var sample = (movedY && display.wheelDY && movedY / display.wheelDY) || + (movedX && display.wheelDX && movedX / display.wheelDX) + display.wheelStartX = display.wheelStartY = null + if (!sample) { return } + wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1) + ++wheelSamples + }, 200) + } else { + display.wheelDX += dx; display.wheelDY += dy + } + } +} + +// SCROLLBARS + +// Prepare DOM reads needed to update the scrollbars. Done in one +// shot to minimize update/measure roundtrips. +function measureForScrollbars(cm) { + var d = cm.display, gutterW = d.gutters.offsetWidth + var docH = Math.round(cm.doc.height + paddingVert(cm.display)) + return { + clientHeight: d.scroller.clientHeight, + viewHeight: d.wrapper.clientHeight, + scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth, + viewWidth: d.wrapper.clientWidth, + barLeft: cm.options.fixedGutter ? gutterW : 0, + docHeight: docH, + scrollHeight: docH + scrollGap(cm) + d.barHeight, + nativeBarWidth: d.nativeBarWidth, + gutterWidth: gutterW + } +} + +var NativeScrollbars = function(place, scroll, cm) { + this.cm = cm + var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar") + var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar") + place(vert); place(horiz) + + on(vert, "scroll", function () { + if (vert.clientHeight) { scroll(vert.scrollTop, "vertical") } + }) + on(horiz, "scroll", function () { + if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal") } + }) + + this.checkedZeroWidth = false + // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). + if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px" } +}; + +NativeScrollbars.prototype.update = function (measure) { + var needsH = measure.scrollWidth > measure.clientWidth + 1 + var needsV = measure.scrollHeight > measure.clientHeight + 1 + var sWidth = measure.nativeBarWidth + + if (needsV) { + this.vert.style.display = "block" + this.vert.style.bottom = needsH ? sWidth + "px" : "0" + var totalHeight = measure.viewHeight - (needsH ? sWidth : 0) + // A bug in IE8 can cause this value to be negative, so guard it. + this.vert.firstChild.style.height = + Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px" + } else { + this.vert.style.display = "" + this.vert.firstChild.style.height = "0" + } + + if (needsH) { + this.horiz.style.display = "block" + this.horiz.style.right = needsV ? sWidth + "px" : "0" + this.horiz.style.left = measure.barLeft + "px" + var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0) + this.horiz.firstChild.style.width = + (measure.scrollWidth - measure.clientWidth + totalWidth) + "px" + } else { + this.horiz.style.display = "" + this.horiz.firstChild.style.width = "0" + } + + if (!this.checkedZeroWidth && measure.clientHeight > 0) { + if (sWidth == 0) { this.zeroWidthHack() } + this.checkedZeroWidth = true + } + + return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0} +}; + +NativeScrollbars.prototype.setScrollLeft = function (pos) { + if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos } + if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz) } +}; + +NativeScrollbars.prototype.setScrollTop = function (pos) { + if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos } + if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert) } +}; + +NativeScrollbars.prototype.zeroWidthHack = function () { + var w = mac && !mac_geMountainLion ? "12px" : "18px" + this.horiz.style.height = this.vert.style.width = w + this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none" + this.disableHoriz = new Delayed + this.disableVert = new Delayed +}; + +NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay) { + bar.style.pointerEvents = "auto" + function maybeDisable() { + // To find out whether the scrollbar is still visible, we + // check whether the element under the pixel in the bottom + // left corner of the scrollbar box is the scrollbar box + // itself (when the bar is still visible) or its filler child + // (when the bar is hidden). If it is still visible, we keep + // it enabled, if it's hidden, we disable pointer events. + var box = bar.getBoundingClientRect() + var elt = document.elementFromPoint(box.left + 1, box.bottom - 1) + if (elt != bar) { bar.style.pointerEvents = "none" } + else { delay.set(1000, maybeDisable) } + } + delay.set(1000, maybeDisable) +}; + +NativeScrollbars.prototype.clear = function () { + var parent = this.horiz.parentNode + parent.removeChild(this.horiz) + parent.removeChild(this.vert) +}; + +var NullScrollbars = function () {}; + +NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} }; +NullScrollbars.prototype.setScrollLeft = function () {}; +NullScrollbars.prototype.setScrollTop = function () {}; +NullScrollbars.prototype.clear = function () {}; + +function updateScrollbars(cm, measure) { + if (!measure) { measure = measureForScrollbars(cm) } + var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight + updateScrollbarsInner(cm, measure) + for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) { + if (startWidth != cm.display.barWidth && cm.options.lineWrapping) + { updateHeightsInViewport(cm) } + updateScrollbarsInner(cm, measureForScrollbars(cm)) + startWidth = cm.display.barWidth; startHeight = cm.display.barHeight + } +} + +// Re-synchronize the fake scrollbars with the actual size of the +// content. +function updateScrollbarsInner(cm, measure) { + var d = cm.display + var sizes = d.scrollbars.update(measure) + + d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px" + d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px" + d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent" + + if (sizes.right && sizes.bottom) { + d.scrollbarFiller.style.display = "block" + d.scrollbarFiller.style.height = sizes.bottom + "px" + d.scrollbarFiller.style.width = sizes.right + "px" + } else { d.scrollbarFiller.style.display = "" } + if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) { + d.gutterFiller.style.display = "block" + d.gutterFiller.style.height = sizes.bottom + "px" + d.gutterFiller.style.width = measure.gutterWidth + "px" + } else { d.gutterFiller.style.display = "" } +} + +var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars} + +function initScrollbars(cm) { + if (cm.display.scrollbars) { + cm.display.scrollbars.clear() + if (cm.display.scrollbars.addClass) + { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass) } + } + + cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) { + cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller) + // Prevent clicks in the scrollbars from killing focus + on(node, "mousedown", function () { + if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0) } + }) + node.setAttribute("cm-not-content", "true") + }, function (pos, axis) { + if (axis == "horizontal") { setScrollLeft(cm, pos) } + else { setScrollTop(cm, pos) } + }, cm) + if (cm.display.scrollbars.addClass) + { addClass(cm.display.wrapper, cm.display.scrollbars.addClass) } +} + +// SCROLLING THINGS INTO VIEW + +// If an editor sits on the top or bottom of the window, partially +// scrolled out of view, this ensures that the cursor is visible. +function maybeScrollWindow(cm, coords) { + if (signalDOMEvent(cm, "scrollCursorIntoView")) { return } + + var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null + if (coords.top + box.top < 0) { doScroll = true } + else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false } + if (doScroll != null && !phantom) { + var scrollNode = elt("div", "\u200b", null, ("position: absolute;\n top: " + (coords.top - display.viewOffset - paddingTop(cm.display)) + "px;\n height: " + (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px;\n left: " + (coords.left) + "px; width: 2px;")) + cm.display.lineSpace.appendChild(scrollNode) + scrollNode.scrollIntoView(doScroll) + cm.display.lineSpace.removeChild(scrollNode) + } +} + +// Scroll a given position into view (immediately), verifying that +// it actually became visible (as line heights are accurately +// measured, the position of something may 'drift' during drawing). +function scrollPosIntoView(cm, pos, end, margin) { + if (margin == null) { margin = 0 } + var coords + for (var limit = 0; limit < 5; limit++) { + var changed = false + coords = cursorCoords(cm, pos) + var endCoords = !end || end == pos ? coords : cursorCoords(cm, end) + var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left), + Math.min(coords.top, endCoords.top) - margin, + Math.max(coords.left, endCoords.left), + Math.max(coords.bottom, endCoords.bottom) + margin) + var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft + if (scrollPos.scrollTop != null) { + setScrollTop(cm, scrollPos.scrollTop) + if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true } + } + if (scrollPos.scrollLeft != null) { + setScrollLeft(cm, scrollPos.scrollLeft) + if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true } + } + if (!changed) { break } + } + return coords +} + +// Scroll a given set of coordinates into view (immediately). +function scrollIntoView(cm, x1, y1, x2, y2) { + var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2) + if (scrollPos.scrollTop != null) { setScrollTop(cm, scrollPos.scrollTop) } + if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft) } +} + +// Calculate a new scroll position needed to scroll the given +// rectangle into view. Returns an object with scrollTop and +// scrollLeft properties. When these are undefined, the +// vertical/horizontal position does not need to be adjusted. +function calculateScrollPos(cm, x1, y1, x2, y2) { + var display = cm.display, snapMargin = textHeight(cm.display) + if (y1 < 0) { y1 = 0 } + var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop + var screen = displayHeight(cm), result = {} + if (y2 - y1 > screen) { y2 = y1 + screen } + var docBottom = cm.doc.height + paddingVert(display) + var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin + if (y1 < screentop) { + result.scrollTop = atTop ? 0 : y1 + } else if (y2 > screentop + screen) { + var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen) + if (newTop != screentop) { result.scrollTop = newTop } + } + + var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft + var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0) + var tooWide = x2 - x1 > screenw + if (tooWide) { x2 = x1 + screenw } + if (x1 < 10) + { result.scrollLeft = 0 } + else if (x1 < screenleft) + { result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10)) } + else if (x2 > screenw + screenleft - 3) + { result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw } + return result +} + +// Store a relative adjustment to the scroll position in the current +// operation (to be applied when the operation finishes). +function addToScrollPos(cm, left, top) { + if (left != null || top != null) { resolveScrollToPos(cm) } + if (left != null) + { cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left } + if (top != null) + { cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top } +} + +// Make sure that at the end of the operation the current cursor is +// shown. +function ensureCursorVisible(cm) { + resolveScrollToPos(cm) + var cur = cm.getCursor(), from = cur, to = cur + if (!cm.options.lineWrapping) { + from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur + to = Pos(cur.line, cur.ch + 1) + } + cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true} +} + +// When an operation has its scrollToPos property set, and another +// scroll action is applied before the end of the operation, this +// 'simulates' scrolling that position into view in a cheap way, so +// that the effect of intermediate scroll commands is not ignored. +function resolveScrollToPos(cm) { + var range = cm.curOp.scrollToPos + if (range) { + cm.curOp.scrollToPos = null + var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to) + var sPos = calculateScrollPos(cm, Math.min(from.left, to.left), + Math.min(from.top, to.top) - range.margin, + Math.max(from.right, to.right), + Math.max(from.bottom, to.bottom) + range.margin) + cm.scrollTo(sPos.scrollLeft, sPos.scrollTop) + } +} + +// Operations are used to wrap a series of changes to the editor +// state in such a way that each change won't have to update the +// cursor and display (which would be awkward, slow, and +// error-prone). Instead, display updates are batched and then all +// combined and executed at once. + +var nextOpId = 0 +// Start a new operation. +function startOperation(cm) { + cm.curOp = { + cm: cm, + viewChanged: false, // Flag that indicates that lines might need to be redrawn + startHeight: cm.doc.height, // Used to detect need to update scrollbar + forceUpdate: false, // Used to force a redraw + updateInput: null, // Whether to reset the input textarea + typing: false, // Whether this reset should be careful to leave existing text (for compositing) + changeObjs: null, // Accumulated changes, for firing change events + cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on + cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already + selectionChanged: false, // Whether the selection needs to be redrawn + updateMaxLine: false, // Set when the widest line needs to be determined anew + scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet + scrollToPos: null, // Used to scroll to a specific position + focus: false, + id: ++nextOpId // Unique ID + } + pushOperation(cm.curOp) +} + +// Finish an operation, updating the display and signalling delayed events +function endOperation(cm) { + var op = cm.curOp + finishOperation(op, function (group) { + for (var i = 0; i < group.ops.length; i++) + { group.ops[i].cm.curOp = null } + endOperations(group) + }) +} + +// The DOM updates done when an operation finishes are batched so +// that the minimum number of relayouts are required. +function endOperations(group) { + var ops = group.ops + for (var i = 0; i < ops.length; i++) // Read DOM + { endOperation_R1(ops[i]) } + for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe) + { endOperation_W1(ops[i$1]) } + for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM + { endOperation_R2(ops[i$2]) } + for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe) + { endOperation_W2(ops[i$3]) } + for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM + { endOperation_finish(ops[i$4]) } +} + +function endOperation_R1(op) { + var cm = op.cm, display = cm.display + maybeClipScrollbars(cm) + if (op.updateMaxLine) { findMaxLine(cm) } + + op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null || + op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom || + op.scrollToPos.to.line >= display.viewTo) || + display.maxLineChanged && cm.options.lineWrapping + op.update = op.mustUpdate && + new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate) +} + +function endOperation_W1(op) { + op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update) +} + +function endOperation_R2(op) { + var cm = op.cm, display = cm.display + if (op.updatedDisplay) { updateHeightsInViewport(cm) } + + op.barMeasure = measureForScrollbars(cm) + + // If the max line changed since it was last measured, measure it, + // and ensure the document's width matches it. + // updateDisplay_W2 will use these properties to do the actual resizing + if (display.maxLineChanged && !cm.options.lineWrapping) { + op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3 + cm.display.sizerWidth = op.adjustWidthTo + op.barMeasure.scrollWidth = + Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth) + op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm)) + } + + if (op.updatedDisplay || op.selectionChanged) + { op.preparedSelection = display.input.prepareSelection(op.focus) } +} + +function endOperation_W2(op) { + var cm = op.cm + + if (op.adjustWidthTo != null) { + cm.display.sizer.style.minWidth = op.adjustWidthTo + "px" + if (op.maxScrollLeft < cm.doc.scrollLeft) + { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true) } + cm.display.maxLineChanged = false + } + + var takeFocus = op.focus && op.focus == activeElt() && (!document.hasFocus || document.hasFocus()) + if (op.preparedSelection) + { cm.display.input.showSelection(op.preparedSelection, takeFocus) } + if (op.updatedDisplay || op.startHeight != cm.doc.height) + { updateScrollbars(cm, op.barMeasure) } + if (op.updatedDisplay) + { setDocumentHeight(cm, op.barMeasure) } + + if (op.selectionChanged) { restartBlink(cm) } + + if (cm.state.focused && op.updateInput) + { cm.display.input.reset(op.typing) } + if (takeFocus) { ensureFocus(op.cm) } +} + +function endOperation_finish(op) { + var cm = op.cm, display = cm.display, doc = cm.doc + + if (op.updatedDisplay) { postUpdateDisplay(cm, op.update) } + + // Abort mouse wheel delta measurement, when scrolling explicitly + if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) + { display.wheelStartX = display.wheelStartY = null } + + // Propagate the scroll position to the actual DOM scroller + if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) { + doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop)) + display.scrollbars.setScrollTop(doc.scrollTop) + display.scroller.scrollTop = doc.scrollTop + } + if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) { + doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - display.scroller.clientWidth, op.scrollLeft)) + display.scrollbars.setScrollLeft(doc.scrollLeft) + display.scroller.scrollLeft = doc.scrollLeft + alignHorizontally(cm) + } + // If we need to scroll a specific position into view, do so. + if (op.scrollToPos) { + var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from), + clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin) + if (op.scrollToPos.isCursor && cm.state.focused) { maybeScrollWindow(cm, coords) } + } + + // Fire events for markers that are hidden/unidden by editing or + // undoing + var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers + if (hidden) { for (var i = 0; i < hidden.length; ++i) + { if (!hidden[i].lines.length) { signal(hidden[i], "hide") } } } + if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1) + { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide") } } } + + if (display.wrapper.offsetHeight) + { doc.scrollTop = cm.display.scroller.scrollTop } + + // Fire change events, and delayed event handlers + if (op.changeObjs) + { signal(cm, "changes", cm, op.changeObjs) } + if (op.update) + { op.update.finish() } +} + +// Run the given function in an operation +function runInOp(cm, f) { + if (cm.curOp) { return f() } + startOperation(cm) + try { return f() } + finally { endOperation(cm) } +} +// Wraps a function in an operation. Returns the wrapped function. +function operation(cm, f) { + return function() { + if (cm.curOp) { return f.apply(cm, arguments) } + startOperation(cm) + try { return f.apply(cm, arguments) } + finally { endOperation(cm) } + } +} +// Used to add methods to editor and doc instances, wrapping them in +// operations. +function methodOp(f) { + return function() { + if (this.curOp) { return f.apply(this, arguments) } + startOperation(this) + try { return f.apply(this, arguments) } + finally { endOperation(this) } + } +} +function docMethodOp(f) { + return function() { + var cm = this.cm + if (!cm || cm.curOp) { return f.apply(this, arguments) } + startOperation(cm) + try { return f.apply(this, arguments) } + finally { endOperation(cm) } + } +} + +// Updates the display.view data structure for a given change to the +// document. From and to are in pre-change coordinates. Lendiff is +// the amount of lines added or subtracted by the change. This is +// used for changes that span multiple lines, or change the way +// lines are divided into visual lines. regLineChange (below) +// registers single-line changes. +function regChange(cm, from, to, lendiff) { + if (from == null) { from = cm.doc.first } + if (to == null) { to = cm.doc.first + cm.doc.size } + if (!lendiff) { lendiff = 0 } + + var display = cm.display + if (lendiff && to < display.viewTo && + (display.updateLineNumbers == null || display.updateLineNumbers > from)) + { display.updateLineNumbers = from } + + cm.curOp.viewChanged = true + + if (from >= display.viewTo) { // Change after + if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) + { resetView(cm) } + } else if (to <= display.viewFrom) { // Change before + if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) { + resetView(cm) + } else { + display.viewFrom += lendiff + display.viewTo += lendiff + } + } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap + resetView(cm) + } else if (from <= display.viewFrom) { // Top overlap + var cut = viewCuttingPoint(cm, to, to + lendiff, 1) + if (cut) { + display.view = display.view.slice(cut.index) + display.viewFrom = cut.lineN + display.viewTo += lendiff + } else { + resetView(cm) } - - var bidi = getOrder(lineObj), dist = lineObj.text.length; - var from = lineLeft(lineObj), to = lineRight(lineObj); - var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine; - - if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1); - // Do a binary search between these bounds. - for (;;) { - if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) { - var ch = x < fromX || x - fromX <= toX - x ? from : to; - var xDiff = x - (ch == from ? fromX : toX); - while (isExtendingChar.test(lineObj.text.charAt(ch))) ++ch; - var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside, - xDiff < 0 ? -1 : xDiff ? 1 : 0); - return pos; - } - var step = Math.ceil(dist / 2), middle = from + step; - if (bidi) { - middle = from; - for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1); - } - var middleX = getX(middle); - if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;} - else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;} - } - } - - var measureText; - function textHeight(display) { - if (display.cachedTextHeight != null) return display.cachedTextHeight; - if (measureText == null) { - measureText = elt("pre"); - // Measure a bunch of lines, for browsers that compute - // fractional heights. - for (var i = 0; i < 49; ++i) { - measureText.appendChild(document.createTextNode("x")); - measureText.appendChild(elt("br")); - } - measureText.appendChild(document.createTextNode("x")); - } - removeChildrenAndAdd(display.measure, measureText); - var height = measureText.offsetHeight / 50; - if (height > 3) display.cachedTextHeight = height; - removeChildren(display.measure); - return height || 1; - } - - function charWidth(display) { - if (display.cachedCharWidth != null) return display.cachedCharWidth; - var anchor = elt("span", "x"); - var pre = elt("pre", [anchor]); - removeChildrenAndAdd(display.measure, pre); - var width = anchor.offsetWidth; - if (width > 2) display.cachedCharWidth = width; - return width || 10; - } - - // OPERATIONS - - // Operations are used to wrap changes in such a way that each - // change won't have to update the cursor and display (which would - // be awkward, slow, and error-prone), but instead updates are - // batched and then all combined and executed at once. - - var nextOpId = 0; - function startOperation(cm) { - cm.curOp = { - // An array of ranges of lines that have to be updated. See - // updateDisplay. - changes: [], - forceUpdate: false, - updateInput: null, - userSelChange: null, - textChanged: null, - selectionChanged: false, - cursorActivity: false, - updateMaxLine: false, - updateScrollPos: false, - id: ++nextOpId - }; - if (!delayedCallbackDepth++) delayedCallbacks = []; - } - - function endOperation(cm) { - var op = cm.curOp, doc = cm.doc, display = cm.display; - cm.curOp = null; - - if (op.updateMaxLine) computeMaxLength(cm); - if (display.maxLineChanged && !cm.options.lineWrapping && display.maxLine) { - var width = measureLineWidth(cm, display.maxLine); - display.sizer.style.minWidth = Math.max(0, width + 3 + scrollerCutOff) + "px"; - display.maxLineChanged = false; - var maxScrollLeft = Math.max(0, display.sizer.offsetLeft + display.sizer.offsetWidth - display.scroller.clientWidth); - if (maxScrollLeft < doc.scrollLeft && !op.updateScrollPos) - setScrollLeft(cm, Math.min(display.scroller.scrollLeft, maxScrollLeft), true); - } - var newScrollPos, updated; - if (op.updateScrollPos) { - newScrollPos = op.updateScrollPos; - } else if (op.selectionChanged && display.scroller.clientHeight) { // don't rescroll if not visible - var coords = cursorCoords(cm, doc.sel.head); - newScrollPos = calculateScrollPos(cm, coords.left, coords.top, coords.left, coords.bottom); - } - if (op.changes.length || op.forceUpdate || newScrollPos && newScrollPos.scrollTop != null) { - updated = updateDisplay(cm, op.changes, newScrollPos && newScrollPos.scrollTop, op.forceUpdate); - if (cm.display.scroller.offsetHeight) cm.doc.scrollTop = cm.display.scroller.scrollTop; - } - if (!updated && op.selectionChanged) updateSelection(cm); - if (op.updateScrollPos) { - var top = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, newScrollPos.scrollTop)); - var left = Math.max(0, Math.min(display.scroller.scrollWidth - display.scroller.clientWidth, newScrollPos.scrollLeft)); - display.scroller.scrollTop = display.scrollbarV.scrollTop = doc.scrollTop = top; - display.scroller.scrollLeft = display.scrollbarH.scrollLeft = doc.scrollLeft = left; - alignHorizontally(cm); - if (op.scrollToPos) - scrollPosIntoView(cm, clipPos(cm.doc, op.scrollToPos.from), - clipPos(cm.doc, op.scrollToPos.to), op.scrollToPos.margin); - } else if (newScrollPos) { - scrollCursorIntoView(cm); - } - if (op.selectionChanged) restartBlink(cm); - - if (cm.state.focused && op.updateInput) - resetInput(cm, op.userSelChange); - - var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers; - if (hidden) for (var i = 0; i < hidden.length; ++i) - if (!hidden[i].lines.length) signal(hidden[i], "hide"); - if (unhidden) for (var i = 0; i < unhidden.length; ++i) - if (unhidden[i].lines.length) signal(unhidden[i], "unhide"); - - var delayed; - if (!--delayedCallbackDepth) { - delayed = delayedCallbacks; - delayedCallbacks = null; - } - if (op.textChanged) - signal(cm, "change", cm, op.textChanged); - if (op.cursorActivity) signal(cm, "cursorActivity", cm); - if (delayed) for (var i = 0; i < delayed.length; ++i) delayed[i](); - } - - // Wraps a function in an operation. Returns the wrapped function. - function operation(cm1, f) { - return function() { - var cm = cm1 || this, withOp = !cm.curOp; - if (withOp) startOperation(cm); - try { var result = f.apply(cm, arguments); } - finally { if (withOp) endOperation(cm); } - return result; - }; - } - function docOperation(f) { - return function() { - var withOp = this.cm && !this.cm.curOp, result; - if (withOp) startOperation(this.cm); - try { result = f.apply(this, arguments); } - finally { if (withOp) endOperation(this.cm); } - return result; - }; - } - function runInOp(cm, f) { - var withOp = !cm.curOp, result; - if (withOp) startOperation(cm); - try { result = f(); } - finally { if (withOp) endOperation(cm); } - return result; - } - - function regChange(cm, from, to, lendiff) { - if (from == null) from = cm.doc.first; - if (to == null) to = cm.doc.first + cm.doc.size; - cm.curOp.changes.push({from: from, to: to, diff: lendiff}); - } - - // INPUT HANDLING - - function slowPoll(cm) { - if (cm.display.pollingFast) return; - cm.display.poll.set(cm.options.pollInterval, function() { - readInput(cm); - if (cm.state.focused) slowPoll(cm); - }); - } - - function fastPoll(cm) { - var missed = false; - cm.display.pollingFast = true; - function p() { - var changed = readInput(cm); - if (!changed && !missed) {missed = true; cm.display.poll.set(60, p);} - else {cm.display.pollingFast = false; slowPoll(cm);} - } - cm.display.poll.set(20, p); - } - - // prevInput is a hack to work with IME. If we reset the textarea - // on every change, that breaks IME. So we look for changes - // compared to the previous content instead. (Modern browsers have - // events that indicate IME taking place, but these are not widely - // supported or compatible enough yet to rely on.) - function readInput(cm) { - var input = cm.display.input, prevInput = cm.display.prevInput, doc = cm.doc, sel = doc.sel; - if (!cm.state.focused || hasSelection(input) || isReadOnly(cm) || cm.state.disableInput) return false; - if (cm.state.pasteIncoming && cm.state.fakedLastChar) { - input.value = input.value.substring(0, input.value.length - 1); - cm.state.fakedLastChar = false; - } - var text = input.value; - if (text == prevInput && posEq(sel.from, sel.to)) return false; - if (ie && !ie_lt9 && cm.display.inputHasSelection === text) { - resetInput(cm, true); - return false; - } - - var withOp = !cm.curOp; - if (withOp) startOperation(cm); - sel.shift = false; - var same = 0, l = Math.min(prevInput.length, text.length); - while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same; - var from = sel.from, to = sel.to; - if (same < prevInput.length) - from = Pos(from.line, from.ch - (prevInput.length - same)); - else if (cm.state.overwrite && posEq(from, to) && !cm.state.pasteIncoming) - to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + (text.length - same))); - - var updateInput = cm.curOp.updateInput; - var changeEvent = {from: from, to: to, text: splitLines(text.slice(same)), - origin: cm.state.pasteIncoming ? "paste" : "+input"}; - makeChange(cm.doc, changeEvent, "end"); - cm.curOp.updateInput = updateInput; - signalLater(cm, "inputRead", cm, changeEvent); - - if (text.length > 1000 || text.indexOf("\n") > -1) input.value = cm.display.prevInput = ""; - else cm.display.prevInput = text; - if (withOp) endOperation(cm); - cm.state.pasteIncoming = false; - return true; - } - - function resetInput(cm, user) { - var minimal, selected, doc = cm.doc; - if (!posEq(doc.sel.from, doc.sel.to)) { - cm.display.prevInput = ""; - minimal = hasCopyEvent && - (doc.sel.to.line - doc.sel.from.line > 100 || (selected = cm.getSelection()).length > 1000); - var content = minimal ? "-" : selected || cm.getSelection(); - cm.display.input.value = content; - if (cm.state.focused) selectInput(cm.display.input); - if (ie && !ie_lt9) cm.display.inputHasSelection = content; - } else if (user) { - cm.display.prevInput = cm.display.input.value = ""; - if (ie && !ie_lt9) cm.display.inputHasSelection = null; - } - cm.display.inaccurateSelection = minimal; - } - - function focusInput(cm) { - if (cm.options.readOnly != "nocursor" && (!mobile || document.activeElement != cm.display.input)) - cm.display.input.focus(); - } - - function isReadOnly(cm) { - return cm.options.readOnly || cm.doc.cantEdit; - } - - // EVENT HANDLERS - - function registerEventHandlers(cm) { - var d = cm.display; - on(d.scroller, "mousedown", operation(cm, onMouseDown)); - if (ie) - on(d.scroller, "dblclick", operation(cm, function(e) { - if (signalDOMEvent(cm, e)) return; - var pos = posFromMouse(cm, e); - if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return; - e_preventDefault(e); - var word = findWordAt(getLine(cm.doc, pos.line).text, pos); - extendSelection(cm.doc, word.from, word.to); - })); + } else if (to >= display.viewTo) { // Bottom overlap + var cut$1 = viewCuttingPoint(cm, from, from, -1) + if (cut$1) { + display.view = display.view.slice(0, cut$1.index) + display.viewTo = cut$1.lineN + } else { + resetView(cm) + } + } else { // Gap in the middle + var cutTop = viewCuttingPoint(cm, from, from, -1) + var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1) + if (cutTop && cutBot) { + display.view = display.view.slice(0, cutTop.index) + .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)) + .concat(display.view.slice(cutBot.index)) + display.viewTo += lendiff + } else { + resetView(cm) + } + } + + var ext = display.externalMeasured + if (ext) { + if (to < ext.lineN) + { ext.lineN += lendiff } + else if (from < ext.lineN + ext.size) + { display.externalMeasured = null } + } +} + +// Register a change to a single line. Type must be one of "text", +// "gutter", "class", "widget" +function regLineChange(cm, line, type) { + cm.curOp.viewChanged = true + var display = cm.display, ext = cm.display.externalMeasured + if (ext && line >= ext.lineN && line < ext.lineN + ext.size) + { display.externalMeasured = null } + + if (line < display.viewFrom || line >= display.viewTo) { return } + var lineView = display.view[findViewIndex(cm, line)] + if (lineView.node == null) { return } + var arr = lineView.changes || (lineView.changes = []) + if (indexOf(arr, type) == -1) { arr.push(type) } +} + +// Clear the view. +function resetView(cm) { + cm.display.viewFrom = cm.display.viewTo = cm.doc.first + cm.display.view = [] + cm.display.viewOffset = 0 +} + +function viewCuttingPoint(cm, oldN, newN, dir) { + var index = findViewIndex(cm, oldN), diff, view = cm.display.view + if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) + { return {index: index, lineN: newN} } + var n = cm.display.viewFrom + for (var i = 0; i < index; i++) + { n += view[i].size } + if (n != oldN) { + if (dir > 0) { + if (index == view.length - 1) { return null } + diff = (n + view[index].size) - oldN + index++ + } else { + diff = n - oldN + } + oldN += diff; newN += diff + } + while (visualLineNo(cm.doc, newN) != newN) { + if (index == (dir < 0 ? 0 : view.length - 1)) { return null } + newN += dir * view[index - (dir < 0 ? 1 : 0)].size + index += dir + } + return {index: index, lineN: newN} +} + +// Force the view to cover a given range, adding empty view element +// or clipping off existing ones as needed. +function adjustView(cm, from, to) { + var display = cm.display, view = display.view + if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) { + display.view = buildViewArray(cm, from, to) + display.viewFrom = from + } else { + if (display.viewFrom > from) + { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view) } + else if (display.viewFrom < from) + { display.view = display.view.slice(findViewIndex(cm, from)) } + display.viewFrom = from + if (display.viewTo < to) + { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)) } + else if (display.viewTo > to) + { display.view = display.view.slice(0, findViewIndex(cm, to)) } + } + display.viewTo = to +} + +// Count the number of lines in the view whose DOM representation is +// out of date (or nonexistent). +function countDirtyView(cm) { + var view = cm.display.view, dirty = 0 + for (var i = 0; i < view.length; i++) { + var lineView = view[i] + if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty } + } + return dirty +} + +// HIGHLIGHT WORKER + +function startWorker(cm, time) { + if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo) + { cm.state.highlight.set(time, bind(highlightWorker, cm)) } +} + +function highlightWorker(cm) { + var doc = cm.doc + if (doc.frontier < doc.first) { doc.frontier = doc.first } + if (doc.frontier >= cm.display.viewTo) { return } + var end = +new Date + cm.options.workTime + var state = copyState(doc.mode, getStateBefore(cm, doc.frontier)) + var changedLines = [] + + doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) { + if (doc.frontier >= cm.display.viewFrom) { // Visible + var oldStyles = line.styles, tooLong = line.text.length > cm.options.maxHighlightLength + var highlighted = highlightLine(cm, line, tooLong ? copyState(doc.mode, state) : state, true) + line.styles = highlighted.styles + var oldCls = line.styleClasses, newCls = highlighted.classes + if (newCls) { line.styleClasses = newCls } + else if (oldCls) { line.styleClasses = null } + var ischange = !oldStyles || oldStyles.length != line.styles.length || + oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass) + for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i] } + if (ischange) { changedLines.push(doc.frontier) } + line.stateAfter = tooLong ? state : copyState(doc.mode, state) + } else { + if (line.text.length <= cm.options.maxHighlightLength) + { processLine(cm, line.text, state) } + line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null + } + ++doc.frontier + if (+new Date > end) { + startWorker(cm, cm.options.workDelay) + return true + } + }) + if (changedLines.length) { runInOp(cm, function () { + for (var i = 0; i < changedLines.length; i++) + { regLineChange(cm, changedLines[i], "text") } + }) } +} + +// DISPLAY DRAWING + +var DisplayUpdate = function(cm, viewport, force) { + var display = cm.display + + this.viewport = viewport + // Store some values that we'll need later (but don't want to force a relayout for) + this.visible = visibleLines(display, cm.doc, viewport) + this.editorIsHidden = !display.wrapper.offsetWidth + this.wrapperHeight = display.wrapper.clientHeight + this.wrapperWidth = display.wrapper.clientWidth + this.oldDisplayWidth = displayWidth(cm) + this.force = force + this.dims = getDimensions(cm) + this.events = [] +}; + +DisplayUpdate.prototype.signal = function (emitter, type) { + if (hasHandler(emitter, type)) + { this.events.push(arguments) } +}; +DisplayUpdate.prototype.finish = function () { + var this$1 = this; + + for (var i = 0; i < this.events.length; i++) + { signal.apply(null, this$1.events[i]) } +}; + +function maybeClipScrollbars(cm) { + var display = cm.display + if (!display.scrollbarsClipped && display.scroller.offsetWidth) { + display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth + display.heightForcer.style.height = scrollGap(cm) + "px" + display.sizer.style.marginBottom = -display.nativeBarWidth + "px" + display.sizer.style.borderRightWidth = scrollGap(cm) + "px" + display.scrollbarsClipped = true + } +} + +// Does the actual updating of the line display. Bails out +// (returning false) when there is nothing to be done and forced is +// false. +function updateDisplayIfNeeded(cm, update) { + var display = cm.display, doc = cm.doc + + if (update.editorIsHidden) { + resetView(cm) + return false + } + + // Bail out if the visible area is already rendered and nothing changed. + if (!update.force && + update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo && + (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) && + display.renderedView == display.view && countDirtyView(cm) == 0) + { return false } + + if (maybeUpdateLineNumberWidth(cm)) { + resetView(cm) + update.dims = getDimensions(cm) + } + + // Compute a suitable new viewport (from & to) + var end = doc.first + doc.size + var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first) + var to = Math.min(end, update.visible.to + cm.options.viewportMargin) + if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom) } + if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo) } + if (sawCollapsedSpans) { + from = visualLineNo(cm.doc, from) + to = visualLineEndNo(cm.doc, to) + } + + var different = from != display.viewFrom || to != display.viewTo || + display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth + adjustView(cm, from, to) + + display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom)) + // Position the mover div to align with the current scroll position + cm.display.mover.style.top = display.viewOffset + "px" + + var toUpdate = countDirtyView(cm) + if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view && + (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) + { return false } + + // For big changes, we hide the enclosing element during the + // update, since that speeds up the operations on most browsers. + var focused = activeElt() + if (toUpdate > 4) { display.lineDiv.style.display = "none" } + patchDisplay(cm, display.updateLineNumbers, update.dims) + if (toUpdate > 4) { display.lineDiv.style.display = "" } + display.renderedView = display.view + // There might have been a widget with a focused element that got + // hidden or updated, if so re-focus it. + if (focused && activeElt() != focused && focused.offsetHeight) { focused.focus() } + + // Prevent selection and cursors from interfering with the scroll + // width and height. + removeChildren(display.cursorDiv) + removeChildren(display.selectionDiv) + display.gutters.style.height = display.sizer.style.minHeight = 0 + + if (different) { + display.lastWrapHeight = update.wrapperHeight + display.lastWrapWidth = update.wrapperWidth + startWorker(cm, 400) + } + + display.updateLineNumbers = null + + return true +} + +function postUpdateDisplay(cm, update) { + var viewport = update.viewport + + for (var first = true;; first = false) { + if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) { + // Clip forced viewport to actual scrollable area. + if (viewport && viewport.top != null) + { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)} } + // Updated line heights might result in the drawn area not + // actually covering the viewport. Keep looping until it does. + update.visible = visibleLines(cm.display, cm.doc, viewport) + if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo) + { break } + } + if (!updateDisplayIfNeeded(cm, update)) { break } + updateHeightsInViewport(cm) + var barMeasure = measureForScrollbars(cm) + updateSelection(cm) + updateScrollbars(cm, barMeasure) + setDocumentHeight(cm, barMeasure) + } + + update.signal(cm, "update", cm) + if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) { + update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo) + cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo + } +} + +function updateDisplaySimple(cm, viewport) { + var update = new DisplayUpdate(cm, viewport) + if (updateDisplayIfNeeded(cm, update)) { + updateHeightsInViewport(cm) + postUpdateDisplay(cm, update) + var barMeasure = measureForScrollbars(cm) + updateSelection(cm) + updateScrollbars(cm, barMeasure) + setDocumentHeight(cm, barMeasure) + update.finish() + } +} + +// Sync the actual display DOM structure with display.view, removing +// nodes for lines that are no longer in view, and creating the ones +// that are not there yet, and updating the ones that are out of +// date. +function patchDisplay(cm, updateNumbersFrom, dims) { + var display = cm.display, lineNumbers = cm.options.lineNumbers + var container = display.lineDiv, cur = container.firstChild + + function rm(node) { + var next = node.nextSibling + // Works around a throw-scroll bug in OS X Webkit + if (webkit && mac && cm.display.currentWheelTarget == node) + { node.style.display = "none" } else - on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); }); - on(d.lineSpace, "selectstart", function(e) { - if (!eventInWidget(d, e)) e_preventDefault(e); - }); - // Gecko browsers fire contextmenu *after* opening the menu, at - // which point we can't mess with it anymore. Context menu is - // handled in onMouseDown for Gecko. - if (!captureMiddleClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);}); - - on(d.scroller, "scroll", function() { - if (d.scroller.clientHeight) { - setScrollTop(cm, d.scroller.scrollTop); - setScrollLeft(cm, d.scroller.scrollLeft, true); - signal(cm, "scroll", cm); + { node.parentNode.removeChild(node) } + return next + } + + var view = display.view, lineN = display.viewFrom + // Loop over the elements in the view, syncing cur (the DOM nodes + // in display.lineDiv) with the view as we go. + for (var i = 0; i < view.length; i++) { + var lineView = view[i] + if (lineView.hidden) { + } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet + var node = buildLineElement(cm, lineView, lineN, dims) + container.insertBefore(node, cur) + } else { // Already drawn + while (cur != lineView.node) { cur = rm(cur) } + var updateNumber = lineNumbers && updateNumbersFrom != null && + updateNumbersFrom <= lineN && lineView.lineNumber + if (lineView.changes) { + if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false } + updateLineForChanges(cm, lineView, lineN, dims) + } + if (updateNumber) { + removeChildren(lineView.lineNumber) + lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN))) } - }); - on(d.scrollbarV, "scroll", function() { - if (d.scroller.clientHeight) setScrollTop(cm, d.scrollbarV.scrollTop); - }); - on(d.scrollbarH, "scroll", function() { - if (d.scroller.clientHeight) setScrollLeft(cm, d.scrollbarH.scrollLeft); - }); - - on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);}); - on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);}); - - function reFocus() { if (cm.state.focused) setTimeout(bind(focusInput, cm), 0); } - on(d.scrollbarH, "mousedown", reFocus); - on(d.scrollbarV, "mousedown", reFocus); - // Prevent wrapper from ever scrolling - on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; }); - - var resizeTimer; - function onResize() { - if (resizeTimer == null) resizeTimer = setTimeout(function() { - resizeTimer = null; - // Might be a text scaling operation, clear size caches. - d.cachedCharWidth = d.cachedTextHeight = knownScrollbarWidth = null; - clearCaches(cm); - runInOp(cm, bind(regChange, cm)); - }, 100); - } - on(window, "resize", onResize); - // Above handler holds on to the editor and its data structures. - // Here we poll to unregister it when the editor is no longer in - // the document, so that it can be garbage-collected. - function unregister() { - for (var p = d.wrapper.parentNode; p && p != document.body; p = p.parentNode) {} - if (p) setTimeout(unregister, 5000); - else off(window, "resize", onResize); - } - setTimeout(unregister, 5000); - - on(d.input, "keyup", operation(cm, function(e) { - if (signalDOMEvent(cm, e) || cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return; - if (e.keyCode == 16) cm.doc.sel.shift = false; - })); - on(d.input, "input", function() { - if (ie && !ie_lt9 && cm.display.inputHasSelection) cm.display.inputHasSelection = null; - fastPoll(cm); - }); - on(d.input, "keydown", operation(cm, onKeyDown)); - on(d.input, "keypress", operation(cm, onKeyPress)); - on(d.input, "focus", bind(onFocus, cm)); - on(d.input, "blur", bind(onBlur, cm)); - - function drag_(e) { - if (signalDOMEvent(cm, e) || cm.options.onDragEvent && cm.options.onDragEvent(cm, addStop(e))) return; - e_stop(e); - } - if (cm.options.dragDrop) { - on(d.scroller, "dragstart", function(e){onDragStart(cm, e);}); - on(d.scroller, "dragenter", drag_); - on(d.scroller, "dragover", drag_); - on(d.scroller, "drop", operation(cm, onDrop)); - } - on(d.scroller, "paste", function(e) { - if (eventInWidget(d, e)) return; - focusInput(cm); - fastPoll(cm); - }); - on(d.input, "paste", function() { - // Workaround for webkit bug https://bugs.webkit.org/show_bug.cgi?id=90206 - // Add a char to the end of textarea before paste occur so that - // selection doesn't span to the end of textarea. - if (webkit && !cm.state.fakedLastChar && !(new Date - cm.state.lastMiddleDown < 200)) { - var start = d.input.selectionStart, end = d.input.selectionEnd; - d.input.value += "$"; - d.input.selectionStart = start; - d.input.selectionEnd = end; - cm.state.fakedLastChar = true; + cur = lineView.node.nextSibling + } + lineN += lineView.size + } + while (cur) { cur = rm(cur) } +} + +function updateGutterSpace(cm) { + var width = cm.display.gutters.offsetWidth + cm.display.sizer.style.marginLeft = width + "px" +} + +function setDocumentHeight(cm, measure) { + cm.display.sizer.style.minHeight = measure.docHeight + "px" + cm.display.heightForcer.style.top = measure.docHeight + "px" + cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px" +} + +// Rebuild the gutter elements, ensure the margin to the left of the +// code matches their width. +function updateGutters(cm) { + var gutters = cm.display.gutters, specs = cm.options.gutters + removeChildren(gutters) + var i = 0 + for (; i < specs.length; ++i) { + var gutterClass = specs[i] + var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass)) + if (gutterClass == "CodeMirror-linenumbers") { + cm.display.lineGutter = gElt + gElt.style.width = (cm.display.lineNumWidth || 1) + "px" + } + } + gutters.style.display = i ? "" : "none" + updateGutterSpace(cm) +} + +// Make sure the gutters options contains the element +// "CodeMirror-linenumbers" when the lineNumbers option is true. +function setGuttersForLineNumbers(options) { + var found = indexOf(options.gutters, "CodeMirror-linenumbers") + if (found == -1 && options.lineNumbers) { + options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]) + } else if (found > -1 && !options.lineNumbers) { + options.gutters = options.gutters.slice(0) + options.gutters.splice(found, 1) + } +} + +// Selection objects are immutable. A new one is created every time +// the selection changes. A selection is one or more non-overlapping +// (and non-touching) ranges, sorted, and an integer that indicates +// which one is the primary selection (the one that's scrolled into +// view, that getCursor returns, etc). +function Selection(ranges, primIndex) { + this.ranges = ranges + this.primIndex = primIndex +} + +Selection.prototype = { + primary: function() { return this.ranges[this.primIndex] }, + equals: function(other) { + var this$1 = this; + + if (other == this) { return true } + if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false } + for (var i = 0; i < this.ranges.length; i++) { + var here = this$1.ranges[i], there = other.ranges[i] + if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) { return false } + } + return true + }, + deepCopy: function() { + var this$1 = this; + + var out = [] + for (var i = 0; i < this.ranges.length; i++) + { out[i] = new Range(copyPos(this$1.ranges[i].anchor), copyPos(this$1.ranges[i].head)) } + return new Selection(out, this.primIndex) + }, + somethingSelected: function() { + var this$1 = this; + + for (var i = 0; i < this.ranges.length; i++) + { if (!this$1.ranges[i].empty()) { return true } } + return false + }, + contains: function(pos, end) { + var this$1 = this; + + if (!end) { end = pos } + for (var i = 0; i < this.ranges.length; i++) { + var range = this$1.ranges[i] + if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0) + { return i } + } + return -1 + } +} + +function Range(anchor, head) { + this.anchor = anchor; this.head = head +} + +Range.prototype = { + from: function() { return minPos(this.anchor, this.head) }, + to: function() { return maxPos(this.anchor, this.head) }, + empty: function() { + return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch + } +} + +// Take an unsorted, potentially overlapping set of ranges, and +// build a selection out of it. 'Consumes' ranges array (modifying +// it). +function normalizeSelection(ranges, primIndex) { + var prim = ranges[primIndex] + ranges.sort(function (a, b) { return cmp(a.from(), b.from()); }) + primIndex = indexOf(ranges, prim) + for (var i = 1; i < ranges.length; i++) { + var cur = ranges[i], prev = ranges[i - 1] + if (cmp(prev.to(), cur.from()) >= 0) { + var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to()) + var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head + if (i <= primIndex) { --primIndex } + ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to)) + } + } + return new Selection(ranges, primIndex) +} + +function simpleSelection(anchor, head) { + return new Selection([new Range(anchor, head || anchor)], 0) +} + +// Compute the position of the end of a change (its 'to' property +// refers to the pre-change end). +function changeEnd(change) { + if (!change.text) { return change.to } + return Pos(change.from.line + change.text.length - 1, + lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)) +} + +// Adjust a position to refer to the post-change position of the +// same text, or the end of the change if the change covers it. +function adjustForChange(pos, change) { + if (cmp(pos, change.from) < 0) { return pos } + if (cmp(pos, change.to) <= 0) { return changeEnd(change) } + + var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch + if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch } + return Pos(line, ch) +} + +function computeSelAfterChange(doc, change) { + var out = [] + for (var i = 0; i < doc.sel.ranges.length; i++) { + var range = doc.sel.ranges[i] + out.push(new Range(adjustForChange(range.anchor, change), + adjustForChange(range.head, change))) + } + return normalizeSelection(out, doc.sel.primIndex) +} + +function offsetPos(pos, old, nw) { + if (pos.line == old.line) + { return Pos(nw.line, pos.ch - old.ch + nw.ch) } + else + { return Pos(nw.line + (pos.line - old.line), pos.ch) } +} + +// Used by replaceSelections to allow moving the selection to the +// start or around the replaced test. Hint may be "start" or "around". +function computeReplacedSel(doc, changes, hint) { + var out = [] + var oldPrev = Pos(doc.first, 0), newPrev = oldPrev + for (var i = 0; i < changes.length; i++) { + var change = changes[i] + var from = offsetPos(change.from, oldPrev, newPrev) + var to = offsetPos(changeEnd(change), oldPrev, newPrev) + oldPrev = change.to + newPrev = to + if (hint == "around") { + var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0 + out[i] = new Range(inv ? to : from, inv ? from : to) + } else { + out[i] = new Range(from, from) + } + } + return new Selection(out, doc.sel.primIndex) +} + +// Used to get the editor into a consistent state again when options change. + +function loadMode(cm) { + cm.doc.mode = getMode(cm.options, cm.doc.modeOption) + resetModeState(cm) +} + +function resetModeState(cm) { + cm.doc.iter(function (line) { + if (line.stateAfter) { line.stateAfter = null } + if (line.styles) { line.styles = null } + }) + cm.doc.frontier = cm.doc.first + startWorker(cm, 100) + cm.state.modeGen++ + if (cm.curOp) { regChange(cm) } +} + +// DOCUMENT DATA STRUCTURE + +// By default, updates that start and end at the beginning of a line +// are treated specially, in order to make the association of line +// widgets and marker elements with the text behave more intuitive. +function isWholeLineUpdate(doc, change) { + return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" && + (!doc.cm || doc.cm.options.wholeLineUpdateBefore) +} + +// Perform a change on the document data structure. +function updateDoc(doc, change, markedSpans, estimateHeight) { + function spansFor(n) {return markedSpans ? markedSpans[n] : null} + function update(line, text, spans) { + updateLine(line, text, spans, estimateHeight) + signalLater(line, "change", line, change) + } + function linesFor(start, end) { + var result = [] + for (var i = start; i < end; ++i) + { result.push(new Line(text[i], spansFor(i), estimateHeight)) } + return result + } + + var from = change.from, to = change.to, text = change.text + var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line) + var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line + + // Adjust the line structure + if (change.full) { + doc.insert(0, linesFor(0, text.length)) + doc.remove(text.length, doc.size - text.length) + } else if (isWholeLineUpdate(doc, change)) { + // This is a whole-line replace. Treated specially to make + // sure line objects move the way they are supposed to. + var added = linesFor(0, text.length - 1) + update(lastLine, lastLine.text, lastSpans) + if (nlines) { doc.remove(from.line, nlines) } + if (added.length) { doc.insert(from.line, added) } + } else if (firstLine == lastLine) { + if (text.length == 1) { + update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans) + } else { + var added$1 = linesFor(1, text.length - 1) + added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight)) + update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)) + doc.insert(from.line + 1, added$1) + } + } else if (text.length == 1) { + update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0)) + doc.remove(from.line + 1, nlines) + } else { + update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)) + update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans) + var added$2 = linesFor(1, text.length - 1) + if (nlines > 1) { doc.remove(from.line + 1, nlines - 1) } + doc.insert(from.line + 1, added$2) + } + + signalLater(doc, "change", doc, change) +} + +// Call f for all linked documents. +function linkedDocs(doc, f, sharedHistOnly) { + function propagate(doc, skip, sharedHist) { + if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) { + var rel = doc.linked[i] + if (rel.doc == skip) { continue } + var shared = sharedHist && rel.sharedHist + if (sharedHistOnly && !shared) { continue } + f(rel.doc, shared) + propagate(rel.doc, doc, shared) + } } + } + propagate(doc, null, true) +} + +// Attach a document to an editor. +function attachDoc(cm, doc) { + if (doc.cm) { throw new Error("This document is already in use.") } + cm.doc = doc + doc.cm = cm + estimateLineHeights(cm) + loadMode(cm) + if (!cm.options.lineWrapping) { findMaxLine(cm) } + cm.options.mode = doc.modeOption + regChange(cm) +} + +function History(startGen) { + // Arrays of change events and selections. Doing something adds an + // event to done and clears undo. Undoing moves events from done + // to undone, redoing moves them in the other direction. + this.done = []; this.undone = [] + this.undoDepth = Infinity + // Used to track when changes can be merged into a single undo + // event + this.lastModTime = this.lastSelTime = 0 + this.lastOp = this.lastSelOp = null + this.lastOrigin = this.lastSelOrigin = null + // Used by the isClean() method + this.generation = this.maxGeneration = startGen || 1 +} + +// Create a history change event from an updateDoc-style change +// object. +function historyChangeFromChange(doc, change) { + var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)} + attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1) + linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true) + return histChange +} + +// Pop all selection events off the end of a history array. Stop at +// a change event. +function clearSelectionEvents(array) { + while (array.length) { + var last = lst(array) + if (last.ranges) { array.pop() } + else { break } + } +} + +// Find the top change event in the history. Pop off selection +// events that are in the way. +function lastChangeEvent(hist, force) { + if (force) { + clearSelectionEvents(hist.done) + return lst(hist.done) + } else if (hist.done.length && !lst(hist.done).ranges) { + return lst(hist.done) + } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) { + hist.done.pop() + return lst(hist.done) + } +} + +// Register a change in the history. Merges changes that are within +// a single operation, or are close together with an origin that +// allows merging (starting with "+") into a single event. +function addChangeToHistory(doc, change, selAfter, opId) { + var hist = doc.history + hist.undone.length = 0 + var time = +new Date, cur + var last + + if ((hist.lastOp == opId || + hist.lastOrigin == change.origin && change.origin && + ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) || + change.origin.charAt(0) == "*")) && + (cur = lastChangeEvent(hist, hist.lastOp == opId))) { + // Merge this change into the last event + last = lst(cur.changes) + if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) { + // Optimized case for simple insertion -- don't want to add + // new changesets for every character typed + last.to = changeEnd(change) + } else { + // Add new sub-event + cur.changes.push(historyChangeFromChange(doc, change)) + } + } else { + // Can not be merged, start a new event. + var before = lst(hist.done) + if (!before || !before.ranges) + { pushSelectionToHistory(doc.sel, hist.done) } + cur = {changes: [historyChangeFromChange(doc, change)], + generation: hist.generation} + hist.done.push(cur) + while (hist.done.length > hist.undoDepth) { + hist.done.shift() + if (!hist.done[0].ranges) { hist.done.shift() } + } + } + hist.done.push(selAfter) + hist.generation = ++hist.maxGeneration + hist.lastModTime = hist.lastSelTime = time + hist.lastOp = hist.lastSelOp = opId + hist.lastOrigin = hist.lastSelOrigin = change.origin + + if (!last) { signal(doc, "historyAdded") } +} + +function selectionEventCanBeMerged(doc, origin, prev, sel) { + var ch = origin.charAt(0) + return ch == "*" || + ch == "+" && + prev.ranges.length == sel.ranges.length && + prev.somethingSelected() == sel.somethingSelected() && + new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500) +} + +// Called whenever the selection changes, sets the new selection as +// the pending selection in the history, and pushes the old pending +// selection into the 'done' array when it was significantly +// different (in number of selected ranges, emptiness, or time). +function addSelectionToHistory(doc, sel, opId, options) { + var hist = doc.history, origin = options && options.origin + + // A new event is started when the previous origin does not match + // the current, or the origins don't allow matching. Origins + // starting with * are always merged, those starting with + are + // merged when similar and close together in time. + if (opId == hist.lastSelOp || + (origin && hist.lastSelOrigin == origin && + (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin || + selectionEventCanBeMerged(doc, origin, lst(hist.done), sel)))) + { hist.done[hist.done.length - 1] = sel } + else + { pushSelectionToHistory(sel, hist.done) } + + hist.lastSelTime = +new Date + hist.lastSelOrigin = origin + hist.lastSelOp = opId + if (options && options.clearRedo !== false) + { clearSelectionEvents(hist.undone) } +} + +function pushSelectionToHistory(sel, dest) { + var top = lst(dest) + if (!(top && top.ranges && top.equals(sel))) + { dest.push(sel) } +} + +// Used to store marked span information in the history. +function attachLocalSpans(doc, change, from, to) { + var existing = change["spans_" + doc.id], n = 0 + doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) { + if (line.markedSpans) + { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans } + ++n + }) +} + +// When un/re-doing restores text containing marked spans, those +// that have been explicitly cleared should not be restored. +function removeClearedSpans(spans) { + if (!spans) { return null } + var out + for (var i = 0; i < spans.length; ++i) { + if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i) } } + else if (out) { out.push(spans[i]) } + } + return !out ? spans : out.length ? out : null +} + +// Retrieve and filter the old marked spans stored in a change event. +function getOldSpans(doc, change) { + var found = change["spans_" + doc.id] + if (!found) { return null } + var nw = [] + for (var i = 0; i < change.text.length; ++i) + { nw.push(removeClearedSpans(found[i])) } + return nw +} + +// Used for un/re-doing changes from the history. Combines the +// result of computing the existing spans with the set of spans that +// existed in the history (so that deleting around a span and then +// undoing brings back the span). +function mergeOldSpans(doc, change) { + var old = getOldSpans(doc, change) + var stretched = stretchSpansOverChange(doc, change) + if (!old) { return stretched } + if (!stretched) { return old } + + for (var i = 0; i < old.length; ++i) { + var oldCur = old[i], stretchCur = stretched[i] + if (oldCur && stretchCur) { + spans: for (var j = 0; j < stretchCur.length; ++j) { + var span = stretchCur[j] + for (var k = 0; k < oldCur.length; ++k) + { if (oldCur[k].marker == span.marker) { continue spans } } + oldCur.push(span) } - cm.state.pasteIncoming = true; - fastPoll(cm); - }); - - function prepareCopy() { - if (d.inaccurateSelection) { - d.prevInput = ""; - d.inaccurateSelection = false; - d.input.value = cm.getSelection(); - selectInput(d.input); + } else if (stretchCur) { + old[i] = stretchCur + } + } + return old +} + +// Used both to provide a JSON-safe object in .getHistory, and, when +// detaching a document, to split the history in two +function copyHistoryArray(events, newGroup, instantiateSel) { + var copy = [] + for (var i = 0; i < events.length; ++i) { + var event = events[i] + if (event.ranges) { + copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event) + continue + } + var changes = event.changes, newChanges = [] + copy.push({changes: newChanges}) + for (var j = 0; j < changes.length; ++j) { + var change = changes[j], m = (void 0) + newChanges.push({from: change.from, to: change.to, text: change.text}) + if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) { + if (indexOf(newGroup, Number(m[1])) > -1) { + lst(newChanges)[prop] = change[prop] + delete change[prop] + } + } } } + } + } + return copy +} + +// The 'scroll' parameter given to many of these indicated whether +// the new cursor position should be scrolled into view after +// modifying the selection. + +// If shift is held or the extend flag is set, extends a range to +// include a given position (and optionally a second position). +// Otherwise, simply returns the range between the given positions. +// Used for cursor motion and such. +function extendRange(doc, range, head, other) { + if (doc.cm && doc.cm.display.shift || doc.extend) { + var anchor = range.anchor + if (other) { + var posBefore = cmp(head, anchor) < 0 + if (posBefore != (cmp(other, anchor) < 0)) { + anchor = head + head = other + } else if (posBefore != (cmp(head, other) < 0)) { + head = other } } - on(d.input, "cut", prepareCopy); - on(d.input, "copy", prepareCopy); - - // Needed to handle Tab key in KHTML - if (khtml) on(d.sizer, "mouseup", function() { - if (document.activeElement == d.input) d.input.blur(); - focusInput(cm); - }); - } - - function eventInWidget(display, e) { - for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { - if (!n || n.ignoreEvents || n.parentNode == display.sizer && n != display.mover) return true; - } - } - - function posFromMouse(cm, e, liberal) { - var display = cm.display; - if (!liberal) { - var target = e_target(e); - if (target == display.scrollbarH || target == display.scrollbarH.firstChild || - target == display.scrollbarV || target == display.scrollbarV.firstChild || - target == display.scrollbarFiller || target == display.gutterFiller) return null; - } - var x, y, space = getRect(display.lineSpace); - // Fails unpredictably on IE[67] when mouse is dragged around quickly. - try { x = e.clientX; y = e.clientY; } catch (e) { return null; } - return coordsChar(cm, x - space.left, y - space.top); - } - - var lastClick, lastDoubleClick; - function onMouseDown(e) { - if (signalDOMEvent(this, e)) return; - var cm = this, display = cm.display, doc = cm.doc, sel = doc.sel; - sel.shift = e.shiftKey; - - if (eventInWidget(display, e)) { - if (!webkit) { - display.scroller.draggable = false; - setTimeout(function(){display.scroller.draggable = true;}, 100); - } - return; - } - if (clickInGutter(cm, e)) return; - var start = posFromMouse(cm, e); - - switch (e_button(e)) { - case 3: - if (captureMiddleClick) onContextMenu.call(cm, cm, e); - return; - case 2: - if (webkit) cm.state.lastMiddleDown = +new Date; - if (start) extendSelection(cm.doc, start); - setTimeout(bind(focusInput, cm), 20); - e_preventDefault(e); - return; - } - // For button 1, if it was clicked inside the editor - // (posFromMouse returning non-null), we have to adjust the - // selection. - if (!start) {if (e_target(e) == display.scroller) e_preventDefault(e); return;} - - if (!cm.state.focused) onFocus(cm); - - var now = +new Date, type = "single"; - if (lastDoubleClick && lastDoubleClick.time > now - 400 && posEq(lastDoubleClick.pos, start)) { - type = "triple"; - e_preventDefault(e); - setTimeout(bind(focusInput, cm), 20); - selectLine(cm, start.line); - } else if (lastClick && lastClick.time > now - 400 && posEq(lastClick.pos, start)) { - type = "double"; - lastDoubleClick = {time: now, pos: start}; - e_preventDefault(e); - var word = findWordAt(getLine(doc, start.line).text, start); - extendSelection(cm.doc, word.from, word.to); - } else { lastClick = {time: now, pos: start}; } - - var last = start; - if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) && !posEq(sel.from, sel.to) && - !posLess(start, sel.from) && !posLess(sel.to, start) && type == "single") { - var dragEnd = operation(cm, function(e2) { - if (webkit) display.scroller.draggable = false; - cm.state.draggingText = false; - off(document, "mouseup", dragEnd); - off(display.scroller, "drop", dragEnd); - if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) { - e_preventDefault(e2); - extendSelection(cm.doc, start); - focusInput(cm); + return new Range(anchor, head) + } else { + return new Range(other || head, head) + } +} + +// Extend the primary selection range, discard the rest. +function extendSelection(doc, head, other, options) { + setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options) +} + +// Extend all selections (pos is an array of selections with length +// equal the number of selections) +function extendSelections(doc, heads, options) { + var out = [] + for (var i = 0; i < doc.sel.ranges.length; i++) + { out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null) } + var newSel = normalizeSelection(out, doc.sel.primIndex) + setSelection(doc, newSel, options) +} + +// Updates a single range in the selection. +function replaceOneSelection(doc, i, range, options) { + var ranges = doc.sel.ranges.slice(0) + ranges[i] = range + setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options) +} + +// Reset the selection to a single range. +function setSimpleSelection(doc, anchor, head, options) { + setSelection(doc, simpleSelection(anchor, head), options) +} + +// Give beforeSelectionChange handlers a change to influence a +// selection update. +function filterSelectionChange(doc, sel, options) { + var obj = { + ranges: sel.ranges, + update: function(ranges) { + var this$1 = this; + + this.ranges = [] + for (var i = 0; i < ranges.length; i++) + { this$1.ranges[i] = new Range(clipPos(doc, ranges[i].anchor), + clipPos(doc, ranges[i].head)) } + }, + origin: options && options.origin + } + signal(doc, "beforeSelectionChange", doc, obj) + if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj) } + if (obj.ranges != sel.ranges) { return normalizeSelection(obj.ranges, obj.ranges.length - 1) } + else { return sel } +} + +function setSelectionReplaceHistory(doc, sel, options) { + var done = doc.history.done, last = lst(done) + if (last && last.ranges) { + done[done.length - 1] = sel + setSelectionNoUndo(doc, sel, options) + } else { + setSelection(doc, sel, options) + } +} + +// Set a new selection. +function setSelection(doc, sel, options) { + setSelectionNoUndo(doc, sel, options) + addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options) +} + +function setSelectionNoUndo(doc, sel, options) { + if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) + { sel = filterSelectionChange(doc, sel, options) } + + var bias = options && options.bias || + (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1) + setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true)) + + if (!(options && options.scroll === false) && doc.cm) + { ensureCursorVisible(doc.cm) } +} + +function setSelectionInner(doc, sel) { + if (sel.equals(doc.sel)) { return } + + doc.sel = sel + + if (doc.cm) { + doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true + signalCursorActivity(doc.cm) + } + signalLater(doc, "cursorActivity", doc) +} + +// Verify that the selection does not partially select any atomic +// marked ranges. +function reCheckSelection(doc) { + setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll) +} + +// Return a selection that does not partially select any atomic +// ranges. +function skipAtomicInSelection(doc, sel, bias, mayClear) { + var out + for (var i = 0; i < sel.ranges.length; i++) { + var range = sel.ranges[i] + var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i] + var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear) + var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear) + if (out || newAnchor != range.anchor || newHead != range.head) { + if (!out) { out = sel.ranges.slice(0, i) } + out[i] = new Range(newAnchor, newHead) + } + } + return out ? normalizeSelection(out, sel.primIndex) : sel +} + +function skipAtomicInner(doc, pos, oldPos, dir, mayClear) { + var line = getLine(doc, pos.line) + if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) { + var sp = line.markedSpans[i], m = sp.marker + if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) && + (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) { + if (mayClear) { + signal(m, "beforeCursorEnter") + if (m.explicitlyCleared) { + if (!line.markedSpans) { break } + else {--i; continue} } - }); - // Let the drag handler handle this. - if (webkit) display.scroller.draggable = true; - cm.state.draggingText = dragEnd; - // IE's approach to draggable - if (display.scroller.dragDrop) display.scroller.dragDrop(); - on(document, "mouseup", dragEnd); - on(display.scroller, "drop", dragEnd); - return; - } - e_preventDefault(e); - if (type == "single") extendSelection(cm.doc, clipPos(doc, start)); - - var startstart = sel.from, startend = sel.to, lastPos = start; - - function doSelect(cur) { - if (posEq(lastPos, cur)) return; - lastPos = cur; - - if (type == "single") { - extendSelection(cm.doc, clipPos(doc, start), cur); - return; } - - startstart = clipPos(doc, startstart); - startend = clipPos(doc, startend); - if (type == "double") { - var word = findWordAt(getLine(doc, cur.line).text, cur); - if (posLess(cur, startstart)) extendSelection(cm.doc, word.from, startend); - else extendSelection(cm.doc, startstart, word.to); - } else if (type == "triple") { - if (posLess(cur, startstart)) extendSelection(cm.doc, startend, clipPos(doc, Pos(cur.line, 0))); - else extendSelection(cm.doc, startstart, clipPos(doc, Pos(cur.line + 1, 0))); + if (!m.atomic) { continue } + + if (oldPos) { + var near = m.find(dir < 0 ? 1 : -1), diff = (void 0) + if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft) + { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null) } + if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0)) + { return skipAtomicInner(doc, near, pos, dir, mayClear) } } - } - var editorSize = getRect(display.wrapper); - // Used to ensure timeout re-tries don't fire when another extend - // happened in the meantime (clearTimeout isn't reliable -- at - // least on Chrome, the timeouts still happen even when cleared, - // if the clear happens after their scheduled firing time). - var counter = 0; - - function extend(e) { - var curCount = ++counter; - var cur = posFromMouse(cm, e, true); - if (!cur) return; - if (!posEq(cur, last)) { - if (!cm.state.focused) onFocus(cm); - last = cur; - doSelect(cur); - var visible = visibleLines(display, doc); - if (cur.line >= visible.to || cur.line < visible.from) - setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150); - } else { - var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0; - if (outside) setTimeout(operation(cm, function() { - if (counter != curCount) return; - display.scroller.scrollTop += outside; - extend(e); - }), 50); + var far = m.find(dir < 0 ? -1 : 1) + if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight) + { far = movePos(doc, far, dir, far.line == pos.line ? line : null) } + return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null + } + } } + return pos +} + +// Ensure a given position is not inside an atomic range. +function skipAtomic(doc, pos, oldPos, bias, mayClear) { + var dir = bias || 1 + var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) || + (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) || + skipAtomicInner(doc, pos, oldPos, -dir, mayClear) || + (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true)) + if (!found) { + doc.cantEdit = true + return Pos(doc.first, 0) + } + return found +} + +function movePos(doc, pos, dir, line) { + if (dir < 0 && pos.ch == 0) { + if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) } + else { return null } + } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) { + if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) } + else { return null } + } else { + return new Pos(pos.line, pos.ch + dir) + } +} + +function selectAll(cm) { + cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll) +} + +// UPDATING + +// Allow "beforeChange" event handlers to influence a change +function filterChange(doc, change, update) { + var obj = { + canceled: false, + from: change.from, + to: change.to, + text: change.text, + origin: change.origin, + cancel: function () { return obj.canceled = true; } + } + if (update) { obj.update = function (from, to, text, origin) { + if (from) { obj.from = clipPos(doc, from) } + if (to) { obj.to = clipPos(doc, to) } + if (text) { obj.text = text } + if (origin !== undefined) { obj.origin = origin } + } } + signal(doc, "beforeChange", doc, obj) + if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj) } + + if (obj.canceled) { return null } + return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin} +} + +// Apply a change to a document, and add it to the document's +// history, and propagating it to all linked documents. +function makeChange(doc, change, ignoreReadOnly) { + if (doc.cm) { + if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) } + if (doc.cm.state.suppressEdits) { return } + } + + if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) { + change = filterChange(doc, change, true) + if (!change) { return } + } + + // Possibly split or suppress the update based on the presence + // of read-only spans in its range. + var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to) + if (split) { + for (var i = split.length - 1; i >= 0; --i) + { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text}) } + } else { + makeChangeInner(doc, change) + } +} + +function makeChangeInner(doc, change) { + if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return } + var selAfter = computeSelAfterChange(doc, change) + addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN) + + makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change)) + var rebased = [] + + linkedDocs(doc, function (doc, sharedHist) { + if (!sharedHist && indexOf(rebased, doc.history) == -1) { + rebaseHist(doc.history, change) + rebased.push(doc.history) + } + makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change)) + }) +} + +// Revert a change stored in a document's history. +function makeChangeFromHistory(doc, type, allowSelectionOnly) { + if (doc.cm && doc.cm.state.suppressEdits && !allowSelectionOnly) { return } + + var hist = doc.history, event, selAfter = doc.sel + var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done + + // Verify that there is a useable event (so that ctrl-z won't + // needlessly clear selection events) + var i = 0 + for (; i < source.length; i++) { + event = source[i] + if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges) + { break } + } + if (i == source.length) { return } + hist.lastOrigin = hist.lastSelOrigin = null + + for (;;) { + event = source.pop() + if (event.ranges) { + pushSelectionToHistory(event, dest) + if (allowSelectionOnly && !event.equals(doc.sel)) { + setSelection(doc, event, {clearRedo: false}) + return } + selAfter = event } + else { break } + } - function done(e) { - counter = Infinity; - e_preventDefault(e); - focusInput(cm); - off(document, "mousemove", move); - off(document, "mouseup", up); - } + // Build up a reverse change object to add to the opposite history + // stack (redo when undoing, and vice versa). + var antiChanges = [] + pushSelectionToHistory(selAfter, dest) + dest.push({changes: antiChanges, generation: hist.generation}) + hist.generation = event.generation || ++hist.maxGeneration - var move = operation(cm, function(e) { - if (!ie && !e_button(e)) done(e); - else extend(e); - }); - var up = operation(cm, done); - on(document, "mousemove", move); - on(document, "mouseup", up); - } + var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange") - function gutterEvent(cm, e, type, prevent, signalfn) { - try { var mX = e.clientX, mY = e.clientY; } - catch(e) { return false; } - if (mX >= Math.floor(getRect(cm.display.gutters).right)) return false; - if (prevent) e_preventDefault(e); + var loop = function ( i ) { + var change = event.changes[i] + change.origin = type + if (filter && !filterChange(doc, change, false)) { + source.length = 0 + return {} + } - var display = cm.display; - var lineBox = getRect(display.lineDiv); + antiChanges.push(historyChangeFromChange(doc, change)) - if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e); - mY -= lineBox.top - display.viewOffset; + var after = i ? computeSelAfterChange(doc, change) : lst(source) + makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)) + if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}) } + var rebased = [] - for (var i = 0; i < cm.options.gutters.length; ++i) { - var g = display.gutters.childNodes[i]; - if (g && getRect(g).right >= mX) { - var line = lineAtHeight(cm.doc, mY); - var gutter = cm.options.gutters[i]; - signalfn(cm, type, cm, line, gutter, e); - return e_defaultPrevented(e); + // Propagate to the linked documents + linkedDocs(doc, function (doc, sharedHist) { + if (!sharedHist && indexOf(rebased, doc.history) == -1) { + rebaseHist(doc.history, change) + rebased.push(doc.history) } - } - } + makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change)) + }) + }; - function contextMenuInGutter(cm, e) { - if (!hasHandler(cm, "gutterContextMenu")) return false; - return gutterEvent(cm, e, "gutterContextMenu", false, signal); + for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) { + var returned = loop( i$1 ); + + if ( returned ) return returned.v; + } +} + +// Sub-views need their line numbers shifted when text is added +// above or below them in the parent document. +function shiftDoc(doc, distance) { + if (distance == 0) { return } + doc.first += distance + doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range( + Pos(range.anchor.line + distance, range.anchor.ch), + Pos(range.head.line + distance, range.head.ch) + ); }), doc.sel.primIndex) + if (doc.cm) { + regChange(doc.cm, doc.first, doc.first - distance, distance) + for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++) + { regLineChange(doc.cm, l, "gutter") } + } +} + +// More lower-level change function, handling only a single document +// (not linked ones). +function makeChangeSingleDoc(doc, change, selAfter, spans) { + if (doc.cm && !doc.cm.curOp) + { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) } + + if (change.to.line < doc.first) { + shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line)) + return + } + if (change.from.line > doc.lastLine()) { return } + + // Clip the change to the size of this doc + if (change.from.line < doc.first) { + var shift = change.text.length - 1 - (doc.first - change.from.line) + shiftDoc(doc, shift) + change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch), + text: [lst(change.text)], origin: change.origin} + } + var last = doc.lastLine() + if (change.to.line > last) { + change = {from: change.from, to: Pos(last, getLine(doc, last).text.length), + text: [change.text[0]], origin: change.origin} + } + + change.removed = getBetween(doc, change.from, change.to) + + if (!selAfter) { selAfter = computeSelAfterChange(doc, change) } + if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans) } + else { updateDoc(doc, change, spans) } + setSelectionNoUndo(doc, selAfter, sel_dontScroll) +} + +// Handle the interaction of a change to a document with the editor +// that this document is part of. +function makeChangeSingleDocInEditor(cm, change, spans) { + var doc = cm.doc, display = cm.display, from = change.from, to = change.to + + var recomputeMaxLength = false, checkWidthStart = from.line + if (!cm.options.lineWrapping) { + checkWidthStart = lineNo(visualLine(getLine(doc, from.line))) + doc.iter(checkWidthStart, to.line + 1, function (line) { + if (line == display.maxLine) { + recomputeMaxLength = true + return true + } + }) } - function clickInGutter(cm, e) { - return gutterEvent(cm, e, "gutterClick", true, signalLater); - } + if (doc.sel.contains(change.from, change.to) > -1) + { signalCursorActivity(cm) } - // Kludge to work around strange IE behavior where it'll sometimes - // re-fire a series of drag-related events right after the drop (#1551) - var lastDrop = 0; + updateDoc(doc, change, spans, estimateHeight(cm)) - function onDrop(e) { - var cm = this; - if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e) || (cm.options.onDragEvent && cm.options.onDragEvent(cm, addStop(e)))) - return; - e_preventDefault(e); - if (ie) lastDrop = +new Date; - var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files; - if (!pos || isReadOnly(cm)) return; - if (files && files.length && window.FileReader && window.File) { - var n = files.length, text = Array(n), read = 0; - var loadFile = function(file, i) { - var reader = new FileReader; - reader.onload = function() { - text[i] = reader.result; - if (++read == n) { - pos = clipPos(cm.doc, pos); - makeChange(cm.doc, {from: pos, to: pos, text: splitLines(text.join("\n")), origin: "paste"}, "around"); - } - }; - reader.readAsText(file); - }; - for (var i = 0; i < n; ++i) loadFile(files[i], i); - } else { - // Don't do a replace if the drop happened inside of the selected text. - if (cm.state.draggingText && !(posLess(pos, cm.doc.sel.from) || posLess(cm.doc.sel.to, pos))) { - cm.state.draggingText(e); - // Ensure the editor is re-focused - setTimeout(bind(focusInput, cm), 20); - return; - } - try { - var text = e.dataTransfer.getData("Text"); - if (text) { - var curFrom = cm.doc.sel.from, curTo = cm.doc.sel.to; - setSelection(cm.doc, pos, pos); - if (cm.state.draggingText) replaceRange(cm.doc, "", curFrom, curTo, "paste"); - cm.replaceSelection(text, null, "paste"); - focusInput(cm); - } + if (!cm.options.lineWrapping) { + doc.iter(checkWidthStart, from.line + change.text.length, function (line) { + var len = lineLength(line) + if (len > display.maxLineLength) { + display.maxLine = line + display.maxLineLength = len + display.maxLineChanged = true + recomputeMaxLength = false } - catch(e){} - } + }) + if (recomputeMaxLength) { cm.curOp.updateMaxLine = true } } - function onDragStart(cm, e) { - if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; } - if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return; + // Adjust frontier, schedule worker + doc.frontier = Math.min(doc.frontier, from.line) + startWorker(cm, 400) - var txt = cm.getSelection(); - e.dataTransfer.setData("Text", txt); + var lendiff = change.text.length - (to.line - from.line) - 1 + // Remember that these lines changed, for updating the display + if (change.full) + { regChange(cm) } + else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change)) + { regLineChange(cm, from.line, "text") } + else + { regChange(cm, from.line, to.line + 1, lendiff) } - // Use dummy image instead of default browsers image. - // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there. - if (e.dataTransfer.setDragImage && !safari) { - var img = elt("img", null, null, "position: fixed; left: 0; top: 0;"); - img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; - if (opera) { - img.width = img.height = 1; - cm.display.wrapper.appendChild(img); - // Force a relayout, or Opera won't use our image for some obscure reason - img._top = img.offsetTop; + var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change") + if (changeHandler || changesHandler) { + var obj = { + from: from, to: to, + text: change.text, + removed: change.removed, + origin: change.origin + } + if (changeHandler) { signalLater(cm, "change", cm, obj) } + if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj) } + } + cm.display.selForContextMenu = null +} + +function replaceRange(doc, code, from, to, origin) { + if (!to) { to = from } + if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp } + if (typeof code == "string") { code = doc.splitLines(code) } + makeChange(doc, {from: from, to: to, text: code, origin: origin}) +} + +// Rebasing/resetting history to deal with externally-sourced changes + +function rebaseHistSelSingle(pos, from, to, diff) { + if (to < pos.line) { + pos.line += diff + } else if (from < pos.line) { + pos.line = from + pos.ch = 0 + } +} + +// Tries to rebase an array of history events given a change in the +// document. If the change touches the same lines as the event, the +// event, and everything 'behind' it, is discarded. If the change is +// before the event, the event's positions are updated. Uses a +// copy-on-write scheme for the positions, to avoid having to +// reallocate them all on every rebase, but also avoid problems with +// shared position objects being unsafely updated. +function rebaseHistArray(array, from, to, diff) { + for (var i = 0; i < array.length; ++i) { + var sub = array[i], ok = true + if (sub.ranges) { + if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true } + for (var j = 0; j < sub.ranges.length; j++) { + rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff) + rebaseHistSelSingle(sub.ranges[j].head, from, to, diff) } - e.dataTransfer.setDragImage(img, 0, 0); - if (opera) img.parentNode.removeChild(img); - } - } - - function setScrollTop(cm, val) { - if (Math.abs(cm.doc.scrollTop - val) < 2) return; - cm.doc.scrollTop = val; - if (!gecko) updateDisplay(cm, [], val); - if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val; - if (cm.display.scrollbarV.scrollTop != val) cm.display.scrollbarV.scrollTop = val; - if (gecko) updateDisplay(cm, []); - startWorker(cm, 100); - } - function setScrollLeft(cm, val, isScroller) { - if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return; - val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth); - cm.doc.scrollLeft = val; - alignHorizontally(cm); - if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val; - if (cm.display.scrollbarH.scrollLeft != val) cm.display.scrollbarH.scrollLeft = val; - } - - // Since the delta values reported on mouse wheel events are - // unstandardized between browsers and even browser versions, and - // generally horribly unpredictable, this code starts by measuring - // the scroll effect that the first few mouse wheel events have, - // and, from that, detects the way it can convert deltas to pixel - // offsets afterwards. - // - // The reason we want to know the amount a wheel event will scroll - // is that it gives us a chance to update the display before the - // actual scrolling happens, reducing flickering. - - var wheelSamples = 0, wheelPixelsPerUnit = null; - // Fill in a browser-detected starting value on browsers where we - // know one. These don't have to be accurate -- the result of them - // being wrong would just be a slight flicker on the first wheel - // scroll (if it is large enough). - if (ie) wheelPixelsPerUnit = -.53; - else if (gecko) wheelPixelsPerUnit = 15; - else if (chrome) wheelPixelsPerUnit = -.7; - else if (safari) wheelPixelsPerUnit = -1/3; - - function onScrollWheel(cm, e) { - var dx = e.wheelDeltaX, dy = e.wheelDeltaY; - if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail; - if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail; - else if (dy == null) dy = e.wheelDelta; - - var display = cm.display, scroll = display.scroller; - // Quit if there's nothing to scroll here - if (!(dx && scroll.scrollWidth > scroll.clientWidth || - dy && scroll.scrollHeight > scroll.clientHeight)) return; - - // Webkit browsers on OS X abort momentum scrolls when the target - // of the scroll event is removed from the scrollable element. - // This hack (see related code in patchDisplay) makes sure the - // element is kept around. - if (dy && mac && webkit) { - for (var cur = e.target; cur != scroll; cur = cur.parentNode) { - if (cur.lineObj) { - cm.display.currentWheelTarget = cur; - break; + continue + } + for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) { + var cur = sub.changes[j$1] + if (to < cur.from.line) { + cur.from = Pos(cur.from.line + diff, cur.from.ch) + cur.to = Pos(cur.to.line + diff, cur.to.ch) + } else if (from <= cur.to.line) { + ok = false + break + } + } + if (!ok) { + array.splice(0, i + 1) + i = 0 + } + } +} + +function rebaseHist(hist, change) { + var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1 + rebaseHistArray(hist.done, from, to, diff) + rebaseHistArray(hist.undone, from, to, diff) +} + +// Utility for applying a change to a line by handle or number, +// returning the number and optionally registering the line as +// changed. +function changeLine(doc, handle, changeType, op) { + var no = handle, line = handle + if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)) } + else { no = lineNo(handle) } + if (no == null) { return null } + if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType) } + return line +} + +// The document is represented as a BTree consisting of leaves, with +// chunk of lines in them, and branches, with up to ten leaves or +// other branch nodes below them. The top node is always a branch +// node, and is the document object itself (meaning it has +// additional methods and properties). +// +// All nodes have parent links. The tree is used both to go from +// line numbers to line objects, and to go from objects to numbers. +// It also indexes by height, and is used to convert between height +// and line object, and to find the total height of the document. +// +// See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html + +function LeafChunk(lines) { + var this$1 = this; + + this.lines = lines + this.parent = null + var height = 0 + for (var i = 0; i < lines.length; ++i) { + lines[i].parent = this$1 + height += lines[i].height + } + this.height = height +} + +LeafChunk.prototype = { + chunkSize: function() { return this.lines.length }, + // Remove the n lines at offset 'at'. + removeInner: function(at, n) { + var this$1 = this; + + for (var i = at, e = at + n; i < e; ++i) { + var line = this$1.lines[i] + this$1.height -= line.height + cleanUpLine(line) + signalLater(line, "delete") + } + this.lines.splice(at, n) + }, + // Helper used to collapse a small branch into a single leaf. + collapse: function(lines) { + lines.push.apply(lines, this.lines) + }, + // Insert the given array of lines at offset 'at', count them as + // having the given height. + insertInner: function(at, lines, height) { + var this$1 = this; + + this.height += height + this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)) + for (var i = 0; i < lines.length; ++i) { lines[i].parent = this$1 } + }, + // Used to iterate over a part of the tree. + iterN: function(at, n, op) { + var this$1 = this; + + for (var e = at + n; at < e; ++at) + { if (op(this$1.lines[at])) { return true } } + } +} + +function BranchChunk(children) { + var this$1 = this; + + this.children = children + var size = 0, height = 0 + for (var i = 0; i < children.length; ++i) { + var ch = children[i] + size += ch.chunkSize(); height += ch.height + ch.parent = this$1 + } + this.size = size + this.height = height + this.parent = null +} + +BranchChunk.prototype = { + chunkSize: function() { return this.size }, + removeInner: function(at, n) { + var this$1 = this; + + this.size -= n + for (var i = 0; i < this.children.length; ++i) { + var child = this$1.children[i], sz = child.chunkSize() + if (at < sz) { + var rm = Math.min(n, sz - at), oldHeight = child.height + child.removeInner(at, rm) + this$1.height -= oldHeight - child.height + if (sz == rm) { this$1.children.splice(i--, 1); child.parent = null } + if ((n -= rm) == 0) { break } + at = 0 + } else { at -= sz } + } + // If the result is smaller than 25 lines, ensure that it is a + // single leaf node. + if (this.size - n < 25 && + (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) { + var lines = [] + this.collapse(lines) + this.children = [new LeafChunk(lines)] + this.children[0].parent = this + } + }, + collapse: function(lines) { + var this$1 = this; + + for (var i = 0; i < this.children.length; ++i) { this$1.children[i].collapse(lines) } + }, + insertInner: function(at, lines, height) { + var this$1 = this; + + this.size += lines.length + this.height += height + for (var i = 0; i < this.children.length; ++i) { + var child = this$1.children[i], sz = child.chunkSize() + if (at <= sz) { + child.insertInner(at, lines, height) + if (child.lines && child.lines.length > 50) { + // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced. + // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest. + var remaining = child.lines.length % 25 + 25 + for (var pos = remaining; pos < child.lines.length;) { + var leaf = new LeafChunk(child.lines.slice(pos, pos += 25)) + child.height -= leaf.height + this$1.children.splice(++i, 0, leaf) + leaf.parent = this$1 + } + child.lines = child.lines.slice(0, remaining) + this$1.maybeSpill() } + break } + at -= sz } - - // On some browsers, horizontal scrolling will cause redraws to - // happen before the gutter has been realigned, causing it to - // wriggle around in a most unseemly way. When we have an - // estimated pixels/delta value, we just handle horizontal - // scrolling entirely here. It'll be slightly off from native, but - // better than glitching out. - if (dx && !gecko && !opera && wheelPixelsPerUnit != null) { - if (dy) - setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight))); - setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth))); - e_preventDefault(e); - display.wheelStartX = null; // Abort measurement, if in progress - return; - } - - if (dy && wheelPixelsPerUnit != null) { - var pixels = dy * wheelPixelsPerUnit; - var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight; - if (pixels < 0) top = Math.max(0, top + pixels - 50); - else bot = Math.min(cm.doc.height, bot + pixels + 50); - updateDisplay(cm, [], {top: top, bottom: bot}); - } - - if (wheelSamples < 20) { - if (display.wheelStartX == null) { - display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop; - display.wheelDX = dx; display.wheelDY = dy; - setTimeout(function() { - if (display.wheelStartX == null) return; - var movedX = scroll.scrollLeft - display.wheelStartX; - var movedY = scroll.scrollTop - display.wheelStartY; - var sample = (movedY && display.wheelDY && movedY / display.wheelDY) || - (movedX && display.wheelDX && movedX / display.wheelDX); - display.wheelStartX = display.wheelStartY = null; - if (!sample) return; - wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1); - ++wheelSamples; - }, 200); - } else { - display.wheelDX += dx; display.wheelDY += dy; + }, + // When a node has grown, check whether it should be split. + maybeSpill: function() { + if (this.children.length <= 10) { return } + var me = this + do { + var spilled = me.children.splice(me.children.length - 5, 5) + var sibling = new BranchChunk(spilled) + if (!me.parent) { // Become the parent node + var copy = new BranchChunk(me.children) + copy.parent = me + me.children = [copy, sibling] + me = copy + } else { + me.size -= sibling.size + me.height -= sibling.height + var myIndex = indexOf(me.parent.children, me) + me.parent.children.splice(myIndex + 1, 0, sibling) + } + sibling.parent = me.parent + } while (me.children.length > 10) + me.parent.maybeSpill() + }, + iterN: function(at, n, op) { + var this$1 = this; + + for (var i = 0; i < this.children.length; ++i) { + var child = this$1.children[i], sz = child.chunkSize() + if (at < sz) { + var used = Math.min(n, sz - at) + if (child.iterN(at, used, op)) { return true } + if ((n -= used) == 0) { break } + at = 0 + } else { at -= sz } + } + } +} + +// Line widgets are block elements displayed above or below a line. + +function LineWidget(doc, node, options) { + var this$1 = this; + + if (options) { for (var opt in options) { if (options.hasOwnProperty(opt)) + { this$1[opt] = options[opt] } } } + this.doc = doc + this.node = node +} +eventMixin(LineWidget) + +function adjustScrollWhenAboveVisible(cm, line, diff) { + if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop)) + { addToScrollPos(cm, null, diff) } +} + +LineWidget.prototype.clear = function() { + var this$1 = this; + + var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line) + if (no == null || !ws) { return } + for (var i = 0; i < ws.length; ++i) { if (ws[i] == this$1) { ws.splice(i--, 1) } } + if (!ws.length) { line.widgets = null } + var height = widgetHeight(this) + updateLineHeight(line, Math.max(0, line.height - height)) + if (cm) { runInOp(cm, function () { + adjustScrollWhenAboveVisible(cm, line, -height) + regLineChange(cm, no, "widget") + }) } +} +LineWidget.prototype.changed = function() { + var oldH = this.height, cm = this.doc.cm, line = this.line + this.height = null + var diff = widgetHeight(this) - oldH + if (!diff) { return } + updateLineHeight(line, line.height + diff) + if (cm) { runInOp(cm, function () { + cm.curOp.forceUpdate = true + adjustScrollWhenAboveVisible(cm, line, diff) + }) } +} + +function addLineWidget(doc, handle, node, options) { + var widget = new LineWidget(doc, node, options) + var cm = doc.cm + if (cm && widget.noHScroll) { cm.display.alignWidgets = true } + changeLine(doc, handle, "widget", function (line) { + var widgets = line.widgets || (line.widgets = []) + if (widget.insertAt == null) { widgets.push(widget) } + else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget) } + widget.line = line + if (cm && !lineIsHidden(doc, line)) { + var aboveVisible = heightAtLine(line) < doc.scrollTop + updateLineHeight(line, line.height + widgetHeight(widget)) + if (aboveVisible) { addToScrollPos(cm, null, widget.height) } + cm.curOp.forceUpdate = true + } + return true + }) + return widget +} + +// TEXTMARKERS + +// Created with markText and setBookmark methods. A TextMarker is a +// handle that can be used to clear or find a marked position in the +// document. Line objects hold arrays (markedSpans) containing +// {from, to, marker} object pointing to such marker objects, and +// indicating that such a marker is present on that line. Multiple +// lines may point to the same marker when it spans across lines. +// The spans will have null for their from/to properties when the +// marker continues beyond the start/end of the line. Markers have +// links back to the lines they currently touch. + +// Collapsed markers have unique ids, in order to be able to order +// them, which is needed for uniquely determining an outer marker +// when they overlap (they may nest, but not partially overlap). +var nextMarkerId = 0 + +function TextMarker(doc, type) { + this.lines = [] + this.type = type + this.doc = doc + this.id = ++nextMarkerId +} +eventMixin(TextMarker) + +// Clear the marker. +TextMarker.prototype.clear = function() { + var this$1 = this; + + if (this.explicitlyCleared) { return } + var cm = this.doc.cm, withOp = cm && !cm.curOp + if (withOp) { startOperation(cm) } + if (hasHandler(this, "clear")) { + var found = this.find() + if (found) { signalLater(this, "clear", found.from, found.to) } + } + var min = null, max = null + for (var i = 0; i < this.lines.length; ++i) { + var line = this$1.lines[i] + var span = getMarkedSpanFor(line.markedSpans, this$1) + if (cm && !this$1.collapsed) { regLineChange(cm, lineNo(line), "text") } + else if (cm) { + if (span.to != null) { max = lineNo(line) } + if (span.from != null) { min = lineNo(line) } + } + line.markedSpans = removeMarkedSpan(line.markedSpans, span) + if (span.from == null && this$1.collapsed && !lineIsHidden(this$1.doc, line) && cm) + { updateLineHeight(line, textHeight(cm.display)) } + } + if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) { + var visual = visualLine(this$1.lines[i$1]), len = lineLength(visual) + if (len > cm.display.maxLineLength) { + cm.display.maxLine = visual + cm.display.maxLineLength = len + cm.display.maxLineChanged = true + } + } } + + if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1) } + this.lines.length = 0 + this.explicitlyCleared = true + if (this.atomic && this.doc.cantEdit) { + this.doc.cantEdit = false + if (cm) { reCheckSelection(cm.doc) } + } + if (cm) { signalLater(cm, "markerCleared", cm, this) } + if (withOp) { endOperation(cm) } + if (this.parent) { this.parent.clear() } +} + +// Find the position of the marker in the document. Returns a {from, +// to} object by default. Side can be passed to get a specific side +// -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the +// Pos objects returned contain a line object, rather than a line +// number (used to prevent looking up the same line twice). +TextMarker.prototype.find = function(side, lineObj) { + var this$1 = this; + + if (side == null && this.type == "bookmark") { side = 1 } + var from, to + for (var i = 0; i < this.lines.length; ++i) { + var line = this$1.lines[i] + var span = getMarkedSpanFor(line.markedSpans, this$1) + if (span.from != null) { + from = Pos(lineObj ? line : lineNo(line), span.from) + if (side == -1) { return from } + } + if (span.to != null) { + to = Pos(lineObj ? line : lineNo(line), span.to) + if (side == 1) { return to } + } + } + return from && {from: from, to: to} +} + +// Signals that the marker's widget changed, and surrounding layout +// should be recomputed. +TextMarker.prototype.changed = function() { + var pos = this.find(-1, true), widget = this, cm = this.doc.cm + if (!pos || !cm) { return } + runInOp(cm, function () { + var line = pos.line, lineN = lineNo(pos.line) + var view = findViewForLine(cm, lineN) + if (view) { + clearLineMeasurementCacheFor(view) + cm.curOp.selectionChanged = cm.curOp.forceUpdate = true + } + cm.curOp.updateMaxLine = true + if (!lineIsHidden(widget.doc, line) && widget.height != null) { + var oldHeight = widget.height + widget.height = null + var dHeight = widgetHeight(widget) - oldHeight + if (dHeight) + { updateLineHeight(line, line.height + dHeight) } + } + }) +} + +TextMarker.prototype.attachLine = function(line) { + if (!this.lines.length && this.doc.cm) { + var op = this.doc.cm.curOp + if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) + { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this) } + } + this.lines.push(line) +} +TextMarker.prototype.detachLine = function(line) { + this.lines.splice(indexOf(this.lines, line), 1) + if (!this.lines.length && this.doc.cm) { + var op = this.doc.cm.curOp + ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this) + } +} + +// Create a marker, wire it up to the right lines, and +function markText(doc, from, to, options, type) { + // Shared markers (across linked documents) are handled separately + // (markTextShared will call out to this again, once per + // document). + if (options && options.shared) { return markTextShared(doc, from, to, options, type) } + // Ensure we are in an operation. + if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) } + + var marker = new TextMarker(doc, type), diff = cmp(from, to) + if (options) { copyObj(options, marker, false) } + // Don't connect empty markers unless clearWhenEmpty is false + if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) + { return marker } + if (marker.replacedWith) { + // Showing up as a widget implies collapsed (widget replaces text) + marker.collapsed = true + marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget") + if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true") } + if (options.insertLeft) { marker.widgetNode.insertLeft = true } + } + if (marker.collapsed) { + if (conflictingCollapsedRange(doc, from.line, from, to, marker) || + from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker)) + { throw new Error("Inserting collapsed marker partially overlapping an existing one") } + seeCollapsedSpans() + } + + if (marker.addToHistory) + { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN) } + + var curLine = from.line, cm = doc.cm, updateMaxLine + doc.iter(curLine, to.line + 1, function (line) { + if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine) + { updateMaxLine = true } + if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0) } + addMarkedSpan(line, new MarkedSpan(marker, + curLine == from.line ? from.ch : null, + curLine == to.line ? to.ch : null)) + ++curLine + }) + // lineIsHidden depends on the presence of the spans, so needs a second pass + if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) { + if (lineIsHidden(doc, line)) { updateLineHeight(line, 0) } + }) } + + if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }) } + + if (marker.readOnly) { + seeReadOnlySpans() + if (doc.history.done.length || doc.history.undone.length) + { doc.clearHistory() } + } + if (marker.collapsed) { + marker.id = ++nextMarkerId + marker.atomic = true + } + if (cm) { + // Sync editor state + if (updateMaxLine) { cm.curOp.updateMaxLine = true } + if (marker.collapsed) + { regChange(cm, from.line, to.line + 1) } + else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css) + { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text") } } + if (marker.atomic) { reCheckSelection(cm.doc) } + signalLater(cm, "markerAdded", cm, marker) + } + return marker +} + +// SHARED TEXTMARKERS + +// A shared marker spans multiple linked documents. It is +// implemented as a meta-marker-object controlling multiple normal +// markers. +function SharedTextMarker(markers, primary) { + var this$1 = this; + + this.markers = markers + this.primary = primary + for (var i = 0; i < markers.length; ++i) + { markers[i].parent = this$1 } +} +eventMixin(SharedTextMarker) + +SharedTextMarker.prototype.clear = function() { + var this$1 = this; + + if (this.explicitlyCleared) { return } + this.explicitlyCleared = true + for (var i = 0; i < this.markers.length; ++i) + { this$1.markers[i].clear() } + signalLater(this, "clear") +} +SharedTextMarker.prototype.find = function(side, lineObj) { + return this.primary.find(side, lineObj) +} + +function markTextShared(doc, from, to, options, type) { + options = copyObj(options) + options.shared = false + var markers = [markText(doc, from, to, options, type)], primary = markers[0] + var widget = options.widgetNode + linkedDocs(doc, function (doc) { + if (widget) { options.widgetNode = widget.cloneNode(true) } + markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type)) + for (var i = 0; i < doc.linked.length; ++i) + { if (doc.linked[i].isParent) { return } } + primary = lst(markers) + }) + return new SharedTextMarker(markers, primary) +} + +function findSharedMarkers(doc) { + return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; }) +} + +function copySharedMarkers(doc, markers) { + for (var i = 0; i < markers.length; i++) { + var marker = markers[i], pos = marker.find() + var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to) + if (cmp(mFrom, mTo)) { + var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type) + marker.markers.push(subMark) + subMark.parent = marker + } + } +} + +function detachSharedMarkers(markers) { + var loop = function ( i ) { + var marker = markers[i], linked = [marker.primary.doc] + linkedDocs(marker.primary.doc, function (d) { return linked.push(d); }) + for (var j = 0; j < marker.markers.length; j++) { + var subMarker = marker.markers[j] + if (indexOf(linked, subMarker.doc) == -1) { + subMarker.parent = null + marker.markers.splice(j--, 1) } } - } + }; - function doHandleBinding(cm, bound, dropShift) { - if (typeof bound == "string") { - bound = commands[bound]; - if (!bound) return false; - } - // Ensure previous input has been read, so that the handler sees a - // consistent view of the document - if (cm.display.pollingFast && readInput(cm)) cm.display.pollingFast = false; - var doc = cm.doc, prevShift = doc.sel.shift, done = false; - try { - if (isReadOnly(cm)) cm.state.suppressEdits = true; - if (dropShift) doc.sel.shift = false; - done = bound(cm) != Pass; - } finally { - doc.sel.shift = prevShift; - cm.state.suppressEdits = false; - } - return done; - } - - function allKeyMaps(cm) { - var maps = cm.state.keyMaps.slice(0); - if (cm.options.extraKeys) maps.push(cm.options.extraKeys); - maps.push(cm.options.keyMap); - return maps; - } - - var maybeTransition; - function handleKeyBinding(cm, e) { - // Handle auto keymap transitions - var startMap = getKeyMap(cm.options.keyMap), next = startMap.auto; - clearTimeout(maybeTransition); - if (next && !isModifierKey(e)) maybeTransition = setTimeout(function() { - if (getKeyMap(cm.options.keyMap) == startMap) { - cm.options.keyMap = (next.call ? next.call(null, cm) : next); - keyMapChanged(cm); + for (var i = 0; i < markers.length; i++) loop( i ); +} + +var nextDocId = 0 +var Doc = function(text, mode, firstLine, lineSep) { + if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep) } + if (firstLine == null) { firstLine = 0 } + + BranchChunk.call(this, [new LeafChunk([new Line("", null)])]) + this.first = firstLine + this.scrollTop = this.scrollLeft = 0 + this.cantEdit = false + this.cleanGeneration = 1 + this.frontier = firstLine + var start = Pos(firstLine, 0) + this.sel = simpleSelection(start) + this.history = new History(null) + this.id = ++nextDocId + this.modeOption = mode + this.lineSep = lineSep + this.extend = false + + if (typeof text == "string") { text = this.splitLines(text) } + updateDoc(this, {from: start, to: start, text: text}) + setSelection(this, simpleSelection(start), sel_dontScroll) +} + +Doc.prototype = createObj(BranchChunk.prototype, { + constructor: Doc, + // Iterate over the document. Supports two forms -- with only one + // argument, it calls that for each line in the document. With + // three, it iterates over the range given by the first two (with + // the second being non-inclusive). + iter: function(from, to, op) { + if (op) { this.iterN(from - this.first, to - from, op) } + else { this.iterN(this.first, this.first + this.size, from) } + }, + + // Non-public interface for adding and removing lines. + insert: function(at, lines) { + var height = 0 + for (var i = 0; i < lines.length; ++i) { height += lines[i].height } + this.insertInner(at - this.first, lines, height) + }, + remove: function(at, n) { this.removeInner(at - this.first, n) }, + + // From here, the methods are part of the public interface. Most + // are also available from CodeMirror (editor) instances. + + getValue: function(lineSep) { + var lines = getLines(this, this.first, this.first + this.size) + if (lineSep === false) { return lines } + return lines.join(lineSep || this.lineSeparator()) + }, + setValue: docMethodOp(function(code) { + var top = Pos(this.first, 0), last = this.first + this.size - 1 + makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length), + text: this.splitLines(code), origin: "setValue", full: true}, true) + setSelection(this, simpleSelection(top)) + }), + replaceRange: function(code, from, to, origin) { + from = clipPos(this, from) + to = to ? clipPos(this, to) : from + replaceRange(this, code, from, to, origin) + }, + getRange: function(from, to, lineSep) { + var lines = getBetween(this, clipPos(this, from), clipPos(this, to)) + if (lineSep === false) { return lines } + return lines.join(lineSep || this.lineSeparator()) + }, + + getLine: function(line) {var l = this.getLineHandle(line); return l && l.text}, + + getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }}, + getLineNumber: function(line) {return lineNo(line)}, + + getLineHandleVisualStart: function(line) { + if (typeof line == "number") { line = getLine(this, line) } + return visualLine(line) + }, + + lineCount: function() {return this.size}, + firstLine: function() {return this.first}, + lastLine: function() {return this.first + this.size - 1}, + + clipPos: function(pos) {return clipPos(this, pos)}, + + getCursor: function(start) { + var range = this.sel.primary(), pos + if (start == null || start == "head") { pos = range.head } + else if (start == "anchor") { pos = range.anchor } + else if (start == "end" || start == "to" || start === false) { pos = range.to() } + else { pos = range.from() } + return pos + }, + listSelections: function() { return this.sel.ranges }, + somethingSelected: function() {return this.sel.somethingSelected()}, + + setCursor: docMethodOp(function(line, ch, options) { + setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options) + }), + setSelection: docMethodOp(function(anchor, head, options) { + setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options) + }), + extendSelection: docMethodOp(function(head, other, options) { + extendSelection(this, clipPos(this, head), other && clipPos(this, other), options) + }), + extendSelections: docMethodOp(function(heads, options) { + extendSelections(this, clipPosArray(this, heads), options) + }), + extendSelectionsBy: docMethodOp(function(f, options) { + var heads = map(this.sel.ranges, f) + extendSelections(this, clipPosArray(this, heads), options) + }), + setSelections: docMethodOp(function(ranges, primary, options) { + var this$1 = this; + + if (!ranges.length) { return } + var out = [] + for (var i = 0; i < ranges.length; i++) + { out[i] = new Range(clipPos(this$1, ranges[i].anchor), + clipPos(this$1, ranges[i].head)) } + if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex) } + setSelection(this, normalizeSelection(out, primary), options) + }), + addSelection: docMethodOp(function(anchor, head, options) { + var ranges = this.sel.ranges.slice(0) + ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor))) + setSelection(this, normalizeSelection(ranges, ranges.length - 1), options) + }), + + getSelection: function(lineSep) { + var this$1 = this; + + var ranges = this.sel.ranges, lines + for (var i = 0; i < ranges.length; i++) { + var sel = getBetween(this$1, ranges[i].from(), ranges[i].to()) + lines = lines ? lines.concat(sel) : sel + } + if (lineSep === false) { return lines } + else { return lines.join(lineSep || this.lineSeparator()) } + }, + getSelections: function(lineSep) { + var this$1 = this; + + var parts = [], ranges = this.sel.ranges + for (var i = 0; i < ranges.length; i++) { + var sel = getBetween(this$1, ranges[i].from(), ranges[i].to()) + if (lineSep !== false) { sel = sel.join(lineSep || this$1.lineSeparator()) } + parts[i] = sel + } + return parts + }, + replaceSelection: function(code, collapse, origin) { + var dup = [] + for (var i = 0; i < this.sel.ranges.length; i++) + { dup[i] = code } + this.replaceSelections(dup, collapse, origin || "+input") + }, + replaceSelections: docMethodOp(function(code, collapse, origin) { + var this$1 = this; + + var changes = [], sel = this.sel + for (var i = 0; i < sel.ranges.length; i++) { + var range = sel.ranges[i] + changes[i] = {from: range.from(), to: range.to(), text: this$1.splitLines(code[i]), origin: origin} + } + var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse) + for (var i$1 = changes.length - 1; i$1 >= 0; i$1--) + { makeChange(this$1, changes[i$1]) } + if (newSel) { setSelectionReplaceHistory(this, newSel) } + else if (this.cm) { ensureCursorVisible(this.cm) } + }), + undo: docMethodOp(function() {makeChangeFromHistory(this, "undo")}), + redo: docMethodOp(function() {makeChangeFromHistory(this, "redo")}), + undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true)}), + redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true)}), + + setExtending: function(val) {this.extend = val}, + getExtending: function() {return this.extend}, + + historySize: function() { + var hist = this.history, done = 0, undone = 0 + for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done } } + for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone } } + return {undo: done, redo: undone} + }, + clearHistory: function() {this.history = new History(this.history.maxGeneration)}, + + markClean: function() { + this.cleanGeneration = this.changeGeneration(true) + }, + changeGeneration: function(forceSplit) { + if (forceSplit) + { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null } + return this.history.generation + }, + isClean: function (gen) { + return this.history.generation == (gen || this.cleanGeneration) + }, + + getHistory: function() { + return {done: copyHistoryArray(this.history.done), + undone: copyHistoryArray(this.history.undone)} + }, + setHistory: function(histData) { + var hist = this.history = new History(this.history.maxGeneration) + hist.done = copyHistoryArray(histData.done.slice(0), null, true) + hist.undone = copyHistoryArray(histData.undone.slice(0), null, true) + }, + + setGutterMarker: docMethodOp(function(line, gutterID, value) { + return changeLine(this, line, "gutter", function (line) { + var markers = line.gutterMarkers || (line.gutterMarkers = {}) + markers[gutterID] = value + if (!value && isEmpty(markers)) { line.gutterMarkers = null } + return true + }) + }), + + clearGutter: docMethodOp(function(gutterID) { + var this$1 = this; + + var i = this.first + this.iter(function (line) { + if (line.gutterMarkers && line.gutterMarkers[gutterID]) { + changeLine(this$1, line, "gutter", function () { + line.gutterMarkers[gutterID] = null + if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null } + return true + }) } - }, 50); - - var name = keyName(e, true), handled = false; - if (!name) return false; - var keymaps = allKeyMaps(cm); - - if (e.shiftKey) { - // First try to resolve full name (including 'Shift-'). Failing - // that, see if there is a cursor-motion command (starting with - // 'go') bound to the keyname without 'Shift-'. - handled = lookupKey("Shift-" + name, keymaps, function(b) {return doHandleBinding(cm, b, true);}) - || lookupKey(name, keymaps, function(b) { - if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) - return doHandleBinding(cm, b); - }); + ++i + }) + }), + + lineInfo: function(line) { + var n + if (typeof line == "number") { + if (!isLine(this, line)) { return null } + n = line + line = getLine(this, line) + if (!line) { return null } } else { - handled = lookupKey(name, keymaps, function(b) { return doHandleBinding(cm, b); }); - } - - if (handled) { - e_preventDefault(e); - restartBlink(cm); - if (ie_lt9) { e.oldKeyCode = e.keyCode; e.keyCode = 0; } - signalLater(cm, "keyHandled", cm, name, e); - } - return handled; - } - - function handleCharBinding(cm, e, ch) { - var handled = lookupKey("'" + ch + "'", allKeyMaps(cm), - function(b) { return doHandleBinding(cm, b, true); }); - if (handled) { - e_preventDefault(e); - restartBlink(cm); - signalLater(cm, "keyHandled", cm, "'" + ch + "'", e); - } - return handled; - } - - var lastStoppedKey = null; - function onKeyDown(e) { - var cm = this; - if (!cm.state.focused) onFocus(cm); - if (signalDOMEvent(cm, e) || cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return; - if (ie && e.keyCode == 27) e.returnValue = false; - var code = e.keyCode; - // IE does strange things with escape. - cm.doc.sel.shift = code == 16 || e.shiftKey; - // First give onKeyEvent option a chance to handle this. - var handled = handleKeyBinding(cm, e); - if (opera) { - lastStoppedKey = handled ? code : null; - // Opera has no cut event... we try to at least catch the key combo - if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) - cm.replaceSelection(""); - } - } - - function onKeyPress(e) { - var cm = this; - if (signalDOMEvent(cm, e) || cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return; - var keyCode = e.keyCode, charCode = e.charCode; - if (opera && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;} - if (((opera && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(cm, e)) return; - var ch = String.fromCharCode(charCode == null ? keyCode : charCode); - if (this.options.electricChars && this.doc.mode.electricChars && - this.options.smartIndent && !isReadOnly(this) && - this.doc.mode.electricChars.indexOf(ch) > -1) - setTimeout(operation(cm, function() {indentLine(cm, cm.doc.sel.to.line, "smart");}), 75); - if (handleCharBinding(cm, e, ch)) return; - if (ie && !ie_lt9) cm.display.inputHasSelection = null; - fastPoll(cm); - } - - function onFocus(cm) { - if (cm.options.readOnly == "nocursor") return; - if (!cm.state.focused) { - signal(cm, "focus", cm); - cm.state.focused = true; - if (cm.display.wrapper.className.search(/\bCodeMirror-focused\b/) == -1) - cm.display.wrapper.className += " CodeMirror-focused"; - if (!cm.curOp) { - resetInput(cm, true); - if (webkit) setTimeout(bind(resetInput, cm, true), 0); // Issue #1730 + n = lineNo(line) + if (n == null) { return null } + } + return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers, + textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass, + widgets: line.widgets} + }, + + addLineClass: docMethodOp(function(handle, where, cls) { + return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { + var prop = where == "text" ? "textClass" + : where == "background" ? "bgClass" + : where == "gutter" ? "gutterClass" : "wrapClass" + if (!line[prop]) { line[prop] = cls } + else if (classTest(cls).test(line[prop])) { return false } + else { line[prop] += " " + cls } + return true + }) + }), + removeLineClass: docMethodOp(function(handle, where, cls) { + return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { + var prop = where == "text" ? "textClass" + : where == "background" ? "bgClass" + : where == "gutter" ? "gutterClass" : "wrapClass" + var cur = line[prop] + if (!cur) { return false } + else if (cls == null) { line[prop] = null } + else { + var found = cur.match(classTest(cls)) + if (!found) { return false } + var end = found.index + found[0].length + line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null } + return true + }) + }), + + addLineWidget: docMethodOp(function(handle, node, options) { + return addLineWidget(this, handle, node, options) + }), + removeLineWidget: function(widget) { widget.clear() }, + + markText: function(from, to, options) { + return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range") + }, + setBookmark: function(pos, options) { + var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options), + insertLeft: options && options.insertLeft, + clearWhenEmpty: false, shared: options && options.shared, + handleMouseEvents: options && options.handleMouseEvents} + pos = clipPos(this, pos) + return markText(this, pos, pos, realOpts, "bookmark") + }, + findMarksAt: function(pos) { + pos = clipPos(this, pos) + var markers = [], spans = getLine(this, pos.line).markedSpans + if (spans) { for (var i = 0; i < spans.length; ++i) { + var span = spans[i] + if ((span.from == null || span.from <= pos.ch) && + (span.to == null || span.to >= pos.ch)) + { markers.push(span.marker.parent || span.marker) } + } } + return markers + }, + findMarks: function(from, to, filter) { + from = clipPos(this, from); to = clipPos(this, to) + var found = [], lineNo = from.line + this.iter(from.line, to.line + 1, function (line) { + var spans = line.markedSpans + if (spans) { for (var i = 0; i < spans.length; i++) { + var span = spans[i] + if (!(span.to != null && lineNo == from.line && from.ch >= span.to || + span.from == null && lineNo != from.line || + span.from != null && lineNo == to.line && span.from >= to.ch) && + (!filter || filter(span.marker))) + { found.push(span.marker.parent || span.marker) } + } } + ++lineNo + }) + return found + }, + getAllMarks: function() { + var markers = [] + this.iter(function (line) { + var sps = line.markedSpans + if (sps) { for (var i = 0; i < sps.length; ++i) + { if (sps[i].from != null) { markers.push(sps[i].marker) } } } + }) + return markers + }, + + posFromIndex: function(off) { + var ch, lineNo = this.first, sepSize = this.lineSeparator().length + this.iter(function (line) { + var sz = line.text.length + sepSize + if (sz > off) { ch = off; return true } + off -= sz + ++lineNo + }) + return clipPos(this, Pos(lineNo, ch)) + }, + indexFromPos: function (coords) { + coords = clipPos(this, coords) + var index = coords.ch + if (coords.line < this.first || coords.ch < 0) { return 0 } + var sepSize = this.lineSeparator().length + this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value + index += line.text.length + sepSize + }) + return index + }, + + copy: function(copyHistory) { + var doc = new Doc(getLines(this, this.first, this.first + this.size), + this.modeOption, this.first, this.lineSep) + doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft + doc.sel = this.sel + doc.extend = false + if (copyHistory) { + doc.history.undoDepth = this.history.undoDepth + doc.setHistory(this.getHistory()) + } + return doc + }, + + linkedDoc: function(options) { + if (!options) { options = {} } + var from = this.first, to = this.first + this.size + if (options.from != null && options.from > from) { from = options.from } + if (options.to != null && options.to < to) { to = options.to } + var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep) + if (options.sharedHist) { copy.history = this.history + ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist}) + copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}] + copySharedMarkers(copy, findSharedMarkers(this)) + return copy + }, + unlinkDoc: function(other) { + var this$1 = this; + + if (other instanceof CodeMirror) { other = other.doc } + if (this.linked) { for (var i = 0; i < this.linked.length; ++i) { + var link = this$1.linked[i] + if (link.doc != other) { continue } + this$1.linked.splice(i, 1) + other.unlinkDoc(this$1) + detachSharedMarkers(findSharedMarkers(this$1)) + break + } } + // If the histories were shared, split them again + if (other.history == this.history) { + var splitIds = [other.id] + linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true) + other.history = new History(null) + other.history.done = copyHistoryArray(this.history.done, splitIds) + other.history.undone = copyHistoryArray(this.history.undone, splitIds) + } + }, + iterLinkedDocs: function(f) {linkedDocs(this, f)}, + + getMode: function() {return this.mode}, + getEditor: function() {return this.cm}, + + splitLines: function(str) { + if (this.lineSep) { return str.split(this.lineSep) } + return splitLinesAuto(str) + }, + lineSeparator: function() { return this.lineSep || "\n" } +}) + +// Public alias. +Doc.prototype.eachLine = Doc.prototype.iter + +// Kludge to work around strange IE behavior where it'll sometimes +// re-fire a series of drag-related events right after the drop (#1551) +var lastDrop = 0 + +function onDrop(e) { + var cm = this + clearDragCursor(cm) + if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) + { return } + e_preventDefault(e) + if (ie) { lastDrop = +new Date } + var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files + if (!pos || cm.isReadOnly()) { return } + // Might be a file drop, in which case we simply extract the text + // and insert it. + if (files && files.length && window.FileReader && window.File) { + var n = files.length, text = Array(n), read = 0 + var loadFile = function (file, i) { + if (cm.options.allowDropFileTypes && + indexOf(cm.options.allowDropFileTypes, file.type) == -1) + { return } + + var reader = new FileReader + reader.onload = operation(cm, function () { + var content = reader.result + if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { content = "" } + text[i] = content + if (++read == n) { + pos = clipPos(cm.doc, pos) + var change = {from: pos, to: pos, + text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())), + origin: "paste"} + makeChange(cm.doc, change) + setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change))) + } + }) + reader.readAsText(file) + } + for (var i = 0; i < n; ++i) { loadFile(files[i], i) } + } else { // Normal drop + // Don't do a replace if the drop happened inside of the selected text. + if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) { + cm.state.draggingText(e) + // Ensure the editor is re-focused + setTimeout(function () { return cm.display.input.focus(); }, 20) + return } - slowPoll(cm); - restartBlink(cm); - } - function onBlur(cm) { - if (cm.state.focused) { - signal(cm, "blur", cm); - cm.state.focused = false; - cm.display.wrapper.className = cm.display.wrapper.className.replace(" CodeMirror-focused", ""); - } - clearInterval(cm.display.blinker); - setTimeout(function() {if (!cm.state.focused) cm.doc.sel.shift = false;}, 150); - } - - var detectingSelectAll; - function onContextMenu(cm, e) { - if (signalDOMEvent(cm, e, "contextmenu")) return; - var display = cm.display, sel = cm.doc.sel; - if (eventInWidget(display, e) || contextMenuInGutter(cm, e)) return; - - var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop; - if (!pos || opera) return; // Opera is difficult. - - // Reset the current text selection only if the click is done outside of the selection - // and 'resetSelectionOnContextMenu' option is true. - var reset = cm.options.resetSelectionOnContextMenu; - if (reset && (posEq(sel.from, sel.to) || posLess(pos, sel.from) || !posLess(pos, sel.to))) - operation(cm, setSelection)(cm.doc, pos, pos); - - var oldCSS = display.input.style.cssText; - display.inputDiv.style.position = "absolute"; - display.input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) + - "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: white; outline: none;" + - "border-width: 0; outline: none; overflow: hidden; opacity: .05; -ms-opacity: .05; filter: alpha(opacity=5);"; - focusInput(cm); - resetInput(cm, true); - // Adds "Select all" to context menu in FF - if (posEq(sel.from, sel.to)) display.input.value = display.prevInput = " "; - - function prepareSelectAllHack() { - if (display.input.selectionStart != null) { - var extval = display.input.value = "\u200b" + (posEq(sel.from, sel.to) ? "" : display.input.value); - display.prevInput = "\u200b"; - display.input.selectionStart = 1; display.input.selectionEnd = extval.length; + try { + var text$1 = e.dataTransfer.getData("Text") + if (text$1) { + var selected + if (cm.state.draggingText && !cm.state.draggingText.copy) + { selected = cm.listSelections() } + setSelectionNoUndo(cm.doc, simpleSelection(pos, pos)) + if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1) + { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag") } } + cm.replaceSelection(text$1, "around", "paste") + cm.display.input.focus() } } - function rehide() { - display.inputDiv.style.position = "relative"; - display.input.style.cssText = oldCSS; - if (ie_lt9) display.scrollbarV.scrollTop = display.scroller.scrollTop = scrollPos; - slowPoll(cm); - - // Try to detect the user choosing select-all - if (display.input.selectionStart != null) { - if (!ie || ie_lt9) prepareSelectAllHack(); - clearTimeout(detectingSelectAll); - var i = 0, poll = function(){ - if (display.prevInput == " " && display.input.selectionStart == 0) - operation(cm, commands.selectAll)(cm); - else if (i++ < 10) detectingSelectAll = setTimeout(poll, 500); - else resetInput(cm); - }; - detectingSelectAll = setTimeout(poll, 200); + catch(e){} + } +} + +function onDragStart(cm, e) { + if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return } + if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return } + + e.dataTransfer.setData("Text", cm.getSelection()) + e.dataTransfer.effectAllowed = "copyMove" + + // Use dummy image instead of default browsers image. + // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there. + if (e.dataTransfer.setDragImage && !safari) { + var img = elt("img", null, null, "position: fixed; left: 0; top: 0;") + img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" + if (presto) { + img.width = img.height = 1 + cm.display.wrapper.appendChild(img) + // Force a relayout, or Opera won't use our image for some obscure reason + img._top = img.offsetTop + } + e.dataTransfer.setDragImage(img, 0, 0) + if (presto) { img.parentNode.removeChild(img) } + } +} + +function onDragOver(cm, e) { + var pos = posFromMouse(cm, e) + if (!pos) { return } + var frag = document.createDocumentFragment() + drawSelectionCursor(cm, pos, frag) + if (!cm.display.dragCursor) { + cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors") + cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv) + } + removeChildrenAndAdd(cm.display.dragCursor, frag) +} + +function clearDragCursor(cm) { + if (cm.display.dragCursor) { + cm.display.lineSpace.removeChild(cm.display.dragCursor) + cm.display.dragCursor = null + } +} + +// These must be handled carefully, because naively registering a +// handler for each editor will cause the editors to never be +// garbage collected. + +function forEachCodeMirror(f) { + if (!document.body.getElementsByClassName) { return } + var byClass = document.body.getElementsByClassName("CodeMirror") + for (var i = 0; i < byClass.length; i++) { + var cm = byClass[i].CodeMirror + if (cm) { f(cm) } + } +} + +var globalsRegistered = false +function ensureGlobalHandlers() { + if (globalsRegistered) { return } + registerGlobalHandlers() + globalsRegistered = true +} +function registerGlobalHandlers() { + // When the window resizes, we need to refresh active editors. + var resizeTimer + on(window, "resize", function () { + if (resizeTimer == null) { resizeTimer = setTimeout(function () { + resizeTimer = null + forEachCodeMirror(onResize) + }, 100) } + }) + // When the window loses focus, we want to show the editor as blurred + on(window, "blur", function () { return forEachCodeMirror(onBlur); }) +} +// Called when the window resizes +function onResize(cm) { + var d = cm.display + if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth) + { return } + // Might be a text scaling operation, clear size caches. + d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null + d.scrollbarsClipped = false + cm.setSize() +} + +var keyNames = { + 3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt", + 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End", + 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert", + 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", + 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete", + 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", + 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete", + 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert" +} + +// Number keys +for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i) } +// Alphabetic keys +for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1) } +// Function keys +for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2 } + +var keyMap = {} + +keyMap.basic = { + "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown", + "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown", + "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore", + "Tab": "defaultTab", "Shift-Tab": "indentAuto", + "Enter": "newlineAndIndent", "Insert": "toggleOverwrite", + "Esc": "singleSelection" +} +// Note that the save and find-related commands aren't defined by +// default. User code or addons can define them. Unknown commands +// are simply ignored. +keyMap.pcDefault = { + "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo", + "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown", + "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd", + "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find", + "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll", + "Ctrl-[": "indentLess", "Ctrl-]": "indentMore", + "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection", + fallthrough: "basic" +} +// Very basic readline/emacs-style bindings, which are standard on Mac. +keyMap.emacsy = { + "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown", + "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", + "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", + "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars", + "Ctrl-O": "openLine" +} +keyMap.macDefault = { + "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo", + "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft", + "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore", + "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find", + "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll", + "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight", + "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd", + fallthrough: ["basic", "emacsy"] +} +keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault + +// KEYMAP DISPATCH + +function normalizeKeyName(name) { + var parts = name.split(/-(?!$)/) + name = parts[parts.length - 1] + var alt, ctrl, shift, cmd + for (var i = 0; i < parts.length - 1; i++) { + var mod = parts[i] + if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true } + else if (/^a(lt)?$/i.test(mod)) { alt = true } + else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true } + else if (/^s(hift)?$/i.test(mod)) { shift = true } + else { throw new Error("Unrecognized modifier name: " + mod) } + } + if (alt) { name = "Alt-" + name } + if (ctrl) { name = "Ctrl-" + name } + if (cmd) { name = "Cmd-" + name } + if (shift) { name = "Shift-" + name } + return name +} + +// This is a kludge to keep keymaps mostly working as raw objects +// (backwards compatibility) while at the same time support features +// like normalization and multi-stroke key bindings. It compiles a +// new normalized keymap, and then updates the old object to reflect +// this. +function normalizeKeyMap(keymap) { + var copy = {} + for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) { + var value = keymap[keyname] + if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue } + if (value == "...") { delete keymap[keyname]; continue } + + var keys = map(keyname.split(" "), normalizeKeyName) + for (var i = 0; i < keys.length; i++) { + var val = (void 0), name = (void 0) + if (i == keys.length - 1) { + name = keys.join(" ") + val = value + } else { + name = keys.slice(0, i + 1).join(" ") + val = "..." + } + var prev = copy[name] + if (!prev) { copy[name] = val } + else if (prev != val) { throw new Error("Inconsistent bindings for " + name) } + } + delete keymap[keyname] + } } + for (var prop in copy) { keymap[prop] = copy[prop] } + return keymap +} + +function lookupKey(key, map, handle, context) { + map = getKeyMap(map) + var found = map.call ? map.call(key, context) : map[key] + if (found === false) { return "nothing" } + if (found === "...") { return "multi" } + if (found != null && handle(found)) { return "handled" } + + if (map.fallthrough) { + if (Object.prototype.toString.call(map.fallthrough) != "[object Array]") + { return lookupKey(key, map.fallthrough, handle, context) } + for (var i = 0; i < map.fallthrough.length; i++) { + var result = lookupKey(key, map.fallthrough[i], handle, context) + if (result) { return result } + } + } +} + +// Modifier key presses don't count as 'real' key presses for the +// purpose of keymap fallthrough. +function isModifierKey(value) { + var name = typeof value == "string" ? value : keyNames[value.keyCode] + return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod" +} + +// Look up the name of a key as indicated by an event object. +function keyName(event, noShift) { + if (presto && event.keyCode == 34 && event["char"]) { return false } + var base = keyNames[event.keyCode], name = base + if (name == null || event.altGraphKey) { return false } + if (event.altKey && base != "Alt") { name = "Alt-" + name } + if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name } + if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") { name = "Cmd-" + name } + if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name } + return name +} + +function getKeyMap(val) { + return typeof val == "string" ? keyMap[val] : val +} + +// Helper for deleting text near the selection(s), used to implement +// backspace, delete, and similar functionality. +function deleteNearSelection(cm, compute) { + var ranges = cm.doc.sel.ranges, kill = [] + // Build up a set of ranges to kill first, merging overlapping + // ranges. + for (var i = 0; i < ranges.length; i++) { + var toKill = compute(ranges[i]) + while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) { + var replaced = kill.pop() + if (cmp(replaced.from, toKill.from) < 0) { + toKill.from = replaced.from + break } } - - if (ie && !ie_lt9) prepareSelectAllHack(); - if (captureMiddleClick) { - e_stop(e); - var mouseup = function() { - off(window, "mouseup", mouseup); - setTimeout(rehide, 20); - }; - on(window, "mouseup", mouseup); + kill.push(toKill) + } + // Next, remove those actual ranges. + runInOp(cm, function () { + for (var i = kill.length - 1; i >= 0; i--) + { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete") } + ensureCursorVisible(cm) + }) +} + +// Commands are parameter-less actions that can be performed on an +// editor, mostly used for keybindings. +var commands = { + selectAll: selectAll, + singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); }, + killLine: function (cm) { return deleteNearSelection(cm, function (range) { + if (range.empty()) { + var len = getLine(cm.doc, range.head.line).text.length + if (range.head.ch == len && range.head.line < cm.lastLine()) + { return {from: range.head, to: Pos(range.head.line + 1, 0)} } + else + { return {from: range.head, to: Pos(range.head.line, len)} } } else { - setTimeout(rehide, 50); - } - } - - // UPDATING - - var changeEnd = CodeMirror.changeEnd = function(change) { - if (!change.text) return change.to; - return Pos(change.from.line + change.text.length - 1, - lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)); - }; + return {from: range.from(), to: range.to()} + } + }); }, + deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({ + from: Pos(range.from().line, 0), + to: clipPos(cm.doc, Pos(range.to().line + 1, 0)) + }); }); }, + delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({ + from: Pos(range.from().line, 0), to: range.from() + }); }); }, + delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { + var top = cm.charCoords(range.head, "div").top + 5 + var leftPos = cm.coordsChar({left: 0, top: top}, "div") + return {from: leftPos, to: range.from()} + }); }, + delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) { + var top = cm.charCoords(range.head, "div").top + 5 + var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div") + return {from: range.from(), to: rightPos } + }); }, + undo: function (cm) { return cm.undo(); }, + redo: function (cm) { return cm.redo(); }, + undoSelection: function (cm) { return cm.undoSelection(); }, + redoSelection: function (cm) { return cm.redoSelection(); }, + goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); }, + goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); }, + goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); }, + {origin: "+move", bias: 1} + ); }, + goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); }, + {origin: "+move", bias: 1} + ); }, + goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); }, + {origin: "+move", bias: -1} + ); }, + goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) { + var top = cm.charCoords(range.head, "div").top + 5 + return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div") + }, sel_move); }, + goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) { + var top = cm.charCoords(range.head, "div").top + 5 + return cm.coordsChar({left: 0, top: top}, "div") + }, sel_move); }, + goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) { + var top = cm.charCoords(range.head, "div").top + 5 + var pos = cm.coordsChar({left: 0, top: top}, "div") + if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) } + return pos + }, sel_move); }, + goLineUp: function (cm) { return cm.moveV(-1, "line"); }, + goLineDown: function (cm) { return cm.moveV(1, "line"); }, + goPageUp: function (cm) { return cm.moveV(-1, "page"); }, + goPageDown: function (cm) { return cm.moveV(1, "page"); }, + goCharLeft: function (cm) { return cm.moveH(-1, "char"); }, + goCharRight: function (cm) { return cm.moveH(1, "char"); }, + goColumnLeft: function (cm) { return cm.moveH(-1, "column"); }, + goColumnRight: function (cm) { return cm.moveH(1, "column"); }, + goWordLeft: function (cm) { return cm.moveH(-1, "word"); }, + goGroupRight: function (cm) { return cm.moveH(1, "group"); }, + goGroupLeft: function (cm) { return cm.moveH(-1, "group"); }, + goWordRight: function (cm) { return cm.moveH(1, "word"); }, + delCharBefore: function (cm) { return cm.deleteH(-1, "char"); }, + delCharAfter: function (cm) { return cm.deleteH(1, "char"); }, + delWordBefore: function (cm) { return cm.deleteH(-1, "word"); }, + delWordAfter: function (cm) { return cm.deleteH(1, "word"); }, + delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); }, + delGroupAfter: function (cm) { return cm.deleteH(1, "group"); }, + indentAuto: function (cm) { return cm.indentSelection("smart"); }, + indentMore: function (cm) { return cm.indentSelection("add"); }, + indentLess: function (cm) { return cm.indentSelection("subtract"); }, + insertTab: function (cm) { return cm.replaceSelection("\t"); }, + insertSoftTab: function (cm) { + var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize + for (var i = 0; i < ranges.length; i++) { + var pos = ranges[i].from() + var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize) + spaces.push(spaceStr(tabSize - col % tabSize)) + } + cm.replaceSelections(spaces) + }, + defaultTab: function (cm) { + if (cm.somethingSelected()) { cm.indentSelection("add") } + else { cm.execCommand("insertTab") } + }, + // Swap the two chars left and right of each selection's head. + // Move cursor behind the two swapped characters afterwards. + // + // Doesn't consider line feeds a character. + // Doesn't scan more than one line above to find a character. + // Doesn't do anything on an empty line. + // Doesn't do anything with non-empty selections. + transposeChars: function (cm) { return runInOp(cm, function () { + var ranges = cm.listSelections(), newSel = [] + for (var i = 0; i < ranges.length; i++) { + if (!ranges[i].empty()) { continue } + var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text + if (line) { + if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1) } + if (cur.ch > 0) { + cur = new Pos(cur.line, cur.ch + 1) + cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2), + Pos(cur.line, cur.ch - 2), cur, "+transpose") + } else if (cur.line > cm.doc.first) { + var prev = getLine(cm.doc, cur.line - 1).text + if (prev) { + cur = new Pos(cur.line, 1) + cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() + + prev.charAt(prev.length - 1), + Pos(cur.line - 1, prev.length - 1), cur, "+transpose") + } + } + } + newSel.push(new Range(cur, cur)) + } + cm.setSelections(newSel) + }); }, + newlineAndIndent: function (cm) { return runInOp(cm, function () { + var sels = cm.listSelections() + for (var i = sels.length - 1; i >= 0; i--) + { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input") } + sels = cm.listSelections() + for (var i$1 = 0; i$1 < sels.length; i$1++) + { cm.indentLine(sels[i$1].from().line, null, true) } + ensureCursorVisible(cm) + }); }, + openLine: function (cm) { return cm.replaceSelection("\n", "start"); }, + toggleOverwrite: function (cm) { return cm.toggleOverwrite(); } +} + + +function lineStart(cm, lineN) { + var line = getLine(cm.doc, lineN) + var visual = visualLine(line) + if (visual != line) { lineN = lineNo(visual) } + var order = getOrder(visual) + var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual) + return Pos(lineN, ch) +} +function lineEnd(cm, lineN) { + var merged, line = getLine(cm.doc, lineN) + while (merged = collapsedSpanAtEnd(line)) { + line = merged.find(1, true).line + lineN = null + } + var order = getOrder(line) + var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line) + return Pos(lineN == null ? lineNo(line) : lineN, ch) +} +function lineStartSmart(cm, pos) { + var start = lineStart(cm, pos.line) + var line = getLine(cm.doc, start.line) + var order = getOrder(line) + if (!order || order[0].level == 0) { + var firstNonWS = Math.max(0, line.text.search(/\S/)) + var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch + return Pos(start.line, inWS ? 0 : firstNonWS) + } + return start +} + +// Run a handler that was bound to a key. +function doHandleBinding(cm, bound, dropShift) { + if (typeof bound == "string") { + bound = commands[bound] + if (!bound) { return false } + } + // Ensure previous input has been read, so that the handler sees a + // consistent view of the document + cm.display.input.ensurePolled() + var prevShift = cm.display.shift, done = false + try { + if (cm.isReadOnly()) { cm.state.suppressEdits = true } + if (dropShift) { cm.display.shift = false } + done = bound(cm) != Pass + } finally { + cm.display.shift = prevShift + cm.state.suppressEdits = false + } + return done +} + +function lookupKeyForEditor(cm, name, handle) { + for (var i = 0; i < cm.state.keyMaps.length; i++) { + var result = lookupKey(name, cm.state.keyMaps[i], handle, cm) + if (result) { return result } + } + return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm)) + || lookupKey(name, cm.options.keyMap, handle, cm) +} + +var stopSeq = new Delayed +function dispatchKey(cm, name, e, handle) { + var seq = cm.state.keySeq + if (seq) { + if (isModifierKey(name)) { return "handled" } + stopSeq.set(50, function () { + if (cm.state.keySeq == seq) { + cm.state.keySeq = null + cm.display.input.reset() + } + }) + name = seq + " " + name + } + var result = lookupKeyForEditor(cm, name, handle) + + if (result == "multi") + { cm.state.keySeq = name } + if (result == "handled") + { signalLater(cm, "keyHandled", cm, name, e) } + + if (result == "handled" || result == "multi") { + e_preventDefault(e) + restartBlink(cm) + } + + if (seq && !result && /\'$/.test(name)) { + e_preventDefault(e) + return true + } + return !!result +} + +// Handle a key from the keydown event. +function handleKeyBinding(cm, e) { + var name = keyName(e, true) + if (!name) { return false } + + if (e.shiftKey && !cm.state.keySeq) { + // First try to resolve full name (including 'Shift-'). Failing + // that, see if there is a cursor-motion command (starting with + // 'go') bound to the keyname without 'Shift-'. + return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); }) + || dispatchKey(cm, name, e, function (b) { + if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) + { return doHandleBinding(cm, b) } + }) + } else { + return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); }) + } +} + +// Handle a key from the keypress event +function handleCharBinding(cm, e, ch) { + return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); }) +} + +var lastStoppedKey = null +function onKeyDown(e) { + var cm = this + cm.curOp.focus = activeElt() + if (signalDOMEvent(cm, e)) { return } + // IE does strange things with escape. + if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false } + var code = e.keyCode + cm.display.shift = code == 16 || e.shiftKey + var handled = handleKeyBinding(cm, e) + if (presto) { + lastStoppedKey = handled ? code : null + // Opera has no cut event... we try to at least catch the key combo + if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) + { cm.replaceSelection("", null, "cut") } + } + + // Turn mouse into crosshair when Alt is held on Mac. + if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) + { showCrossHair(cm) } +} + +function showCrossHair(cm) { + var lineDiv = cm.display.lineDiv + addClass(lineDiv, "CodeMirror-crosshair") + + function up(e) { + if (e.keyCode == 18 || !e.altKey) { + rmClass(lineDiv, "CodeMirror-crosshair") + off(document, "keyup", up) + off(document, "mouseover", up) + } + } + on(document, "keyup", up) + on(document, "mouseover", up) +} + +function onKeyUp(e) { + if (e.keyCode == 16) { this.doc.sel.shift = false } + signalDOMEvent(this, e) +} + +function onKeyPress(e) { + var cm = this + if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return } + var keyCode = e.keyCode, charCode = e.charCode + if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return} + if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return } + var ch = String.fromCharCode(charCode == null ? keyCode : charCode) + // Some browsers fire keypress events for backspace + if (ch == "\x08") { return } + if (handleCharBinding(cm, e, ch)) { return } + cm.display.input.onKeyPress(e) +} + +// A mouse down can be a single click, double click, triple click, +// start of selection drag, start of text drag, new cursor +// (ctrl-click), rectangle drag (alt-drag), or xwin +// middle-click-paste. Or it might be a click on something we should +// not interfere with, such as a scrollbar or widget. +function onMouseDown(e) { + var cm = this, display = cm.display + if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return } + display.input.ensurePolled() + display.shift = e.shiftKey + + if (eventInWidget(display, e)) { + if (!webkit) { + // Briefly turn off draggability, to allow widgets to do + // normal dragging things. + display.scroller.draggable = false + setTimeout(function () { return display.scroller.draggable = true; }, 100) + } + return + } + if (clickInGutter(cm, e)) { return } + var start = posFromMouse(cm, e) + window.focus() + + switch (e_button(e)) { + case 1: + // #3261: make sure, that we're not starting a second selection + if (cm.state.selectingText) + { cm.state.selectingText(e) } + else if (start) + { leftButtonDown(cm, e, start) } + else if (e_target(e) == display.scroller) + { e_preventDefault(e) } + break + case 2: + if (webkit) { cm.state.lastMiddleDown = +new Date } + if (start) { extendSelection(cm.doc, start) } + setTimeout(function () { return display.input.focus(); }, 20) + e_preventDefault(e) + break + case 3: + if (captureRightClick) { onContextMenu(cm, e) } + else { delayBlurEvent(cm) } + break + } +} + +var lastClick; +var lastDoubleClick; +function leftButtonDown(cm, e, start) { + if (ie) { setTimeout(bind(ensureFocus, cm), 0) } + else { cm.curOp.focus = activeElt() } + + var now = +new Date, type + if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) { + type = "triple" + } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) { + type = "double" + lastDoubleClick = {time: now, pos: start} + } else { + type = "single" + lastClick = {time: now, pos: start} + } + + var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained + if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() && + type == "single" && (contained = sel.contains(start)) > -1 && + (cmp((contained = sel.ranges[contained]).from(), start) < 0 || start.xRel > 0) && + (cmp(contained.to(), start) > 0 || start.xRel < 0)) + { leftButtonStartDrag(cm, e, start, modifier) } + else + { leftButtonSelect(cm, e, start, type, modifier) } +} + +// Start a text drag. When it ends, see if any dragging actually +// happen, and treat as a click if it didn't. +function leftButtonStartDrag(cm, e, start, modifier) { + var display = cm.display, startTime = +new Date + var dragEnd = operation(cm, function (e2) { + if (webkit) { display.scroller.draggable = false } + cm.state.draggingText = false + off(document, "mouseup", dragEnd) + off(display.scroller, "drop", dragEnd) + if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) { + e_preventDefault(e2) + if (!modifier && +new Date - 200 < startTime) + { extendSelection(cm.doc, start) } + // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081) + if (webkit || ie && ie_version == 9) + { setTimeout(function () {document.body.focus(); display.input.focus()}, 20) } + else + { display.input.focus() } + } + }) + // Let the drag handler handle this. + if (webkit) { display.scroller.draggable = true } + cm.state.draggingText = dragEnd + dragEnd.copy = mac ? e.altKey : e.ctrlKey + // IE's approach to draggable + if (display.scroller.dragDrop) { display.scroller.dragDrop() } + on(document, "mouseup", dragEnd) + on(display.scroller, "drop", dragEnd) +} + +// Normal selection, as opposed to text dragging. +function leftButtonSelect(cm, e, start, type, addNew) { + var display = cm.display, doc = cm.doc + e_preventDefault(e) + + var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges + if (addNew && !e.shiftKey) { + ourIndex = doc.sel.contains(start) + if (ourIndex > -1) + { ourRange = ranges[ourIndex] } + else + { ourRange = new Range(start, start) } + } else { + ourRange = doc.sel.primary() + ourIndex = doc.sel.primIndex + } + + if (chromeOS ? e.shiftKey && e.metaKey : e.altKey) { + type = "rect" + if (!addNew) { ourRange = new Range(start, start) } + start = posFromMouse(cm, e, true, true) + ourIndex = -1 + } else if (type == "double") { + var word = cm.findWordAt(start) + if (cm.display.shift || doc.extend) + { ourRange = extendRange(doc, ourRange, word.anchor, word.head) } + else + { ourRange = word } + } else if (type == "triple") { + var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0))) + if (cm.display.shift || doc.extend) + { ourRange = extendRange(doc, ourRange, line.anchor, line.head) } + else + { ourRange = line } + } else { + ourRange = extendRange(doc, ourRange, start) + } + + if (!addNew) { + ourIndex = 0 + setSelection(doc, new Selection([ourRange], 0), sel_mouse) + startSel = doc.sel + } else if (ourIndex == -1) { + ourIndex = ranges.length + setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex), + {scroll: false, origin: "*mouse"}) + } else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single" && !e.shiftKey) { + setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0), + {scroll: false, origin: "*mouse"}) + startSel = doc.sel + } else { + replaceOneSelection(doc, ourIndex, ourRange, sel_mouse) + } + + var lastPos = start + function extendTo(pos) { + if (cmp(lastPos, pos) == 0) { return } + lastPos = pos + + if (type == "rect") { + var ranges = [], tabSize = cm.options.tabSize + var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize) + var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize) + var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol) + for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line)); + line <= end; line++) { + var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize) + if (left == right) + { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))) } + else if (text.length > leftPos) + { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))) } + } + if (!ranges.length) { ranges.push(new Range(start, start)) } + setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex), + {origin: "*mouse", scroll: false}) + cm.scrollIntoView(pos) + } else { + var oldRange = ourRange + var anchor = oldRange.anchor, head = pos + if (type != "single") { + var range + if (type == "double") + { range = cm.findWordAt(pos) } + else + { range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0))) } + if (cmp(range.anchor, anchor) > 0) { + head = range.head + anchor = minPos(oldRange.from(), range.anchor) + } else { + head = range.anchor + anchor = maxPos(oldRange.to(), range.head) + } + } + var ranges$1 = startSel.ranges.slice(0) + ranges$1[ourIndex] = new Range(clipPos(doc, anchor), head) + setSelection(doc, normalizeSelection(ranges$1, ourIndex), sel_mouse) + } + } + + var editorSize = display.wrapper.getBoundingClientRect() + // Used to ensure timeout re-tries don't fire when another extend + // happened in the meantime (clearTimeout isn't reliable -- at + // least on Chrome, the timeouts still happen even when cleared, + // if the clear happens after their scheduled firing time). + var counter = 0 + + function extend(e) { + var curCount = ++counter + var cur = posFromMouse(cm, e, true, type == "rect") + if (!cur) { return } + if (cmp(cur, lastPos) != 0) { + cm.curOp.focus = activeElt() + extendTo(cur) + var visible = visibleLines(display, doc) + if (cur.line >= visible.to || cur.line < visible.from) + { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e) }}), 150) } + } else { + var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0 + if (outside) { setTimeout(operation(cm, function () { + if (counter != curCount) { return } + display.scroller.scrollTop += outside + extend(e) + }), 50) } + } + } + + function done(e) { + cm.state.selectingText = false + counter = Infinity + e_preventDefault(e) + display.input.focus() + off(document, "mousemove", move) + off(document, "mouseup", up) + doc.history.lastSelOrigin = null + } + + var move = operation(cm, function (e) { + if (!e_button(e)) { done(e) } + else { extend(e) } + }) + var up = operation(cm, done) + cm.state.selectingText = up + on(document, "mousemove", move) + on(document, "mouseup", up) +} + + +// Determines whether an event happened in the gutter, and fires the +// handlers for the corresponding event. +function gutterEvent(cm, e, type, prevent) { + var mX, mY + try { mX = e.clientX; mY = e.clientY } + catch(e) { return false } + if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false } + if (prevent) { e_preventDefault(e) } + + var display = cm.display + var lineBox = display.lineDiv.getBoundingClientRect() + + if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) } + mY -= lineBox.top - display.viewOffset + + for (var i = 0; i < cm.options.gutters.length; ++i) { + var g = display.gutters.childNodes[i] + if (g && g.getBoundingClientRect().right >= mX) { + var line = lineAtHeight(cm.doc, mY) + var gutter = cm.options.gutters[i] + signal(cm, type, cm, line, gutter, e) + return e_defaultPrevented(e) + } + } +} + +function clickInGutter(cm, e) { + return gutterEvent(cm, e, "gutterClick", true) +} + +// CONTEXT MENU HANDLING + +// To make the context menu work, we need to briefly unhide the +// textarea (making it as unobtrusive as possible) to let the +// right-click take effect on it. +function onContextMenu(cm, e) { + if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return } + if (signalDOMEvent(cm, e, "contextmenu")) { return } + cm.display.input.onContextMenu(e) +} + +function contextMenuInGutter(cm, e) { + if (!hasHandler(cm, "gutterContextMenu")) { return false } + return gutterEvent(cm, e, "gutterContextMenu", false) +} + +function themeChanged(cm) { + cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + + cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-") + clearCaches(cm) +} + +var Init = {toString: function(){return "CodeMirror.Init"}} + +var defaults = {} +var optionHandlers = {} + +function defineOptions(CodeMirror) { + var optionHandlers = CodeMirror.optionHandlers - // Make sure a position will be valid after the given change. - function clipPostChange(doc, change, pos) { - if (!posLess(change.from, pos)) return clipPos(doc, pos); - var diff = (change.text.length - 1) - (change.to.line - change.from.line); - if (pos.line > change.to.line + diff) { - var preLine = pos.line - diff, lastLine = doc.first + doc.size - 1; - if (preLine > lastLine) return Pos(lastLine, getLine(doc, lastLine).text.length); - return clipToLen(pos, getLine(doc, preLine).text.length); - } - if (pos.line == change.to.line + diff) - return clipToLen(pos, lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0) + - getLine(doc, change.to.line).text.length - change.to.ch); - var inside = pos.line - change.from.line; - return clipToLen(pos, change.text[inside].length + (inside ? 0 : change.from.ch)); + function option(name, deflt, handle, notOnInit) { + CodeMirror.defaults[name] = deflt + if (handle) { optionHandlers[name] = + notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old) }} : handle } } - // Hint can be null|"end"|"start"|"around"|{anchor,head} - function computeSelAfterChange(doc, change, hint) { - if (hint && typeof hint == "object") // Assumed to be {anchor, head} object - return {anchor: clipPostChange(doc, change, hint.anchor), - head: clipPostChange(doc, change, hint.head)}; - - if (hint == "start") return {anchor: change.from, head: change.from}; - - var end = changeEnd(change); - if (hint == "around") return {anchor: change.from, head: end}; - if (hint == "end") return {anchor: end, head: end}; + CodeMirror.defineOption = option - // hint is null, leave the selection alone as much as possible - var adjustPos = function(pos) { - if (posLess(pos, change.from)) return pos; - if (!posLess(change.to, pos)) return end; + // Passed to option handlers when there is no old value. + CodeMirror.Init = Init - var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch; - if (pos.line == change.to.line) ch += end.ch - change.to.ch; - return Pos(line, ch); - }; - return {anchor: adjustPos(doc.sel.anchor), head: adjustPos(doc.sel.head)}; - } - - function filterChange(doc, change, update) { - var obj = { - canceled: false, - from: change.from, - to: change.to, - text: change.text, - origin: change.origin, - cancel: function() { this.canceled = true; } - }; - if (update) obj.update = function(from, to, text, origin) { - if (from) this.from = clipPos(doc, from); - if (to) this.to = clipPos(doc, to); - if (text) this.text = text; - if (origin !== undefined) this.origin = origin; - }; - signal(doc, "beforeChange", doc, obj); - if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj); - - if (obj.canceled) return null; - return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}; - } - - // Replace the range from from to to by the strings in replacement. - // change is a {from, to, text [, origin]} object - function makeChange(doc, change, selUpdate, ignoreReadOnly) { - if (doc.cm) { - if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, selUpdate, ignoreReadOnly); - if (doc.cm.state.suppressEdits) return; - } - - if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) { - change = filterChange(doc, change, true); - if (!change) return; - } - - // Possibly split or suppress the update based on the presence - // of read-only spans in its range. - var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to); - if (split) { - for (var i = split.length - 1; i >= 1; --i) - makeChangeNoReadonly(doc, {from: split[i].from, to: split[i].to, text: [""]}); - if (split.length) - makeChangeNoReadonly(doc, {from: split[0].from, to: split[0].to, text: change.text}, selUpdate); + // These two are, on init, called from the constructor because they + // have to be initialized before the editor can start at all. + option("value", "", function (cm, val) { return cm.setValue(val); }, true) + option("mode", null, function (cm, val) { + cm.doc.modeOption = val + loadMode(cm) + }, true) + + option("indentUnit", 2, loadMode, true) + option("indentWithTabs", false) + option("smartIndent", true) + option("tabSize", 4, function (cm) { + resetModeState(cm) + clearCaches(cm) + regChange(cm) + }, true) + option("lineSeparator", null, function (cm, val) { + cm.doc.lineSep = val + if (!val) { return } + var newBreaks = [], lineNo = cm.doc.first + cm.doc.iter(function (line) { + for (var pos = 0;;) { + var found = line.text.indexOf(val, pos) + if (found == -1) { break } + pos = found + val.length + newBreaks.push(Pos(lineNo, found)) + } + lineNo++ + }) + for (var i = newBreaks.length - 1; i >= 0; i--) + { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)) } + }) + option("specialChars", /[\u0000-\u001f\u007f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/g, function (cm, val, old) { + cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g") + if (old != Init) { cm.refresh() } + }) + option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true) + option("electricChars", true) + option("inputStyle", mobile ? "contenteditable" : "textarea", function () { + throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME + }, true) + option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true) + option("rtlMoveVisually", !windows) + option("wholeLineUpdateBefore", true) + + option("theme", "default", function (cm) { + themeChanged(cm) + guttersChanged(cm) + }, true) + option("keyMap", "default", function (cm, val, old) { + var next = getKeyMap(val) + var prev = old != Init && getKeyMap(old) + if (prev && prev.detach) { prev.detach(cm, next) } + if (next.attach) { next.attach(cm, prev || null) } + }) + option("extraKeys", null) + + option("lineWrapping", false, wrappingChanged, true) + option("gutters", [], function (cm) { + setGuttersForLineNumbers(cm.options) + guttersChanged(cm) + }, true) + option("fixedGutter", true, function (cm, val) { + cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0" + cm.refresh() + }, true) + option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true) + option("scrollbarStyle", "native", function (cm) { + initScrollbars(cm) + updateScrollbars(cm) + cm.display.scrollbars.setScrollTop(cm.doc.scrollTop) + cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft) + }, true) + option("lineNumbers", false, function (cm) { + setGuttersForLineNumbers(cm.options) + guttersChanged(cm) + }, true) + option("firstLineNumber", 1, guttersChanged, true) + option("lineNumberFormatter", function (integer) { return integer; }, guttersChanged, true) + option("showCursorWhenSelecting", false, updateSelection, true) + + option("resetSelectionOnContextMenu", true) + option("lineWiseCopyCut", true) + + option("readOnly", false, function (cm, val) { + if (val == "nocursor") { + onBlur(cm) + cm.display.input.blur() + cm.display.disabled = true } else { - makeChangeNoReadonly(doc, change, selUpdate); + cm.display.disabled = false + } + cm.display.input.readOnlyChanged(val) + }) + option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset() }}, true) + option("dragDrop", true, dragDropChanged) + option("allowDropFileTypes", null) + + option("cursorBlinkRate", 530) + option("cursorScrollMargin", 0) + option("cursorHeight", 1, updateSelection, true) + option("singleCursorHeightPerLine", true, updateSelection, true) + option("workTime", 100) + option("workDelay", 100) + option("flattenSpans", true, resetModeState, true) + option("addModeClass", false, resetModeState, true) + option("pollInterval", 100) + option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; }) + option("historyEventDelay", 1250) + option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true) + option("maxHighlightLength", 10000, resetModeState, true) + option("moveInputWithCursor", true, function (cm, val) { + if (!val) { cm.display.input.resetPosition() } + }) + + option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; }) + option("autofocus", null) +} + +function guttersChanged(cm) { + updateGutters(cm) + regChange(cm) + alignHorizontally(cm) +} + +function dragDropChanged(cm, value, old) { + var wasOn = old && old != Init + if (!value != !wasOn) { + var funcs = cm.display.dragFunctions + var toggle = value ? on : off + toggle(cm.display.scroller, "dragstart", funcs.start) + toggle(cm.display.scroller, "dragenter", funcs.enter) + toggle(cm.display.scroller, "dragover", funcs.over) + toggle(cm.display.scroller, "dragleave", funcs.leave) + toggle(cm.display.scroller, "drop", funcs.drop) + } +} + +function wrappingChanged(cm) { + if (cm.options.lineWrapping) { + addClass(cm.display.wrapper, "CodeMirror-wrap") + cm.display.sizer.style.minWidth = "" + cm.display.sizerWidth = null + } else { + rmClass(cm.display.wrapper, "CodeMirror-wrap") + findMaxLine(cm) + } + estimateLineHeights(cm) + regChange(cm) + clearCaches(cm) + setTimeout(function () { return updateScrollbars(cm); }, 100) +} + +// A CodeMirror instance represents an editor. This is the object +// that user code is usually dealing with. + +function CodeMirror(place, options) { + var this$1 = this; + + if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) } + + this.options = options = options ? copyObj(options) : {} + // Determine effective options based on given values and defaults. + copyObj(defaults, options, false) + setGuttersForLineNumbers(options) + + var doc = options.value + if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator) } + this.doc = doc + + var input = new CodeMirror.inputStyles[options.inputStyle](this) + var display = this.display = new Display(place, doc, input) + display.wrapper.CodeMirror = this + updateGutters(this) + themeChanged(this) + if (options.lineWrapping) + { this.display.wrapper.className += " CodeMirror-wrap" } + initScrollbars(this) + + this.state = { + keyMaps: [], // stores maps added by addKeyMap + overlays: [], // highlighting overlays, as added by addOverlay + modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info + overwrite: false, + delayingBlurEvent: false, + focused: false, + suppressEdits: false, // used to disable editing during key handlers when in readOnly mode + pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll + selectingText: false, + draggingText: false, + highlight: new Delayed(), // stores highlight worker timeout + keySeq: null, // Unfinished key sequence + specialChars: null + } + + if (options.autofocus && !mobile) { display.input.focus() } + + // Override magic textarea content restore that IE sometimes does + // on our hidden textarea on reload + if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20) } + + registerEventHandlers(this) + ensureGlobalHandlers() + + startOperation(this) + this.curOp.forceUpdate = true + attachDoc(this, doc) + + if ((options.autofocus && !mobile) || this.hasFocus()) + { setTimeout(bind(onFocus, this), 20) } + else + { onBlur(this) } + + for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt)) + { optionHandlers[opt](this$1, options[opt], Init) } } + maybeUpdateLineNumberWidth(this) + if (options.finishInit) { options.finishInit(this) } + for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this$1) } + endOperation(this) + // Suppress optimizelegibility in Webkit, since it breaks text + // measuring on line wrapping boundaries. + if (webkit && options.lineWrapping && + getComputedStyle(display.lineDiv).textRendering == "optimizelegibility") + { display.lineDiv.style.textRendering = "auto" } +} + +// The default configuration options. +CodeMirror.defaults = defaults +// Functions to run when options are changed. +CodeMirror.optionHandlers = optionHandlers + +// Attach the necessary event handlers when initializing the editor +function registerEventHandlers(cm) { + var d = cm.display + on(d.scroller, "mousedown", operation(cm, onMouseDown)) + // Older IE's will not fire a second mousedown for a double click + if (ie && ie_version < 11) + { on(d.scroller, "dblclick", operation(cm, function (e) { + if (signalDOMEvent(cm, e)) { return } + var pos = posFromMouse(cm, e) + if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return } + e_preventDefault(e) + var word = cm.findWordAt(pos) + extendSelection(cm.doc, word.anchor, word.head) + })) } + else + { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }) } + // Some browsers fire contextmenu *after* opening the menu, at + // which point we can't mess with it anymore. Context menu is + // handled in onMouseDown for these browsers. + if (!captureRightClick) { on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); }) } + + // Used to suppress mouse event handling when a touch happens + var touchFinished, prevTouch = {end: 0} + function finishTouch() { + if (d.activeTouch) { + touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000) + prevTouch = d.activeTouch + prevTouch.end = +new Date + } + } + function isMouseLikeTouchEvent(e) { + if (e.touches.length != 1) { return false } + var touch = e.touches[0] + return touch.radiusX <= 1 && touch.radiusY <= 1 + } + function farAway(touch, other) { + if (other.left == null) { return true } + var dx = other.left - touch.left, dy = other.top - touch.top + return dx * dx + dy * dy > 20 * 20 + } + on(d.scroller, "touchstart", function (e) { + if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e)) { + d.input.ensurePolled() + clearTimeout(touchFinished) + var now = +new Date + d.activeTouch = {start: now, moved: false, + prev: now - prevTouch.end <= 300 ? prevTouch : null} + if (e.touches.length == 1) { + d.activeTouch.left = e.touches[0].pageX + d.activeTouch.top = e.touches[0].pageY + } + } + }) + on(d.scroller, "touchmove", function () { + if (d.activeTouch) { d.activeTouch.moved = true } + }) + on(d.scroller, "touchend", function (e) { + var touch = d.activeTouch + if (touch && !eventInWidget(d, e) && touch.left != null && + !touch.moved && new Date - touch.start < 300) { + var pos = cm.coordsChar(d.activeTouch, "page"), range + if (!touch.prev || farAway(touch, touch.prev)) // Single tap + { range = new Range(pos, pos) } + else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap + { range = cm.findWordAt(pos) } + else // Triple tap + { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) } + cm.setSelection(range.anchor, range.head) + cm.focus() + e_preventDefault(e) + } + finishTouch() + }) + on(d.scroller, "touchcancel", finishTouch) + + // Sync scrolling between fake scrollbars and real scrollable + // area, ensure viewport is updated when scrolling. + on(d.scroller, "scroll", function () { + if (d.scroller.clientHeight) { + setScrollTop(cm, d.scroller.scrollTop) + setScrollLeft(cm, d.scroller.scrollLeft, true) + signal(cm, "scroll", cm) + } + }) + + // Listen to wheel events in order to try and update the viewport on time. + on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); }) + on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); }) + + // Prevent wrapper from ever scrolling + on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; }) + + d.dragFunctions = { + enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e) }}, + over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e) }}, + start: function (e) { return onDragStart(cm, e); }, + drop: operation(cm, onDrop), + leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm) }} + } + + var inp = d.input.getField() + on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); }) + on(inp, "keydown", operation(cm, onKeyDown)) + on(inp, "keypress", operation(cm, onKeyPress)) + on(inp, "focus", function (e) { return onFocus(cm, e); }) + on(inp, "blur", function (e) { return onBlur(cm, e); }) +} + +var initHooks = [] +CodeMirror.defineInitHook = function (f) { return initHooks.push(f); } + +// Indent the given line. The how parameter can be "smart", +// "add"/null, "subtract", or "prev". When aggressive is false +// (typically set to true for forced single-line indents), empty +// lines are not indented, and places where the mode returns Pass +// are left alone. +function indentLine(cm, n, how, aggressive) { + var doc = cm.doc, state + if (how == null) { how = "add" } + if (how == "smart") { + // Fall back to "prev" when the mode doesn't have an indentation + // method. + if (!doc.mode.indent) { how = "prev" } + else { state = getStateBefore(cm, n) } + } + + var tabSize = cm.options.tabSize + var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize) + if (line.stateAfter) { line.stateAfter = null } + var curSpaceString = line.text.match(/^\s*/)[0], indentation + if (!aggressive && !/\S/.test(line.text)) { + indentation = 0 + how = "not" + } else if (how == "smart") { + indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text) + if (indentation == Pass || indentation > 150) { + if (!aggressive) { return } + how = "prev" + } + } + if (how == "prev") { + if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize) } + else { indentation = 0 } + } else if (how == "add") { + indentation = curSpace + cm.options.indentUnit + } else if (how == "subtract") { + indentation = curSpace - cm.options.indentUnit + } else if (typeof how == "number") { + indentation = curSpace + how + } + indentation = Math.max(0, indentation) + + var indentString = "", pos = 0 + if (cm.options.indentWithTabs) + { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t"} } + if (pos < indentation) { indentString += spaceStr(indentation - pos) } + + if (indentString != curSpaceString) { + replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input") + line.stateAfter = null + return true + } else { + // Ensure that, if the cursor was in the whitespace at the start + // of the line, it is moved to the end of that space. + for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) { + var range = doc.sel.ranges[i$1] + if (range.head.line == n && range.head.ch < curSpaceString.length) { + var pos$1 = Pos(n, curSpaceString.length) + replaceOneSelection(doc, i$1, new Range(pos$1, pos$1)) + break + } } } +} - function makeChangeNoReadonly(doc, change, selUpdate) { - if (change.text.length == 1 && change.text[0] == "" && posEq(change.from, change.to)) return; - var selAfter = computeSelAfterChange(doc, change, selUpdate); - addToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN); +// This will be set to a {lineWise: bool, text: [string]} object, so +// that, when pasting, we know what kind of selections the copied +// text was made out of. +var lastCopied = null - makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change)); - var rebased = []; +function setLastCopied(newLastCopied) { + lastCopied = newLastCopied +} - linkedDocs(doc, function(doc, sharedHist) { - if (!sharedHist && indexOf(rebased, doc.history) == -1) { - rebaseHist(doc.history, change); - rebased.push(doc.history); - } - makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change)); - }); - } +function applyTextInput(cm, inserted, deleted, sel, origin) { + var doc = cm.doc + cm.display.shift = false + if (!sel) { sel = doc.sel } - function makeChangeFromHistory(doc, type) { - if (doc.cm && doc.cm.state.suppressEdits) return; + var paste = cm.state.pasteIncoming || origin == "paste" + var textLines = splitLinesAuto(inserted), multiPaste = null + // When pasing N lines into N selections, insert one line per selection + if (paste && sel.ranges.length > 1) { + if (lastCopied && lastCopied.text.join("\n") == inserted) { + if (sel.ranges.length % lastCopied.text.length == 0) { + multiPaste = [] + for (var i = 0; i < lastCopied.text.length; i++) + { multiPaste.push(doc.splitLines(lastCopied.text[i])) } + } + } else if (textLines.length == sel.ranges.length) { + multiPaste = map(textLines, function (l) { return [l]; }) + } + } + + var updateInput + // Normal behavior is to insert the new text into every selection + for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) { + var range = sel.ranges[i$1] + var from = range.from(), to = range.to() + if (range.empty()) { + if (deleted && deleted > 0) // Handle deletion + { from = Pos(from.line, from.ch - deleted) } + else if (cm.state.overwrite && !paste) // Handle overwrite + { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)) } + else if (lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted) + { from = to = Pos(from.line, 0) } + } + updateInput = cm.curOp.updateInput + var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines, + origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")} + makeChange(cm.doc, changeEvent) + signalLater(cm, "inputRead", cm, changeEvent) + } + if (inserted && !paste) + { triggerElectric(cm, inserted) } + + ensureCursorVisible(cm) + cm.curOp.updateInput = updateInput + cm.curOp.typing = true + cm.state.pasteIncoming = cm.state.cutIncoming = false +} + +function handlePaste(e, cm) { + var pasted = e.clipboardData && e.clipboardData.getData("Text") + if (pasted) { + e.preventDefault() + if (!cm.isReadOnly() && !cm.options.disableInput) + { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }) } + return true + } +} + +function triggerElectric(cm, inserted) { + // When an 'electric' character is inserted, immediately trigger a reindent + if (!cm.options.electricChars || !cm.options.smartIndent) { return } + var sel = cm.doc.sel + + for (var i = sel.ranges.length - 1; i >= 0; i--) { + var range = sel.ranges[i] + if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) { continue } + var mode = cm.getModeAt(range.head) + var indented = false + if (mode.electricChars) { + for (var j = 0; j < mode.electricChars.length; j++) + { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) { + indented = indentLine(cm, range.head.line, "smart") + break + } } + } else if (mode.electricInput) { + if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch))) + { indented = indentLine(cm, range.head.line, "smart") } + } + if (indented) { signalLater(cm, "electricInput", cm, range.head.line) } + } +} + +function copyableRanges(cm) { + var text = [], ranges = [] + for (var i = 0; i < cm.doc.sel.ranges.length; i++) { + var line = cm.doc.sel.ranges[i].head.line + var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)} + ranges.push(lineRange) + text.push(cm.getRange(lineRange.anchor, lineRange.head)) + } + return {text: text, ranges: ranges} +} + +function disableBrowserMagic(field, spellcheck) { + field.setAttribute("autocorrect", "off") + field.setAttribute("autocapitalize", "off") + field.setAttribute("spellcheck", !!spellcheck) +} + +function hiddenTextarea() { + var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none") + var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;") + // The textarea is kept positioned near the cursor to prevent the + // fact that it'll be scrolled into view on input from scrolling + // our fake cursor out of view. On webkit, when wrap=off, paste is + // very slow. So make the area wide instead. + if (webkit) { te.style.width = "1000px" } + else { te.setAttribute("wrap", "off") } + // If border: 0; -- iOS fails to open keyboard (issue #1287) + if (ios) { te.style.border = "1px solid black" } + disableBrowserMagic(te) + return div +} + +// The publicly visible API. Note that methodOp(f) means +// 'wrap f in an operation, performed on its `this` parameter'. + +// This is not the complete set of editor methods. Most of the +// methods defined on the Doc type are also injected into +// CodeMirror.prototype, for backwards compatibility and +// convenience. + +function addEditorMethods(CodeMirror) { + var optionHandlers = CodeMirror.optionHandlers + + var helpers = CodeMirror.helpers = {} - var hist = doc.history; - var event = (type == "undo" ? hist.done : hist.undone).pop(); - if (!event) return; + CodeMirror.prototype = { + constructor: CodeMirror, + focus: function(){window.focus(); this.display.input.focus()}, - var anti = {changes: [], anchorBefore: event.anchorAfter, headBefore: event.headAfter, - anchorAfter: event.anchorBefore, headAfter: event.headBefore, - generation: hist.generation}; - (type == "undo" ? hist.undone : hist.done).push(anti); - hist.generation = event.generation || ++hist.maxGeneration; + setOption: function(option, value) { + var options = this.options, old = options[option] + if (options[option] == value && option != "mode") { return } + options[option] = value + if (optionHandlers.hasOwnProperty(option)) + { operation(this, optionHandlers[option])(this, value, old) } + signal(this, "optionChange", this, option) + }, - var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange"); + getOption: function(option) {return this.options[option]}, + getDoc: function() {return this.doc}, - for (var i = event.changes.length - 1; i >= 0; --i) { - var change = event.changes[i]; - change.origin = type; - if (filter && !filterChange(doc, change, false)) { - (type == "undo" ? hist.done : hist.undone).length = 0; - return; - } + addKeyMap: function(map, bottom) { + this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map)) + }, + removeKeyMap: function(map) { + var maps = this.state.keyMaps + for (var i = 0; i < maps.length; ++i) + { if (maps[i] == map || maps[i].name == map) { + maps.splice(i, 1) + return true + } } + }, - anti.changes.push(historyChangeFromChange(doc, change)); + addOverlay: methodOp(function(spec, options) { + var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec) + if (mode.startState) { throw new Error("Overlays may not be stateful.") } + insertSorted(this.state.overlays, + {mode: mode, modeSpec: spec, opaque: options && options.opaque, + priority: (options && options.priority) || 0}, + function (overlay) { return overlay.priority; }) + this.state.modeGen++ + regChange(this) + }), + removeOverlay: methodOp(function(spec) { + var this$1 = this; - var after = i ? computeSelAfterChange(doc, change, null) - : {anchor: event.anchorBefore, head: event.headBefore}; - makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)); - var rebased = []; + var overlays = this.state.overlays + for (var i = 0; i < overlays.length; ++i) { + var cur = overlays[i].modeSpec + if (cur == spec || typeof spec == "string" && cur.name == spec) { + overlays.splice(i, 1) + this$1.state.modeGen++ + regChange(this$1) + return + } + } + }), - linkedDocs(doc, function(doc, sharedHist) { - if (!sharedHist && indexOf(rebased, doc.history) == -1) { - rebaseHist(doc.history, change); - rebased.push(doc.history); + indentLine: methodOp(function(n, dir, aggressive) { + if (typeof dir != "string" && typeof dir != "number") { + if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev" } + else { dir = dir ? "add" : "subtract" } + } + if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive) } + }), + indentSelection: methodOp(function(how) { + var this$1 = this; + + var ranges = this.doc.sel.ranges, end = -1 + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i] + if (!range.empty()) { + var from = range.from(), to = range.to() + var start = Math.max(end, from.line) + end = Math.min(this$1.lastLine(), to.line - (to.ch ? 0 : 1)) + 1 + for (var j = start; j < end; ++j) + { indentLine(this$1, j, how) } + var newRanges = this$1.doc.sel.ranges + if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0) + { replaceOneSelection(this$1.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll) } + } else if (range.head.line > end) { + indentLine(this$1, range.head.line, how, true) + end = range.head.line + if (i == this$1.doc.sel.primIndex) { ensureCursorVisible(this$1) } } - makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change)); - }); - } - } + } + }), - function shiftDoc(doc, distance) { - function shiftPos(pos) {return Pos(pos.line + distance, pos.ch);} - doc.first += distance; - if (doc.cm) regChange(doc.cm, doc.first, doc.first, distance); - doc.sel.head = shiftPos(doc.sel.head); doc.sel.anchor = shiftPos(doc.sel.anchor); - doc.sel.from = shiftPos(doc.sel.from); doc.sel.to = shiftPos(doc.sel.to); - } + // Fetch the parser token for a given character. Useful for hacks + // that want to inspect the mode state (say, for completion). + getTokenAt: function(pos, precise) { + return takeToken(this, pos, precise) + }, - function makeChangeSingleDoc(doc, change, selAfter, spans) { - if (doc.cm && !doc.cm.curOp) - return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans); + getLineTokens: function(line, precise) { + return takeToken(this, Pos(line), precise, true) + }, - if (change.to.line < doc.first) { - shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line)); - return; - } - if (change.from.line > doc.lastLine()) return; + getTokenTypeAt: function(pos) { + pos = clipPos(this.doc, pos) + var styles = getLineStyles(this, getLine(this.doc, pos.line)) + var before = 0, after = (styles.length - 1) / 2, ch = pos.ch + var type + if (ch == 0) { type = styles[2] } + else { for (;;) { + var mid = (before + after) >> 1 + if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid } + else if (styles[mid * 2 + 1] < ch) { before = mid + 1 } + else { type = styles[mid * 2 + 2]; break } + } } + var cut = type ? type.indexOf("overlay ") : -1 + return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1) + }, - // Clip the change to the size of this doc - if (change.from.line < doc.first) { - var shift = change.text.length - 1 - (doc.first - change.from.line); - shiftDoc(doc, shift); - change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch), - text: [lst(change.text)], origin: change.origin}; - } - var last = doc.lastLine(); - if (change.to.line > last) { - change = {from: change.from, to: Pos(last, getLine(doc, last).text.length), - text: [change.text[0]], origin: change.origin}; - } - - change.removed = getBetween(doc, change.from, change.to); - - if (!selAfter) selAfter = computeSelAfterChange(doc, change, null); - if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans, selAfter); - else updateDoc(doc, change, spans, selAfter); - } - - function makeChangeSingleDocInEditor(cm, change, spans, selAfter) { - var doc = cm.doc, display = cm.display, from = change.from, to = change.to; - - var recomputeMaxLength = false, checkWidthStart = from.line; - if (!cm.options.lineWrapping) { - checkWidthStart = lineNo(visualLine(doc, getLine(doc, from.line))); - doc.iter(checkWidthStart, to.line + 1, function(line) { - if (line == display.maxLine) { - recomputeMaxLength = true; - return true; - } - }); - } - - if (!posLess(doc.sel.head, change.from) && !posLess(change.to, doc.sel.head)) - cm.curOp.cursorActivity = true; - - updateDoc(doc, change, spans, selAfter, estimateHeight(cm)); - - if (!cm.options.lineWrapping) { - doc.iter(checkWidthStart, from.line + change.text.length, function(line) { - var len = lineLength(doc, line); - if (len > display.maxLineLength) { - display.maxLine = line; - display.maxLineLength = len; - display.maxLineChanged = true; - recomputeMaxLength = false; - } - }); - if (recomputeMaxLength) cm.curOp.updateMaxLine = true; - } - - // Adjust frontier, schedule worker - doc.frontier = Math.min(doc.frontier, from.line); - startWorker(cm, 400); - - var lendiff = change.text.length - (to.line - from.line) - 1; - // Remember that these lines changed, for updating the display - regChange(cm, from.line, to.line + 1, lendiff); - - if (hasHandler(cm, "change")) { - var changeObj = {from: from, to: to, - text: change.text, - removed: change.removed, - origin: change.origin}; - if (cm.curOp.textChanged) { - for (var cur = cm.curOp.textChanged; cur.next; cur = cur.next) {} - cur.next = changeObj; - } else cm.curOp.textChanged = changeObj; - } - } - - function replaceRange(doc, code, from, to, origin) { - if (!to) to = from; - if (posLess(to, from)) { var tmp = to; to = from; from = tmp; } - if (typeof code == "string") code = splitLines(code); - makeChange(doc, {from: from, to: to, text: code, origin: origin}, null); - } - - // POSITION OBJECT - - function Pos(line, ch) { - if (!(this instanceof Pos)) return new Pos(line, ch); - this.line = line; this.ch = ch; - } - CodeMirror.Pos = Pos; - - function posEq(a, b) {return a.line == b.line && a.ch == b.ch;} - function posLess(a, b) {return a.line < b.line || (a.line == b.line && a.ch < b.ch);} - function copyPos(x) {return Pos(x.line, x.ch);} - - // SELECTION - - function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));} - function clipPos(doc, pos) { - if (pos.line < doc.first) return Pos(doc.first, 0); - var last = doc.first + doc.size - 1; - if (pos.line > last) return Pos(last, getLine(doc, last).text.length); - return clipToLen(pos, getLine(doc, pos.line).text.length); - } - function clipToLen(pos, linelen) { - var ch = pos.ch; - if (ch == null || ch > linelen) return Pos(pos.line, linelen); - else if (ch < 0) return Pos(pos.line, 0); - else return pos; - } - function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;} - - // If shift is held, this will move the selection anchor. Otherwise, - // it'll set the whole selection. - function extendSelection(doc, pos, other, bias) { - if (doc.sel.shift || doc.sel.extend) { - var anchor = doc.sel.anchor; - if (other) { - var posBefore = posLess(pos, anchor); - if (posBefore != posLess(other, anchor)) { - anchor = pos; - pos = other; - } else if (posBefore != posLess(pos, other)) { - pos = other; - } - } - setSelection(doc, anchor, pos, bias); - } else { - setSelection(doc, pos, other || pos, bias); - } - if (doc.cm) doc.cm.curOp.userSelChange = true; - } - - function filterSelectionChange(doc, anchor, head) { - var obj = {anchor: anchor, head: head}; - signal(doc, "beforeSelectionChange", doc, obj); - if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj); - obj.anchor = clipPos(doc, obj.anchor); obj.head = clipPos(doc, obj.head); - return obj; - } - - // Update the selection. Last two args are only used by - // updateDoc, since they have to be expressed in the line - // numbers before the update. - function setSelection(doc, anchor, head, bias, checkAtomic) { - if (!checkAtomic && hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) { - var filtered = filterSelectionChange(doc, anchor, head); - head = filtered.head; - anchor = filtered.anchor; - } - - var sel = doc.sel; - sel.goalColumn = null; - if (bias == null) bias = posLess(head, sel.head) ? -1 : 1; - // Skip over atomic spans. - if (checkAtomic || !posEq(anchor, sel.anchor)) - anchor = skipAtomic(doc, anchor, bias, checkAtomic != "push"); - if (checkAtomic || !posEq(head, sel.head)) - head = skipAtomic(doc, head, bias, checkAtomic != "push"); - - if (posEq(sel.anchor, anchor) && posEq(sel.head, head)) return; - - sel.anchor = anchor; sel.head = head; - var inv = posLess(head, anchor); - sel.from = inv ? head : anchor; - sel.to = inv ? anchor : head; - - if (doc.cm) - doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = - doc.cm.curOp.cursorActivity = true; - - signalLater(doc, "cursorActivity", doc); - } - - function reCheckSelection(cm) { - setSelection(cm.doc, cm.doc.sel.from, cm.doc.sel.to, null, "push"); - } - - function skipAtomic(doc, pos, bias, mayClear) { - var flipped = false, curPos = pos; - var dir = bias || 1; - doc.cantEdit = false; - search: for (;;) { - var line = getLine(doc, curPos.line); - if (line.markedSpans) { - for (var i = 0; i < line.markedSpans.length; ++i) { - var sp = line.markedSpans[i], m = sp.marker; - if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) && - (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) { - if (mayClear) { - signal(m, "beforeCursorEnter"); - if (m.explicitlyCleared) { - if (!line.markedSpans) break; - else {--i; continue;} - } - } - if (!m.atomic) continue; - var newPos = m.find()[dir < 0 ? "from" : "to"]; - if (posEq(newPos, curPos)) { - newPos.ch += dir; - if (newPos.ch < 0) { - if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1)); - else newPos = null; - } else if (newPos.ch > line.text.length) { - if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0); - else newPos = null; - } - if (!newPos) { - if (flipped) { - // Driven in a corner -- no valid cursor position found at all - // -- try again *with* clearing, if we didn't already - if (!mayClear) return skipAtomic(doc, pos, bias, true); - // Otherwise, turn off editing until further notice, and return the start of the doc - doc.cantEdit = true; - return Pos(doc.first, 0); - } - flipped = true; newPos = pos; dir = -dir; - } - } - curPos = newPos; - continue search; - } - } - } - return curPos; - } - } - - // SCROLLING - - function scrollCursorIntoView(cm) { - var coords = scrollPosIntoView(cm, cm.doc.sel.head, null, cm.options.cursorScrollMargin); - if (!cm.state.focused) return; - var display = cm.display, box = getRect(display.sizer), doScroll = null; - if (coords.top + box.top < 0) doScroll = true; - else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false; - if (doScroll != null && !phantom) { - var hidden = display.cursor.style.display == "none"; - if (hidden) { - display.cursor.style.display = ""; - display.cursor.style.left = coords.left + "px"; - display.cursor.style.top = (coords.top - display.viewOffset) + "px"; - } - display.cursor.scrollIntoView(doScroll); - if (hidden) display.cursor.style.display = "none"; - } - } - - function scrollPosIntoView(cm, pos, end, margin) { - if (margin == null) margin = 0; - for (;;) { - var changed = false, coords = cursorCoords(cm, pos); - var endCoords = !end || end == pos ? coords : cursorCoords(cm, end); - var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left), - Math.min(coords.top, endCoords.top) - margin, - Math.max(coords.left, endCoords.left), - Math.max(coords.bottom, endCoords.bottom) + margin); - var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft; - if (scrollPos.scrollTop != null) { - setScrollTop(cm, scrollPos.scrollTop); - if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true; - } - if (scrollPos.scrollLeft != null) { - setScrollLeft(cm, scrollPos.scrollLeft); - if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true; - } - if (!changed) return coords; - } - } - - function scrollIntoView(cm, x1, y1, x2, y2) { - var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2); - if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop); - if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft); - } - - function calculateScrollPos(cm, x1, y1, x2, y2) { - var display = cm.display, snapMargin = textHeight(cm.display); - if (y1 < 0) y1 = 0; - var screen = display.scroller.clientHeight - scrollerCutOff, screentop = display.scroller.scrollTop, result = {}; - var docBottom = cm.doc.height + paddingVert(display); - var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin; - if (y1 < screentop) { - result.scrollTop = atTop ? 0 : y1; - } else if (y2 > screentop + screen) { - var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen); - if (newTop != screentop) result.scrollTop = newTop; - } - - var screenw = display.scroller.clientWidth - scrollerCutOff, screenleft = display.scroller.scrollLeft; - x1 += display.gutters.offsetWidth; x2 += display.gutters.offsetWidth; - var gutterw = display.gutters.offsetWidth; - var atLeft = x1 < gutterw + 10; - if (x1 < screenleft + gutterw || atLeft) { - if (atLeft) x1 = 0; - result.scrollLeft = Math.max(0, x1 - 10 - gutterw); - } else if (x2 > screenw + screenleft - 3) { - result.scrollLeft = x2 + 10 - screenw; - } - return result; - } - - function updateScrollPos(cm, left, top) { - cm.curOp.updateScrollPos = {scrollLeft: left == null ? cm.doc.scrollLeft : left, - scrollTop: top == null ? cm.doc.scrollTop : top}; - } - - function addToScrollPos(cm, left, top) { - var pos = cm.curOp.updateScrollPos || (cm.curOp.updateScrollPos = {scrollLeft: cm.doc.scrollLeft, scrollTop: cm.doc.scrollTop}); - var scroll = cm.display.scroller; - pos.scrollTop = Math.max(0, Math.min(scroll.scrollHeight - scroll.clientHeight, pos.scrollTop + top)); - pos.scrollLeft = Math.max(0, Math.min(scroll.scrollWidth - scroll.clientWidth, pos.scrollLeft + left)); - } - - // API UTILITIES - - function indentLine(cm, n, how, aggressive) { - var doc = cm.doc; - if (how == null) how = "add"; - if (how == "smart") { - if (!cm.doc.mode.indent) how = "prev"; - else var state = getStateBefore(cm, n); - } - - var tabSize = cm.options.tabSize; - var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize); - var curSpaceString = line.text.match(/^\s*/)[0], indentation; - if (how == "smart") { - indentation = cm.doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text); - if (indentation == Pass) { - if (!aggressive) return; - how = "prev"; - } - } - if (how == "prev") { - if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize); - else indentation = 0; - } else if (how == "add") { - indentation = curSpace + cm.options.indentUnit; - } else if (how == "subtract") { - indentation = curSpace - cm.options.indentUnit; - } else if (typeof how == "number") { - indentation = curSpace + how; - } - indentation = Math.max(0, indentation); - - var indentString = "", pos = 0; - if (cm.options.indentWithTabs) - for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} - if (pos < indentation) indentString += spaceStr(indentation - pos); - - if (indentString != curSpaceString) - replaceRange(cm.doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input"); - else if (doc.sel.head.line == n && doc.sel.head.ch < curSpaceString.length) - setSelection(doc, Pos(n, curSpaceString.length), Pos(n, curSpaceString.length), 1); - line.stateAfter = null; - } - - function changeLine(cm, handle, op) { - var no = handle, line = handle, doc = cm.doc; - if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle)); - else no = lineNo(handle); - if (no == null) return null; - if (op(line, no)) regChange(cm, no, no + 1); - else return null; - return line; - } - - function findPosH(doc, pos, dir, unit, visually) { - var line = pos.line, ch = pos.ch, origDir = dir; - var lineObj = getLine(doc, line); - var possible = true; - function findNextLine() { - var l = line + dir; - if (l < doc.first || l >= doc.first + doc.size) return (possible = false); - line = l; - return lineObj = getLine(doc, l); - } - function moveOnce(boundToLine) { - var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true); - if (next == null) { - if (!boundToLine && findNextLine()) { - if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj); - else ch = dir < 0 ? lineObj.text.length : 0; - } else return (possible = false); - } else ch = next; - return true; - } - - if (unit == "char") moveOnce(); - else if (unit == "column") moveOnce(true); - else if (unit == "word" || unit == "group") { - var sawType = null, group = unit == "group"; - for (var first = true;; first = false) { - if (dir < 0 && !moveOnce(!first)) break; - var cur = lineObj.text.charAt(ch) || "\n"; - var type = isWordChar(cur) ? "w" - : !group ? null - : /\s/.test(cur) ? null - : "p"; - if (sawType && sawType != type) { - if (dir < 0) {dir = 1; moveOnce();} - break; - } - if (type) sawType = type; - if (dir > 0 && !moveOnce(!first)) break; - } - } - var result = skipAtomic(doc, Pos(line, ch), origDir, true); - if (!possible) result.hitSide = true; - return result; - } - - function findPosV(cm, pos, dir, unit) { - var doc = cm.doc, x = pos.left, y; - if (unit == "page") { - var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight); - y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display)); - } else if (unit == "line") { - y = dir > 0 ? pos.bottom + 3 : pos.top - 3; - } - for (;;) { - var target = coordsChar(cm, x, y); - if (!target.outside) break; - if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; } - y += dir * 5; - } - return target; - } - - function findWordAt(line, pos) { - var start = pos.ch, end = pos.ch; - if (line) { - if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end; - var startChar = line.charAt(start); - var check = isWordChar(startChar) ? isWordChar - : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);} - : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);}; - while (start > 0 && check(line.charAt(start - 1))) --start; - while (end < line.length && check(line.charAt(end))) ++end; - } - return {from: Pos(pos.line, start), to: Pos(pos.line, end)}; - } - - function selectLine(cm, line) { - extendSelection(cm.doc, Pos(line, 0), clipPos(cm.doc, Pos(line + 1, 0))); - } - - // PROTOTYPE - - // The publicly visible API. Note that operation(null, f) means - // 'wrap f in an operation, performed on its `this` parameter' - - CodeMirror.prototype = { - constructor: CodeMirror, - focus: function(){window.focus(); focusInput(this); fastPoll(this);}, - - setOption: function(option, value) { - var options = this.options, old = options[option]; - if (options[option] == value && option != "mode") return; - options[option] = value; - if (optionHandlers.hasOwnProperty(option)) - operation(this, optionHandlers[option])(this, value, old); + getModeAt: function(pos) { + var mode = this.doc.mode + if (!mode.innerMode) { return mode } + return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode }, - getOption: function(option) {return this.options[option];}, - getDoc: function() {return this.doc;}, - - addKeyMap: function(map, bottom) { - this.state.keyMaps[bottom ? "push" : "unshift"](map); - }, - removeKeyMap: function(map) { - var maps = this.state.keyMaps; - for (var i = 0; i < maps.length; ++i) - if (maps[i] == map || (typeof maps[i] != "string" && maps[i].name == map)) { - maps.splice(i, 1); - return true; - } + getHelper: function(pos, type) { + return this.getHelpers(pos, type)[0] }, - addOverlay: operation(null, function(spec, options) { - var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec); - if (mode.startState) throw new Error("Overlays may not be stateful."); - this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque}); - this.state.modeGen++; - regChange(this); - }), - removeOverlay: operation(null, function(spec) { - var overlays = this.state.overlays; - for (var i = 0; i < overlays.length; ++i) { - var cur = overlays[i].modeSpec; - if (cur == spec || typeof spec == "string" && cur.name == spec) { - overlays.splice(i, 1); - this.state.modeGen++; - regChange(this); - return; + getHelpers: function(pos, type) { + var this$1 = this; + + var found = [] + if (!helpers.hasOwnProperty(type)) { return found } + var help = helpers[type], mode = this.getModeAt(pos) + if (typeof mode[type] == "string") { + if (help[mode[type]]) { found.push(help[mode[type]]) } + } else if (mode[type]) { + for (var i = 0; i < mode[type].length; i++) { + var val = help[mode[type][i]] + if (val) { found.push(val) } } + } else if (mode.helperType && help[mode.helperType]) { + found.push(help[mode.helperType]) + } else if (help[mode.name]) { + found.push(help[mode.name]) } - }), - - indentLine: operation(null, function(n, dir, aggressive) { - if (typeof dir != "string" && typeof dir != "number") { - if (dir == null) dir = this.options.smartIndent ? "smart" : "prev"; - else dir = dir ? "add" : "subtract"; - } - if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive); - }), - indentSelection: operation(null, function(how) { - var sel = this.doc.sel; - if (posEq(sel.from, sel.to)) return indentLine(this, sel.from.line, how); - var e = sel.to.line - (sel.to.ch ? 0 : 1); - for (var i = sel.from.line; i <= e; ++i) indentLine(this, i, how); - }), - - // Fetch the parser token for a given character. Useful for hacks - // that want to inspect the mode state (say, for completion). - getTokenAt: function(pos, precise) { - var doc = this.doc; - pos = clipPos(doc, pos); - var state = getStateBefore(this, pos.line, precise), mode = this.doc.mode; - var line = getLine(doc, pos.line); - var stream = new StringStream(line.text, this.options.tabSize); - while (stream.pos < pos.ch && !stream.eol()) { - stream.start = stream.pos; - var style = mode.token(stream, state); - } - return {start: stream.start, - end: stream.pos, - string: stream.current(), - className: style || null, // Deprecated, use 'type' instead - type: style || null, - state: state}; - }, - - getTokenTypeAt: function(pos) { - pos = clipPos(this.doc, pos); - var styles = getLineStyles(this, getLine(this.doc, pos.line)); - var before = 0, after = (styles.length - 1) / 2, ch = pos.ch; - if (ch == 0) return styles[2]; - for (;;) { - var mid = (before + after) >> 1; - if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid; - else if (styles[mid * 2 + 1] < ch) before = mid + 1; - else return styles[mid * 2 + 2]; + for (var i$1 = 0; i$1 < help._global.length; i$1++) { + var cur = help._global[i$1] + if (cur.pred(mode, this$1) && indexOf(found, cur.val) == -1) + { found.push(cur.val) } } - }, - - getModeAt: function(pos) { - var mode = this.doc.mode; - if (!mode.innerMode) return mode; - return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode; - }, - - getHelper: function(pos, type) { - if (!helpers.hasOwnProperty(type)) return; - var help = helpers[type], mode = this.getModeAt(pos); - return mode[type] && help[mode[type]] || - mode.helperType && help[mode.helperType] || - help[mode.name]; + return found }, getStateAfter: function(line, precise) { - var doc = this.doc; - line = clipLine(doc, line == null ? doc.first + doc.size - 1: line); - return getStateBefore(this, line + 1, precise); + var doc = this.doc + line = clipLine(doc, line == null ? doc.first + doc.size - 1: line) + return getStateBefore(this, line + 1, precise) }, cursorCoords: function(start, mode) { - var pos, sel = this.doc.sel; - if (start == null) pos = sel.head; - else if (typeof start == "object") pos = clipPos(this.doc, start); - else pos = start ? sel.from : sel.to; - return cursorCoords(this, pos, mode || "page"); + var pos, range = this.doc.sel.primary() + if (start == null) { pos = range.head } + else if (typeof start == "object") { pos = clipPos(this.doc, start) } + else { pos = start ? range.from() : range.to() } + return cursorCoords(this, pos, mode || "page") }, charCoords: function(pos, mode) { - return charCoords(this, clipPos(this.doc, pos), mode || "page"); + return charCoords(this, clipPos(this.doc, pos), mode || "page") }, coordsChar: function(coords, mode) { - coords = fromCoordSystem(this, coords, mode || "page"); - return coordsChar(this, coords.left, coords.top); + coords = fromCoordSystem(this, coords, mode || "page") + return coordsChar(this, coords.left, coords.top) }, lineAtHeight: function(height, mode) { - height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top; - return lineAtHeight(this.doc, height + this.display.viewOffset); + height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top + return lineAtHeight(this.doc, height + this.display.viewOffset) }, - heightAtLine: function(line, mode) { - var end = false, last = this.doc.first + this.doc.size - 1; - if (line < this.doc.first) line = this.doc.first; - else if (line > last) { line = last; end = true; } - var lineObj = getLine(this.doc, line); - return intoCoordSystem(this, getLine(this.doc, line), {top: 0, left: 0}, mode || "page").top + - (end ? lineObj.height : 0); - }, - - defaultTextHeight: function() { return textHeight(this.display); }, - defaultCharWidth: function() { return charWidth(this.display); }, - - setGutterMarker: operation(null, function(line, gutterID, value) { - return changeLine(this, line, function(line) { - var markers = line.gutterMarkers || (line.gutterMarkers = {}); - markers[gutterID] = value; - if (!value && isEmpty(markers)) line.gutterMarkers = null; - return true; - }); - }), - - clearGutter: operation(null, function(gutterID) { - var cm = this, doc = cm.doc, i = doc.first; - doc.iter(function(line) { - if (line.gutterMarkers && line.gutterMarkers[gutterID]) { - line.gutterMarkers[gutterID] = null; - regChange(cm, i, i + 1); - if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null; - } - ++i; - }); - }), - - addLineClass: operation(null, function(handle, where, cls) { - return changeLine(this, handle, function(line) { - var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass"; - if (!line[prop]) line[prop] = cls; - else if (new RegExp("(?:^|\\s)" + cls + "(?:$|\\s)").test(line[prop])) return false; - else line[prop] += " " + cls; - return true; - }); - }), - - removeLineClass: operation(null, function(handle, where, cls) { - return changeLine(this, handle, function(line) { - var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass"; - var cur = line[prop]; - if (!cur) return false; - else if (cls == null) line[prop] = null; - else { - var found = cur.match(new RegExp("(?:^|\\s+)" + cls + "(?:$|\\s+)")); - if (!found) return false; - var end = found.index + found[0].length; - line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null; - } - return true; - }); - }), - - addLineWidget: operation(null, function(handle, node, options) { - return addLineWidget(this, handle, node, options); - }), - - removeLineWidget: function(widget) { widget.clear(); }, - - lineInfo: function(line) { + heightAtLine: function(line, mode, includeWidgets) { + var end = false, lineObj if (typeof line == "number") { - if (!isLine(this.doc, line)) return null; - var n = line; - line = getLine(this.doc, line); - if (!line) return null; + var last = this.doc.first + this.doc.size - 1 + if (line < this.doc.first) { line = this.doc.first } + else if (line > last) { line = last; end = true } + lineObj = getLine(this.doc, line) } else { - var n = lineNo(line); - if (n == null) return null; + lineObj = line } - return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers, - textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass, - widgets: line.widgets}; + return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets).top + + (end ? this.doc.height - heightAtLine(lineObj) : 0) }, - getViewport: function() { return {from: this.display.showingFrom, to: this.display.showingTo};}, + defaultTextHeight: function() { return textHeight(this.display) }, + defaultCharWidth: function() { return charWidth(this.display) }, + + getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}}, addWidget: function(pos, node, scroll, vert, horiz) { - var display = this.display; - pos = cursorCoords(this, clipPos(this.doc, pos)); - var top = pos.bottom, left = pos.left; - node.style.position = "absolute"; - display.sizer.appendChild(node); + var display = this.display + pos = cursorCoords(this, clipPos(this.doc, pos)) + var top = pos.bottom, left = pos.left + node.style.position = "absolute" + node.setAttribute("cm-ignore-events", "true") + this.display.input.setUneditable(node) + display.sizer.appendChild(node) if (vert == "over") { - top = pos.top; + top = pos.top } else if (vert == "above" || vert == "near") { var vspace = Math.max(display.wrapper.clientHeight, this.doc.height), - hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth); + hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth) // Default to positioning above (if specified and possible); otherwise default to positioning below if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) - top = pos.top - node.offsetHeight; + { top = pos.top - node.offsetHeight } else if (pos.bottom + node.offsetHeight <= vspace) - top = pos.bottom; + { top = pos.bottom } if (left + node.offsetWidth > hspace) - left = hspace - node.offsetWidth; + { left = hspace - node.offsetWidth } } - node.style.top = top + "px"; - node.style.left = node.style.right = ""; + node.style.top = top + "px" + node.style.left = node.style.right = "" if (horiz == "right") { - left = display.sizer.clientWidth - node.offsetWidth; - node.style.right = "0px"; + left = display.sizer.clientWidth - node.offsetWidth + node.style.right = "0px" } else { - if (horiz == "left") left = 0; - else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2; - node.style.left = left + "px"; + if (horiz == "left") { left = 0 } + else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2 } + node.style.left = left + "px" } if (scroll) - scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight); + { scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight) } }, - triggerOnKeyDown: operation(null, onKeyDown), + triggerOnKeyDown: methodOp(onKeyDown), + triggerOnKeyPress: methodOp(onKeyPress), + triggerOnKeyUp: onKeyUp, + + execCommand: function(cmd) { + if (commands.hasOwnProperty(cmd)) + { return commands[cmd].call(null, this) } + }, - execCommand: function(cmd) {return commands[cmd](this);}, + triggerElectric: methodOp(function(text) { triggerElectric(this, text) }), findPosH: function(from, amount, unit, visually) { - var dir = 1; - if (amount < 0) { dir = -1; amount = -amount; } - for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { - cur = findPosH(this.doc, cur, dir, unit, visually); - if (cur.hitSide) break; + var this$1 = this; + + var dir = 1 + if (amount < 0) { dir = -1; amount = -amount } + var cur = clipPos(this.doc, from) + for (var i = 0; i < amount; ++i) { + cur = findPosH(this$1.doc, cur, dir, unit, visually) + if (cur.hitSide) { break } } - return cur; + return cur }, - moveH: operation(null, function(dir, unit) { - var sel = this.doc.sel, pos; - if (sel.shift || sel.extend || posEq(sel.from, sel.to)) - pos = findPosH(this.doc, sel.head, dir, unit, this.options.rtlMoveVisually); - else - pos = dir < 0 ? sel.from : sel.to; - extendSelection(this.doc, pos, pos, dir); + moveH: methodOp(function(dir, unit) { + var this$1 = this; + + this.extendSelectionsBy(function (range) { + if (this$1.display.shift || this$1.doc.extend || range.empty()) + { return findPosH(this$1.doc, range.head, dir, unit, this$1.options.rtlMoveVisually) } + else + { return dir < 0 ? range.from() : range.to() } + }, sel_move) }), - deleteH: operation(null, function(dir, unit) { - var sel = this.doc.sel; - if (!posEq(sel.from, sel.to)) replaceRange(this.doc, "", sel.from, sel.to, "+delete"); - else replaceRange(this.doc, "", sel.from, findPosH(this.doc, sel.head, dir, unit, false), "+delete"); - this.curOp.userSelChange = true; + deleteH: methodOp(function(dir, unit) { + var sel = this.doc.sel, doc = this.doc + if (sel.somethingSelected()) + { doc.replaceSelection("", null, "+delete") } + else + { deleteNearSelection(this, function (range) { + var other = findPosH(doc, range.head, dir, unit, false) + return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other} + }) } }), findPosV: function(from, amount, unit, goalColumn) { - var dir = 1, x = goalColumn; - if (amount < 0) { dir = -1; amount = -amount; } - for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { - var coords = cursorCoords(this, cur, "div"); - if (x == null) x = coords.left; - else coords.left = x; - cur = findPosV(this, coords, dir, unit); - if (cur.hitSide) break; + var this$1 = this; + + var dir = 1, x = goalColumn + if (amount < 0) { dir = -1; amount = -amount } + var cur = clipPos(this.doc, from) + for (var i = 0; i < amount; ++i) { + var coords = cursorCoords(this$1, cur, "div") + if (x == null) { x = coords.left } + else { coords.left = x } + cur = findPosV(this$1, coords, dir, unit) + if (cur.hitSide) { break } } - return cur; + return cur }, - moveV: operation(null, function(dir, unit) { - var sel = this.doc.sel; - var pos = cursorCoords(this, sel.head, "div"); - if (sel.goalColumn != null) pos.left = sel.goalColumn; - var target = findPosV(this, pos, dir, unit); - - if (unit == "page") addToScrollPos(this, 0, charCoords(this, target, "div").top - pos.top); - extendSelection(this.doc, target, target, dir); - sel.goalColumn = pos.left; + moveV: methodOp(function(dir, unit) { + var this$1 = this; + + var doc = this.doc, goals = [] + var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected() + doc.extendSelectionsBy(function (range) { + if (collapse) + { return dir < 0 ? range.from() : range.to() } + var headPos = cursorCoords(this$1, range.head, "div") + if (range.goalColumn != null) { headPos.left = range.goalColumn } + goals.push(headPos.left) + var pos = findPosV(this$1, headPos, dir, unit) + if (unit == "page" && range == doc.sel.primary()) + { addToScrollPos(this$1, null, charCoords(this$1, pos, "div").top - headPos.top) } + return pos + }, sel_move) + if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++) + { doc.sel.ranges[i].goalColumn = goals[i] } } }), + // Find the word at the given position (as returned by coordsChar). + findWordAt: function(pos) { + var doc = this.doc, line = getLine(doc, pos.line).text + var start = pos.ch, end = pos.ch + if (line) { + var helper = this.getHelper(pos, "wordChars") + if ((pos.xRel < 0 || end == line.length) && start) { --start; } else { ++end } + var startChar = line.charAt(start) + var check = isWordChar(startChar, helper) + ? function (ch) { return isWordChar(ch, helper); } + : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); } + : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); } + while (start > 0 && check(line.charAt(start - 1))) { --start } + while (end < line.length && check(line.charAt(end))) { ++end } + } + return new Range(Pos(pos.line, start), Pos(pos.line, end)) + }, + toggleOverwrite: function(value) { - if (value != null && value == this.state.overwrite) return; + if (value != null && value == this.state.overwrite) { return } if (this.state.overwrite = !this.state.overwrite) - this.display.cursor.className += " CodeMirror-overwrite"; + { addClass(this.display.cursorDiv, "CodeMirror-overwrite") } else - this.display.cursor.className = this.display.cursor.className.replace(" CodeMirror-overwrite", ""); + { rmClass(this.display.cursorDiv, "CodeMirror-overwrite") } + + signal(this, "overwriteToggle", this, this.state.overwrite) }, - hasFocus: function() { return this.state.focused; }, + hasFocus: function() { return this.display.input.getField() == activeElt() }, + isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) }, - scrollTo: operation(null, function(x, y) { - updateScrollPos(this, x, y); + scrollTo: methodOp(function(x, y) { + if (x != null || y != null) { resolveScrollToPos(this) } + if (x != null) { this.curOp.scrollLeft = x } + if (y != null) { this.curOp.scrollTop = y } }), getScrollInfo: function() { - var scroller = this.display.scroller, co = scrollerCutOff; + var scroller = this.display.scroller return {left: scroller.scrollLeft, top: scroller.scrollTop, - height: scroller.scrollHeight - co, width: scroller.scrollWidth - co, - clientHeight: scroller.clientHeight - co, clientWidth: scroller.clientWidth - co}; + height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight, + width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth, + clientHeight: displayHeight(this), clientWidth: displayWidth(this)} }, - scrollIntoView: operation(null, function(range, margin) { - if (range == null) range = {from: this.doc.sel.head, to: null}; - else if (typeof range == "number") range = {from: Pos(range, 0), to: null}; - else if (range.from == null) range = {from: range, to: null}; - if (!range.to) range.to = range.from; - if (!margin) margin = 0; + scrollIntoView: methodOp(function(range, margin) { + if (range == null) { + range = {from: this.doc.sel.primary().head, to: null} + if (margin == null) { margin = this.options.cursorScrollMargin } + } else if (typeof range == "number") { + range = {from: Pos(range, 0), to: null} + } else if (range.from == null) { + range = {from: range, to: null} + } + if (!range.to) { range.to = range.from } + range.margin = margin || 0 - var coords = range; if (range.from.line != null) { - this.curOp.scrollToPos = {from: range.from, to: range.to, margin: margin}; - coords = {from: cursorCoords(this, range.from), - to: cursorCoords(this, range.to)}; + resolveScrollToPos(this) + this.curOp.scrollToPos = range + } else { + var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left), + Math.min(range.from.top, range.to.top) - range.margin, + Math.max(range.from.right, range.to.right), + Math.max(range.from.bottom, range.to.bottom) + range.margin) + this.scrollTo(sPos.scrollLeft, sPos.scrollTop) } - var sPos = calculateScrollPos(this, Math.min(coords.from.left, coords.to.left), - Math.min(coords.from.top, coords.to.top) - margin, - Math.max(coords.from.right, coords.to.right), - Math.max(coords.from.bottom, coords.to.bottom) + margin); - updateScrollPos(this, sPos.scrollLeft, sPos.scrollTop); }), - setSize: operation(null, function(width, height) { - function interpret(val) { - return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; - } - if (width != null) this.display.wrapper.style.width = interpret(width); - if (height != null) this.display.wrapper.style.height = interpret(height); - if (this.options.lineWrapping) - this.display.measureLineCache.length = this.display.measureLineCachePos = 0; - this.curOp.forceUpdate = true; + setSize: methodOp(function(width, height) { + var this$1 = this; + + var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; } + if (width != null) { this.display.wrapper.style.width = interpret(width) } + if (height != null) { this.display.wrapper.style.height = interpret(height) } + if (this.options.lineWrapping) { clearLineMeasurementCache(this) } + var lineNo = this.display.viewFrom + this.doc.iter(lineNo, this.display.viewTo, function (line) { + if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) + { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo, "widget"); break } } } + ++lineNo + }) + this.curOp.forceUpdate = true + signal(this, "refresh", this) }), - operation: function(f){return runInOp(this, f);}, - - refresh: operation(null, function() { - var badHeight = this.display.cachedTextHeight == null; - clearCaches(this); - updateScrollPos(this, this.doc.scrollLeft, this.doc.scrollTop); - regChange(this); - if (badHeight) estimateLineHeights(this); + operation: function(f){return runInOp(this, f)}, + + refresh: methodOp(function() { + var oldHeight = this.display.cachedTextHeight + regChange(this) + this.curOp.forceUpdate = true + clearCaches(this) + this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop) + updateGutterSpace(this) + if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5) + { estimateLineHeights(this) } + signal(this, "refresh", this) }), - swapDoc: operation(null, function(doc) { - var old = this.doc; - old.cm = null; - attachDoc(this, doc); - clearCaches(this); - resetInput(this, true); - updateScrollPos(this, doc.scrollLeft, doc.scrollTop); - signalLater(this, "swapDoc", this, old); - return old; + swapDoc: methodOp(function(doc) { + var old = this.doc + old.cm = null + attachDoc(this, doc) + clearCaches(this) + this.display.input.reset() + this.scrollTo(doc.scrollLeft, doc.scrollTop) + this.curOp.forceScroll = true + signalLater(this, "swapDoc", this, old) + return old }), - getInputField: function(){return this.display.input;}, - getWrapperElement: function(){return this.display.wrapper;}, - getScrollerElement: function(){return this.display.scroller;}, - getGutterElement: function(){return this.display.gutters;} - }; - eventMixin(CodeMirror); - - // OPTION DEFAULTS - - var optionHandlers = CodeMirror.optionHandlers = {}; - - // The default configuration options. - var defaults = CodeMirror.defaults = {}; - - function option(name, deflt, handle, notOnInit) { - CodeMirror.defaults[name] = deflt; - if (handle) optionHandlers[name] = - notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle; + getInputField: function(){return this.display.input.getField()}, + getWrapperElement: function(){return this.display.wrapper}, + getScrollerElement: function(){return this.display.scroller}, + getGutterElement: function(){return this.display.gutters} } + eventMixin(CodeMirror) - var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}}; + CodeMirror.registerHelper = function(type, name, value) { + if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []} } + helpers[type][name] = value + } + CodeMirror.registerGlobalHelper = function(type, name, predicate, value) { + CodeMirror.registerHelper(type, name, value) + helpers[type]._global.push({pred: predicate, val: value}) + } +} + +// Used for horizontal relative motion. Dir is -1 or 1 (left or +// right), unit can be "char", "column" (like char, but doesn't +// cross line boundaries), "word" (across next word), or "group" (to +// the start of next group of word or non-word-non-whitespace +// chars). The visually param controls whether, in right-to-left +// text, direction 1 means to move towards the next index in the +// string, or towards the character to the right of the current +// position. The resulting position will have a hitSide=true +// property if it reached the end of the document. +function findPosH(doc, pos, dir, unit, visually) { + var line = pos.line, ch = pos.ch, origDir = dir + var lineObj = getLine(doc, line) + function findNextLine() { + var l = line + dir + if (l < doc.first || l >= doc.first + doc.size) { return false } + line = l + return lineObj = getLine(doc, l) + } + function moveOnce(boundToLine) { + var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true) + if (next == null) { + if (!boundToLine && findNextLine()) { + if (visually) { ch = (dir < 0 ? lineRight : lineLeft)(lineObj) } + else { ch = dir < 0 ? lineObj.text.length : 0 } + } else { return false } + } else { ch = next } + return true + } + + if (unit == "char") { + moveOnce() + } else if (unit == "column") { + moveOnce(true) + } else if (unit == "word" || unit == "group") { + var sawType = null, group = unit == "group" + var helper = doc.cm && doc.cm.getHelper(pos, "wordChars") + for (var first = true;; first = false) { + if (dir < 0 && !moveOnce(!first)) { break } + var cur = lineObj.text.charAt(ch) || "\n" + var type = isWordChar(cur, helper) ? "w" + : group && cur == "\n" ? "n" + : !group || /\s/.test(cur) ? null + : "p" + if (group && !first && !type) { type = "s" } + if (sawType && sawType != type) { + if (dir < 0) {dir = 1; moveOnce()} + break + } - // These two are, on init, called from the constructor because they - // have to be initialized before the editor can start at all. - option("value", "", function(cm, val) { - cm.setValue(val); - }, true); - option("mode", null, function(cm, val) { - cm.doc.modeOption = val; - loadMode(cm); - }, true); - - option("indentUnit", 2, loadMode, true); - option("indentWithTabs", false); - option("smartIndent", true); - option("tabSize", 4, function(cm) { - loadMode(cm); - clearCaches(cm); - regChange(cm); - }, true); - option("specialChars", /[\t\u0000-\u0019\u00ad\u200b\u2028\u2029\ufeff]/g, function(cm, val) { - cm.options.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g"); - cm.refresh(); - }, true); - option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true); - option("electricChars", true); - option("rtlMoveVisually", !windows); - option("wholeLineUpdateBefore", true); - - option("theme", "default", function(cm) { - themeChanged(cm); - guttersChanged(cm); - }, true); - option("keyMap", "default", keyMapChanged); - option("extraKeys", null); - - option("onKeyEvent", null); - option("onDragEvent", null); - - option("lineWrapping", false, wrappingChanged, true); - option("gutters", [], function(cm) { - setGuttersForLineNumbers(cm.options); - guttersChanged(cm); - }, true); - option("fixedGutter", true, function(cm, val) { - cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"; - cm.refresh(); - }, true); - option("coverGutterNextToScrollbar", false, updateScrollbars, true); - option("lineNumbers", false, function(cm) { - setGuttersForLineNumbers(cm.options); - guttersChanged(cm); - }, true); - option("firstLineNumber", 1, guttersChanged, true); - option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true); - option("showCursorWhenSelecting", false, updateSelection, true); - - option("resetSelectionOnContextMenu", true); - - option("readOnly", false, function(cm, val) { - if (val == "nocursor") { - onBlur(cm); - cm.display.input.blur(); - cm.display.disabled = true; + if (type) { sawType = type } + if (dir > 0 && !moveOnce(!first)) { break } + } + } + var result = skipAtomic(doc, Pos(line, ch), pos, origDir, true) + if (!cmp(pos, result)) { result.hitSide = true } + return result +} + +// For relative vertical movement. Dir may be -1 or 1. Unit can be +// "page" or "line". The resulting position will have a hitSide=true +// property if it reached the end of the document. +function findPosV(cm, pos, dir, unit) { + var doc = cm.doc, x = pos.left, y + if (unit == "page") { + var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight) + var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3) + y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount + + } else if (unit == "line") { + y = dir > 0 ? pos.bottom + 3 : pos.top - 3 + } + var target + for (;;) { + target = coordsChar(cm, x, y) + if (!target.outside) { break } + if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break } + y += dir * 5 + } + return target +} + +// CONTENTEDITABLE INPUT STYLE + +var ContentEditableInput = function(cm) { + this.cm = cm + this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null + this.polling = new Delayed() + this.composing = null + this.gracePeriod = false + this.readDOMTimeout = null +}; + +ContentEditableInput.prototype.init = function (display) { + var this$1 = this; + + var input = this, cm = input.cm + var div = input.div = display.lineDiv + disableBrowserMagic(div, cm.options.spellcheck) + + on(div, "paste", function (e) { + if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return } + // IE doesn't fire input events, so we schedule a read for the pasted content in this way + if (ie_version <= 11) { setTimeout(operation(cm, function () { + if (!input.pollContent()) { regChange(cm) } + }), 20) } + }) + + on(div, "compositionstart", function (e) { + this$1.composing = {data: e.data, done: false} + }) + on(div, "compositionupdate", function (e) { + if (!this$1.composing) { this$1.composing = {data: e.data, done: false} } + }) + on(div, "compositionend", function (e) { + if (this$1.composing) { + if (e.data != this$1.composing.data) { this$1.readFromDOMSoon() } + this$1.composing.done = true + } + }) + + on(div, "touchstart", function () { return input.forceCompositionEnd(); }) + + on(div, "input", function () { + if (!this$1.composing) { this$1.readFromDOMSoon() } + }) + + function onCopyCut(e) { + if (signalDOMEvent(cm, e)) { return } + if (cm.somethingSelected()) { + setLastCopied({lineWise: false, text: cm.getSelections()}) + if (e.type == "cut") { cm.replaceSelection("", null, "cut") } + } else if (!cm.options.lineWiseCopyCut) { + return } else { - cm.display.disabled = false; - if (!val) resetInput(cm, true); - } - }); - option("dragDrop", true); - - option("cursorBlinkRate", 530); - option("cursorScrollMargin", 0); - option("cursorHeight", 1); - option("workTime", 100); - option("workDelay", 100); - option("flattenSpans", true); - option("pollInterval", 100); - option("undoDepth", 40, function(cm, val){cm.doc.history.undoDepth = val;}); - option("historyEventDelay", 500); - option("viewportMargin", 10, function(cm){cm.refresh();}, true); - option("maxHighlightLength", 10000, function(cm){loadMode(cm); cm.refresh();}, true); - option("crudeMeasuringFrom", 10000); - option("moveInputWithCursor", true, function(cm, val) { - if (!val) cm.display.inputDiv.style.top = cm.display.inputDiv.style.left = 0; - }); - - option("tabindex", null, function(cm, val) { - cm.display.input.tabIndex = val || ""; - }); - option("autofocus", null); - - // MODE DEFINITION AND QUERYING - - // Known modes, by name and by MIME - var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {}; - - CodeMirror.defineMode = function(name, mode) { - if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name; - if (arguments.length > 2) { - mode.dependencies = []; - for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(arguments[i]); - } - modes[name] = mode; - }; - - CodeMirror.defineMIME = function(mime, spec) { - mimeModes[mime] = spec; - }; - - CodeMirror.resolveMode = function(spec) { - if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { - spec = mimeModes[spec]; - } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) { - var found = mimeModes[spec.name]; - spec = createObj(found, spec); - spec.name = found.name; - } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) { - return CodeMirror.resolveMode("application/xml"); - } - if (typeof spec == "string") return {name: spec}; - else return spec || {name: "null"}; - }; - - CodeMirror.getMode = function(options, spec) { - var spec = CodeMirror.resolveMode(spec); - var mfactory = modes[spec.name]; - if (!mfactory) return CodeMirror.getMode(options, "text/plain"); - var modeObj = mfactory(options, spec); - if (modeExtensions.hasOwnProperty(spec.name)) { - var exts = modeExtensions[spec.name]; - for (var prop in exts) { - if (!exts.hasOwnProperty(prop)) continue; - if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop]; - modeObj[prop] = exts[prop]; + var ranges = copyableRanges(cm) + setLastCopied({lineWise: true, text: ranges.text}) + if (e.type == "cut") { + cm.operation(function () { + cm.setSelections(ranges.ranges, 0, sel_dontScroll) + cm.replaceSelection("", null, "cut") + }) } } - modeObj.name = spec.name; - - return modeObj; - }; - - CodeMirror.defineMode("null", function() { - return {token: function(stream) {stream.skipToEnd();}}; - }); - CodeMirror.defineMIME("text/plain", "null"); - - var modeExtensions = CodeMirror.modeExtensions = {}; - CodeMirror.extendMode = function(mode, properties) { - var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}); - copyObj(properties, exts); - }; - - // EXTENSIONS - - CodeMirror.defineExtension = function(name, func) { - CodeMirror.prototype[name] = func; - }; - CodeMirror.defineDocExtension = function(name, func) { - Doc.prototype[name] = func; - }; - CodeMirror.defineOption = option; - - var initHooks = []; - CodeMirror.defineInitHook = function(f) {initHooks.push(f);}; - - var helpers = CodeMirror.helpers = {}; - CodeMirror.registerHelper = function(type, name, value) { - if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {}; - helpers[type][name] = value; - }; - - // UTILITIES - - CodeMirror.isWordChar = isWordChar; - - // MODE STATE HANDLING - - // Utility functions for working with state. Exported because modes - // sometimes need to do this. - function copyState(mode, state) { - if (state === true) return state; - if (mode.copyState) return mode.copyState(state); - var nstate = {}; - for (var n in state) { - var val = state[n]; - if (val instanceof Array) val = val.concat([]); - nstate[n] = val; - } - return nstate; - } - CodeMirror.copyState = copyState; - - function startState(mode, a1, a2) { - return mode.startState ? mode.startState(a1, a2) : true; - } - CodeMirror.startState = startState; - - CodeMirror.innerMode = function(mode, state) { - while (mode.innerMode) { - var info = mode.innerMode(state); - if (!info || info.mode == mode) break; - state = info.state; - mode = info.mode; + if (e.clipboardData) { + e.clipboardData.clearData() + var content = lastCopied.text.join("\n") + // iOS exposes the clipboard API, but seems to discard content inserted into it + e.clipboardData.setData("Text", content) + if (e.clipboardData.getData("Text") == content) { + e.preventDefault() + return + } } - return info || {mode: mode, state: state}; - }; - - // STANDARD COMMANDS - - var commands = CodeMirror.commands = { - selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()));}, - killLine: function(cm) { - var from = cm.getCursor(true), to = cm.getCursor(false), sel = !posEq(from, to); - if (!sel && cm.getLine(from.line).length == from.ch) - cm.replaceRange("", from, Pos(from.line + 1, 0), "+delete"); - else cm.replaceRange("", from, sel ? to : Pos(from.line), "+delete"); - }, - deleteLine: function(cm) { - var l = cm.getCursor().line; - cm.replaceRange("", Pos(l, 0), Pos(l), "+delete"); - }, - delLineLeft: function(cm) { - var cur = cm.getCursor(); - cm.replaceRange("", Pos(cur.line, 0), cur, "+delete"); - }, - undo: function(cm) {cm.undo();}, - redo: function(cm) {cm.redo();}, - goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));}, - goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));}, - goLineStart: function(cm) { - cm.extendSelection(lineStart(cm, cm.getCursor().line)); - }, - goLineStartSmart: function(cm) { - var cur = cm.getCursor(), start = lineStart(cm, cur.line); - var line = cm.getLineHandle(start.line); - var order = getOrder(line); - if (!order || order[0].level == 0) { - var firstNonWS = Math.max(0, line.text.search(/\S/)); - var inWS = cur.line == start.line && cur.ch <= firstNonWS && cur.ch; - cm.extendSelection(Pos(start.line, inWS ? 0 : firstNonWS)); - } else cm.extendSelection(start); - }, - goLineEnd: function(cm) { - cm.extendSelection(lineEnd(cm, cm.getCursor().line)); - }, - goLineRight: function(cm) { - var top = cm.charCoords(cm.getCursor(), "div").top + 5; - cm.extendSelection(cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")); - }, - goLineLeft: function(cm) { - var top = cm.charCoords(cm.getCursor(), "div").top + 5; - cm.extendSelection(cm.coordsChar({left: 0, top: top}, "div")); - }, - goLineUp: function(cm) {cm.moveV(-1, "line");}, - goLineDown: function(cm) {cm.moveV(1, "line");}, - goPageUp: function(cm) {cm.moveV(-1, "page");}, - goPageDown: function(cm) {cm.moveV(1, "page");}, - goCharLeft: function(cm) {cm.moveH(-1, "char");}, - goCharRight: function(cm) {cm.moveH(1, "char");}, - goColumnLeft: function(cm) {cm.moveH(-1, "column");}, - goColumnRight: function(cm) {cm.moveH(1, "column");}, - goWordLeft: function(cm) {cm.moveH(-1, "word");}, - goGroupRight: function(cm) {cm.moveH(1, "group");}, - goGroupLeft: function(cm) {cm.moveH(-1, "group");}, - goWordRight: function(cm) {cm.moveH(1, "word");}, - delCharBefore: function(cm) {cm.deleteH(-1, "char");}, - delCharAfter: function(cm) {cm.deleteH(1, "char");}, - delWordBefore: function(cm) {cm.deleteH(-1, "word");}, - delWordAfter: function(cm) {cm.deleteH(1, "word");}, - delGroupBefore: function(cm) {cm.deleteH(-1, "group");}, - delGroupAfter: function(cm) {cm.deleteH(1, "group");}, - indentAuto: function(cm) {cm.indentSelection("smart");}, - indentMore: function(cm) {cm.indentSelection("add");}, - indentLess: function(cm) {cm.indentSelection("subtract");}, - insertTab: function(cm) {cm.replaceSelection("\t", "end", "+input");}, - defaultTab: function(cm) { - if (cm.somethingSelected()) cm.indentSelection("add"); - else cm.replaceSelection("\t", "end", "+input"); - }, - transposeChars: function(cm) { - var cur = cm.getCursor(), line = cm.getLine(cur.line); - if (cur.ch > 0 && cur.ch < line.length - 1) - cm.replaceRange(line.charAt(cur.ch) + line.charAt(cur.ch - 1), - Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1)); - }, - newlineAndIndent: function(cm) { - operation(cm, function() { - cm.replaceSelection("\n", "end", "+input"); - cm.indentLine(cm.getCursor().line, null, true); - })(); - }, - toggleOverwrite: function(cm) {cm.toggleOverwrite();} - }; - - // STANDARD KEYMAPS - - var keyMap = CodeMirror.keyMap = {}; - keyMap.basic = { - "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown", - "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown", - "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore", - "Tab": "defaultTab", "Shift-Tab": "indentAuto", - "Enter": "newlineAndIndent", "Insert": "toggleOverwrite" - }; - // Note that the save and find-related commands aren't defined by - // default. Unknown commands are simply ignored. - keyMap.pcDefault = { - "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo", - "Ctrl-Home": "goDocStart", "Alt-Up": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Down": "goDocEnd", - "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd", - "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find", - "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll", - "Ctrl-[": "indentLess", "Ctrl-]": "indentMore", - fallthrough: "basic" - }; - keyMap.macDefault = { - "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo", - "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft", - "Alt-Right": "goGroupRight", "Cmd-Left": "goLineStart", "Cmd-Right": "goLineEnd", "Alt-Backspace": "delGroupBefore", - "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find", - "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll", - "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delLineLeft", - fallthrough: ["basic", "emacsy"] - }; - keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; - keyMap.emacsy = { - "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown", - "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", - "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", - "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars" - }; - - // KEYMAP DISPATCH - - function getKeyMap(val) { - if (typeof val == "string") return keyMap[val]; - else return val; - } - - function lookupKey(name, maps, handle) { - function lookup(map) { - map = getKeyMap(map); - var found = map[name]; - if (found === false) return "stop"; - if (found != null && handle(found)) return true; - if (map.nofallthrough) return "stop"; - - var fallthrough = map.fallthrough; - if (fallthrough == null) return false; - if (Object.prototype.toString.call(fallthrough) != "[object Array]") - return lookup(fallthrough); - for (var i = 0, e = fallthrough.length; i < e; ++i) { - var done = lookup(fallthrough[i]); - if (done) return done; + // Old-fashioned briefly-focus-a-textarea hack + var kludge = hiddenTextarea(), te = kludge.firstChild + cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild) + te.value = lastCopied.text.join("\n") + var hadFocus = document.activeElement + selectInput(te) + setTimeout(function () { + cm.display.lineSpace.removeChild(kludge) + hadFocus.focus() + if (hadFocus == div) { input.showPrimarySelection() } + }, 50) + } + on(div, "copy", onCopyCut) + on(div, "cut", onCopyCut) +}; + +ContentEditableInput.prototype.prepareSelection = function () { + var result = prepareSelection(this.cm, false) + result.focus = this.cm.state.focused + return result +}; + +ContentEditableInput.prototype.showSelection = function (info, takeFocus) { + if (!info || !this.cm.display.view.length) { return } + if (info.focus || takeFocus) { this.showPrimarySelection() } + this.showMultipleSelections(info) +}; + +ContentEditableInput.prototype.showPrimarySelection = function () { + var sel = window.getSelection(), prim = this.cm.doc.sel.primary() + var curAnchor = domToPos(this.cm, sel.anchorNode, sel.anchorOffset) + var curFocus = domToPos(this.cm, sel.focusNode, sel.focusOffset) + if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad && + cmp(minPos(curAnchor, curFocus), prim.from()) == 0 && + cmp(maxPos(curAnchor, curFocus), prim.to()) == 0) + { return } + + var start = posToDOM(this.cm, prim.from()) + var end = posToDOM(this.cm, prim.to()) + if (!start && !end) { return } + + var view = this.cm.display.view + var old = sel.rangeCount && sel.getRangeAt(0) + if (!start) { + start = {node: view[0].measure.map[2], offset: 0} + } else if (!end) { // FIXME dangerously hacky + var measure = view[view.length - 1].measure + var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map + end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]} + } + + var rng + try { rng = range(start.node, start.offset, end.offset, end.node) } + catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible + if (rng) { + if (!gecko && this.cm.state.focused) { + sel.collapse(start.node, start.offset) + if (!rng.collapsed) { + sel.removeAllRanges() + sel.addRange(rng) } - return false; - } - - for (var i = 0; i < maps.length; ++i) { - var done = lookup(maps[i]); - if (done) return done != "stop"; - } - } - function isModifierKey(event) { - var name = keyNames[event.keyCode]; - return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"; - } - function keyName(event, noShift) { - if (opera && event.keyCode == 34 && event["char"]) return false; - var name = keyNames[event.keyCode]; - if (name == null || event.altGraphKey) return false; - if (event.altKey) name = "Alt-" + name; - if (flipCtrlCmd ? event.metaKey : event.ctrlKey) name = "Ctrl-" + name; - if (flipCtrlCmd ? event.ctrlKey : event.metaKey) name = "Cmd-" + name; - if (!noShift && event.shiftKey) name = "Shift-" + name; - return name; - } - CodeMirror.lookupKey = lookupKey; - CodeMirror.isModifierKey = isModifierKey; - CodeMirror.keyName = keyName; - - // FROMTEXTAREA - - CodeMirror.fromTextArea = function(textarea, options) { - if (!options) options = {}; - options.value = textarea.value; - if (!options.tabindex && textarea.tabindex) - options.tabindex = textarea.tabindex; - if (!options.placeholder && textarea.placeholder) - options.placeholder = textarea.placeholder; - // Set autofocus to true if this textarea is focused, or if it has - // autofocus and no other element is focused. - if (options.autofocus == null) { - var hasFocus = document.body; - // doc.activeElement occasionally throws on IE - try { hasFocus = document.activeElement; } catch(e) {} - options.autofocus = hasFocus == textarea || - textarea.getAttribute("autofocus") != null && hasFocus == document.body; - } - - function save() {textarea.value = cm.getValue();} - if (textarea.form) { - on(textarea.form, "submit", save); - // Deplorable hack to make the submit method do the right thing. - if (!options.leaveSubmitMethodAlone) { - var form = textarea.form, realSubmit = form.submit; - try { - var wrappedSubmit = form.submit = function() { - save(); - form.submit = realSubmit; - form.submit(); - form.submit = wrappedSubmit; - }; - } catch(e) {} + } else { + sel.removeAllRanges() + sel.addRange(rng) + } + if (old && sel.anchorNode == null) { sel.addRange(old) } + else if (gecko) { this.startGracePeriod() } + } + this.rememberSelection() +}; + +ContentEditableInput.prototype.startGracePeriod = function () { + var this$1 = this; + + clearTimeout(this.gracePeriod) + this.gracePeriod = setTimeout(function () { + this$1.gracePeriod = false + if (this$1.selectionChanged()) + { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }) } + }, 20) +}; + +ContentEditableInput.prototype.showMultipleSelections = function (info) { + removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors) + removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection) +}; + +ContentEditableInput.prototype.rememberSelection = function () { + var sel = window.getSelection() + this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset + this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset +}; + +ContentEditableInput.prototype.selectionInEditor = function () { + var sel = window.getSelection() + if (!sel.rangeCount) { return false } + var node = sel.getRangeAt(0).commonAncestorContainer + return contains(this.div, node) +}; + +ContentEditableInput.prototype.focus = function () { + if (this.cm.options.readOnly != "nocursor") { + if (!this.selectionInEditor()) + { this.showSelection(this.prepareSelection(), true) } + this.div.focus() + } +}; +ContentEditableInput.prototype.blur = function () { this.div.blur() }; +ContentEditableInput.prototype.getField = function () { return this.div }; + +ContentEditableInput.prototype.supportsTouch = function () { return true }; + +ContentEditableInput.prototype.receivedFocus = function () { + var input = this + if (this.selectionInEditor()) + { this.pollSelection() } + else + { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }) } + + function poll() { + if (input.cm.state.focused) { + input.pollSelection() + input.polling.set(input.cm.options.pollInterval, poll) + } + } + this.polling.set(this.cm.options.pollInterval, poll) +}; + +ContentEditableInput.prototype.selectionChanged = function () { + var sel = window.getSelection() + return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset || + sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset +}; + +ContentEditableInput.prototype.pollSelection = function () { + if (!this.composing && this.readDOMTimeout == null && !this.gracePeriod && this.selectionChanged()) { + var sel = window.getSelection(), cm = this.cm + this.rememberSelection() + var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset) + var head = domToPos(cm, sel.focusNode, sel.focusOffset) + if (anchor && head) { runInOp(cm, function () { + setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll) + if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true } + }) } + } +}; + +ContentEditableInput.prototype.pollContent = function () { + if (this.readDOMTimeout != null) { + clearTimeout(this.readDOMTimeout) + this.readDOMTimeout = null + } + + var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary() + var from = sel.from(), to = sel.to() + if (from.ch == 0 && from.line > cm.firstLine()) + { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length) } + if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine()) + { to = Pos(to.line + 1, 0) } + if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false } + + var fromIndex, fromLine, fromNode + if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) { + fromLine = lineNo(display.view[0].line) + fromNode = display.view[0].node + } else { + fromLine = lineNo(display.view[fromIndex].line) + fromNode = display.view[fromIndex - 1].node.nextSibling + } + var toIndex = findViewIndex(cm, to.line) + var toLine, toNode + if (toIndex == display.view.length - 1) { + toLine = display.viewTo - 1 + toNode = display.lineDiv.lastChild + } else { + toLine = lineNo(display.view[toIndex + 1].line) - 1 + toNode = display.view[toIndex + 1].node.previousSibling + } + + if (!fromNode) { return false } + var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine)) + var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length)) + while (newText.length > 1 && oldText.length > 1) { + if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine-- } + else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++ } + else { break } + } + + var cutFront = 0, cutEnd = 0 + var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length) + while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront)) + { ++cutFront } + var newBot = lst(newText), oldBot = lst(oldText) + var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0), + oldBot.length - (oldText.length == 1 ? cutFront : 0)) + while (cutEnd < maxCutEnd && + newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) + { ++cutEnd } + + newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "") + newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "") + + var chFrom = Pos(fromLine, cutFront) + var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0) + if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) { + replaceRange(cm.doc, newText, chFrom, chTo, "+input") + return true + } +}; + +ContentEditableInput.prototype.ensurePolled = function () { + this.forceCompositionEnd() +}; +ContentEditableInput.prototype.reset = function () { + this.forceCompositionEnd() +}; +ContentEditableInput.prototype.forceCompositionEnd = function () { + if (!this.composing) { return } + clearTimeout(this.readDOMTimeout) + this.composing = null + if (!this.pollContent()) { regChange(this.cm) } + this.div.blur() + this.div.focus() +}; +ContentEditableInput.prototype.readFromDOMSoon = function () { + var this$1 = this; + + if (this.readDOMTimeout != null) { return } + this.readDOMTimeout = setTimeout(function () { + this$1.readDOMTimeout = null + if (this$1.composing) { + if (this$1.composing.done) { this$1.composing = null } + else { return } + } + if (this$1.cm.isReadOnly() || !this$1.pollContent()) + { runInOp(this$1.cm, function () { return regChange(this$1.cm); }) } + }, 80) +}; + +ContentEditableInput.prototype.setUneditable = function (node) { + node.contentEditable = "false" +}; + +ContentEditableInput.prototype.onKeyPress = function (e) { + e.preventDefault() + if (!this.cm.isReadOnly()) + { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0) } +}; + +ContentEditableInput.prototype.readOnlyChanged = function (val) { + this.div.contentEditable = String(val != "nocursor") +}; + +ContentEditableInput.prototype.onContextMenu = function () {}; +ContentEditableInput.prototype.resetPosition = function () {}; + +ContentEditableInput.prototype.needsContentAttribute = true + +function posToDOM(cm, pos) { + var view = findViewForLine(cm, pos.line) + if (!view || view.hidden) { return null } + var line = getLine(cm.doc, pos.line) + var info = mapFromLineView(view, line, pos.line) + + var order = getOrder(line), side = "left" + if (order) { + var partPos = getBidiPartAt(order, pos.ch) + side = partPos % 2 ? "right" : "left" + } + var result = nodeAndOffsetInLineMap(info.map, pos.ch, side) + result.offset = result.collapse == "right" ? result.end : result.start + return result +} + +function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos } + +function domTextBetween(cm, from, to, fromLine, toLine) { + var text = "", closing = false, lineSep = cm.doc.lineSeparator() + function recognizeMarker(id) { return function (marker) { return marker.id == id; } } + function walk(node) { + if (node.nodeType == 1) { + var cmText = node.getAttribute("cm-text") + if (cmText != null) { + if (cmText == "") { text += node.textContent.replace(/\u200b/g, "") } + else { text += cmText } + return } - } - - textarea.style.display = "none"; - var cm = CodeMirror(function(node) { - textarea.parentNode.insertBefore(node, textarea.nextSibling); - }, options); - cm.save = save; - cm.getTextArea = function() { return textarea; }; - cm.toTextArea = function() { - save(); - textarea.parentNode.removeChild(cm.getWrapperElement()); - textarea.style.display = ""; - if (textarea.form) { - off(textarea.form, "submit", save); - if (typeof textarea.form.submit == "function") - textarea.form.submit = realSubmit; + var markerID = node.getAttribute("cm-marker"), range + if (markerID) { + var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID)) + if (found.length && (range = found[0].find())) + { text += getBetween(cm.doc, range.from, range.to).join(lineSep) } + return } - }; - return cm; - }; - - // STRING STREAM - - // Fed to the mode parsers, provides helper functions to make - // parsers more succinct. - - // The character stream used by a mode's parser. - function StringStream(string, tabSize) { - this.pos = this.start = 0; - this.string = string; - this.tabSize = tabSize || 8; - this.lastColumnPos = this.lastColumnValue = 0; + if (node.getAttribute("contenteditable") == "false") { return } + for (var i = 0; i < node.childNodes.length; i++) + { walk(node.childNodes[i]) } + if (/^(pre|div|p)$/i.test(node.nodeName)) + { closing = true } + } else if (node.nodeType == 3) { + var val = node.nodeValue + if (!val) { return } + if (closing) { + text += lineSep + closing = false + } + text += val + } + } + for (;;) { + walk(from) + if (from == to) { break } + from = from.nextSibling + } + return text +} + +function domToPos(cm, node, offset) { + var lineNode + if (node == cm.display.lineDiv) { + lineNode = cm.display.lineDiv.childNodes[offset] + if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) } + node = null; offset = 0 + } else { + for (lineNode = node;; lineNode = lineNode.parentNode) { + if (!lineNode || lineNode == cm.display.lineDiv) { return null } + if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break } + } + } + for (var i = 0; i < cm.display.view.length; i++) { + var lineView = cm.display.view[i] + if (lineView.node == lineNode) + { return locateNodeInLineView(lineView, node, offset) } + } +} + +function locateNodeInLineView(lineView, node, offset) { + var wrapper = lineView.text.firstChild, bad = false + if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) } + if (node == wrapper) { + bad = true + node = wrapper.childNodes[offset] + offset = 0 + if (!node) { + var line = lineView.rest ? lst(lineView.rest) : lineView.line + return badPos(Pos(lineNo(line), line.text.length), bad) + } + } + + var textNode = node.nodeType == 3 ? node : null, topNode = node + if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) { + textNode = node.firstChild + if (offset) { offset = textNode.nodeValue.length } + } + while (topNode.parentNode != wrapper) { topNode = topNode.parentNode } + var measure = lineView.measure, maps = measure.maps + + function find(textNode, topNode, offset) { + for (var i = -1; i < (maps ? maps.length : 0); i++) { + var map = i < 0 ? measure.map : maps[i] + for (var j = 0; j < map.length; j += 3) { + var curNode = map[j + 2] + if (curNode == textNode || curNode == topNode) { + var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]) + var ch = map[j] + offset + if (offset < 0 || curNode != textNode) { ch = map[j + (offset ? 1 : 0)] } + return Pos(line, ch) + } + } + } } + var found = find(textNode, topNode, offset) + if (found) { return badPos(found, bad) } - StringStream.prototype = { - eol: function() {return this.pos >= this.string.length;}, - sol: function() {return this.pos == 0;}, - peek: function() {return this.string.charAt(this.pos) || undefined;}, - next: function() { - if (this.pos < this.string.length) - return this.string.charAt(this.pos++); - }, - eat: function(match) { - var ch = this.string.charAt(this.pos); - if (typeof match == "string") var ok = ch == match; - else var ok = ch && (match.test ? match.test(ch) : match(ch)); - if (ok) {++this.pos; return ch;} - }, - eatWhile: function(match) { - var start = this.pos; - while (this.eat(match)){} - return this.pos > start; - }, - eatSpace: function() { - var start = this.pos; - while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos; - return this.pos > start; - }, - skipToEnd: function() {this.pos = this.string.length;}, - skipTo: function(ch) { - var found = this.string.indexOf(ch, this.pos); - if (found > -1) {this.pos = found; return true;} - }, - backUp: function(n) {this.pos -= n;}, - column: function() { - if (this.lastColumnPos < this.start) { - this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue); - this.lastColumnPos = this.start; + // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems + for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) { + found = find(after, after.firstChild, 0) + if (found) + { return badPos(Pos(found.line, found.ch - dist), bad) } + else + { dist += after.textContent.length } + } + for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) { + found = find(before, before.firstChild, -1) + if (found) + { return badPos(Pos(found.line, found.ch + dist$1), bad) } + else + { dist$1 += before.textContent.length } + } +} + +// TEXTAREA INPUT STYLE + +var TextareaInput = function(cm) { + this.cm = cm + // See input.poll and input.reset + this.prevInput = "" + + // Flag that indicates whether we expect input to appear real soon + // now (after some event like 'keypress' or 'input') and are + // polling intensively. + this.pollingFast = false + // Self-resetting timeout for the poller + this.polling = new Delayed() + // Tracks when input.reset has punted to just putting a short + // string into the textarea instead of the full selection. + this.inaccurateSelection = false + // Used to work around IE issue with selection being forgotten when focus moves away from textarea + this.hasSelection = false + this.composing = null +}; + +TextareaInput.prototype.init = function (display) { + var this$1 = this; + + var input = this, cm = this.cm + + // Wraps and hides input textarea + var div = this.wrapper = hiddenTextarea() + // The semihidden textarea that is focused when the editor is + // focused, and receives input. + var te = this.textarea = div.firstChild + display.wrapper.insertBefore(div, display.wrapper.firstChild) + + // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore) + if (ios) { te.style.width = "0px" } + + on(te, "input", function () { + if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null } + input.poll() + }) + + on(te, "paste", function (e) { + if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return } + + cm.state.pasteIncoming = true + input.fastPoll() + }) + + function prepareCopyCut(e) { + if (signalDOMEvent(cm, e)) { return } + if (cm.somethingSelected()) { + setLastCopied({lineWise: false, text: cm.getSelections()}) + if (input.inaccurateSelection) { + input.prevInput = "" + input.inaccurateSelection = false + te.value = lastCopied.text.join("\n") + selectInput(te) } - return this.lastColumnValue; - }, - indentation: function() {return countColumn(this.string, null, this.tabSize);}, - match: function(pattern, consume, caseInsensitive) { - if (typeof pattern == "string") { - var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;}; - var substr = this.string.substr(this.pos, pattern.length); - if (cased(substr) == cased(pattern)) { - if (consume !== false) this.pos += pattern.length; - return true; - } + } else if (!cm.options.lineWiseCopyCut) { + return + } else { + var ranges = copyableRanges(cm) + setLastCopied({lineWise: true, text: ranges.text}) + if (e.type == "cut") { + cm.setSelections(ranges.ranges, null, sel_dontScroll) } else { - var match = this.string.slice(this.pos).match(pattern); - if (match && match.index > 0) return null; - if (match && consume !== false) this.pos += match[0].length; - return match; + input.prevInput = "" + te.value = ranges.text.join("\n") + selectInput(te) } - }, - current: function(){return this.string.slice(this.start, this.pos);} - }; - CodeMirror.StringStream = StringStream; - - // TEXTMARKERS - - function TextMarker(doc, type) { - this.lines = []; - this.type = type; - this.doc = doc; - } - CodeMirror.TextMarker = TextMarker; - eventMixin(TextMarker); - - TextMarker.prototype.clear = function() { - if (this.explicitlyCleared) return; - var cm = this.doc.cm, withOp = cm && !cm.curOp; - if (withOp) startOperation(cm); - if (hasHandler(this, "clear")) { - var found = this.find(); - if (found) signalLater(this, "clear", found.from, found.to); - } - var min = null, max = null; - for (var i = 0; i < this.lines.length; ++i) { - var line = this.lines[i]; - var span = getMarkedSpanFor(line.markedSpans, this); - if (span.to != null) max = lineNo(line); - line.markedSpans = removeMarkedSpan(line.markedSpans, span); - if (span.from != null) - min = lineNo(line); - else if (this.collapsed && !lineIsHidden(this.doc, line) && cm) - updateLineHeight(line, textHeight(cm.display)); - } - if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) { - var visual = visualLine(cm.doc, this.lines[i]), len = lineLength(cm.doc, visual); - if (len > cm.display.maxLineLength) { - cm.display.maxLine = visual; - cm.display.maxLineLength = len; - cm.display.maxLineChanged = true; + } + if (e.type == "cut") { cm.state.cutIncoming = true } + } + on(te, "cut", prepareCopyCut) + on(te, "copy", prepareCopyCut) + + on(display.scroller, "paste", function (e) { + if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return } + cm.state.pasteIncoming = true + input.focus() + }) + + // Prevent normal selection in the editor (we handle our own) + on(display.lineSpace, "selectstart", function (e) { + if (!eventInWidget(display, e)) { e_preventDefault(e) } + }) + + on(te, "compositionstart", function () { + var start = cm.getCursor("from") + if (input.composing) { input.composing.range.clear() } + input.composing = { + start: start, + range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"}) + } + }) + on(te, "compositionend", function () { + if (input.composing) { + input.poll() + input.composing.range.clear() + input.composing = null + } + }) +}; + +TextareaInput.prototype.prepareSelection = function () { + // Redraw the selection and/or cursor + var cm = this.cm, display = cm.display, doc = cm.doc + var result = prepareSelection(cm) + + // Move the hidden textarea near the cursor to prevent scrolling artifacts + if (cm.options.moveInputWithCursor) { + var headPos = cursorCoords(cm, doc.sel.primary().head, "div") + var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect() + result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10, + headPos.top + lineOff.top - wrapOff.top)) + result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10, + headPos.left + lineOff.left - wrapOff.left)) + } + + return result +}; + +TextareaInput.prototype.showSelection = function (drawn) { + var cm = this.cm, display = cm.display + removeChildrenAndAdd(display.cursorDiv, drawn.cursors) + removeChildrenAndAdd(display.selectionDiv, drawn.selection) + if (drawn.teTop != null) { + this.wrapper.style.top = drawn.teTop + "px" + this.wrapper.style.left = drawn.teLeft + "px" + } +}; + +// Reset the input to correspond to the selection (or to be empty, +// when not typing and nothing is selected) +TextareaInput.prototype.reset = function (typing) { + if (this.contextMenuPending) { return } + var minimal, selected, cm = this.cm, doc = cm.doc + if (cm.somethingSelected()) { + this.prevInput = "" + var range = doc.sel.primary() + minimal = hasCopyEvent && + (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000) + var content = minimal ? "-" : selected || cm.getSelection() + this.textarea.value = content + if (cm.state.focused) { selectInput(this.textarea) } + if (ie && ie_version >= 9) { this.hasSelection = content } + } else if (!typing) { + this.prevInput = this.textarea.value = "" + if (ie && ie_version >= 9) { this.hasSelection = null } + } + this.inaccurateSelection = minimal +}; + +TextareaInput.prototype.getField = function () { return this.textarea }; + +TextareaInput.prototype.supportsTouch = function () { return false }; + +TextareaInput.prototype.focus = function () { + if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) { + try { this.textarea.focus() } + catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM + } +}; + +TextareaInput.prototype.blur = function () { this.textarea.blur() }; + +TextareaInput.prototype.resetPosition = function () { + this.wrapper.style.top = this.wrapper.style.left = 0 +}; + +TextareaInput.prototype.receivedFocus = function () { this.slowPoll() }; + +// Poll for input changes, using the normal rate of polling. This +// runs as long as the editor is focused. +TextareaInput.prototype.slowPoll = function () { + var this$1 = this; + + if (this.pollingFast) { return } + this.polling.set(this.cm.options.pollInterval, function () { + this$1.poll() + if (this$1.cm.state.focused) { this$1.slowPoll() } + }) +}; + +// When an event has just come in that is likely to add or change +// something in the input textarea, we poll faster, to ensure that +// the change appears on the screen quickly. +TextareaInput.prototype.fastPoll = function () { + var missed = false, input = this + input.pollingFast = true + function p() { + var changed = input.poll() + if (!changed && !missed) {missed = true; input.polling.set(60, p)} + else {input.pollingFast = false; input.slowPoll()} + } + input.polling.set(20, p) +}; + +// Read input from the textarea, and update the document to match. +// When something is selected, it is present in the textarea, and +// selected (unless it is huge, in which case a placeholder is +// used). When nothing is selected, the cursor sits after previously +// seen text (can be empty), which is stored in prevInput (we must +// not reset the textarea when typing, because that breaks IME). +TextareaInput.prototype.poll = function () { + var this$1 = this; + + var cm = this.cm, input = this.textarea, prevInput = this.prevInput + // Since this is called a *lot*, try to bail out as cheaply as + // possible when it is clear that nothing happened. hasSelection + // will be the case when there is a lot of text in the textarea, + // in which case reading its value would be expensive. + if (this.contextMenuPending || !cm.state.focused || + (hasSelection(input) && !prevInput && !this.composing) || + cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq) + { return false } + + var text = input.value + // If nothing changed, bail. + if (text == prevInput && !cm.somethingSelected()) { return false } + // Work around nonsensical selection resetting in IE9/10, and + // inexplicable appearance of private area unicode characters on + // some key combos in Mac (#2689). + if (ie && ie_version >= 9 && this.hasSelection === text || + mac && /[\uf700-\uf7ff]/.test(text)) { + cm.display.input.reset() + return false + } + + if (cm.doc.sel == cm.display.selForContextMenu) { + var first = text.charCodeAt(0) + if (first == 0x200b && !prevInput) { prevInput = "\u200b" } + if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") } + } + // Find the part of the input that is actually new + var same = 0, l = Math.min(prevInput.length, text.length) + while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same } + + runInOp(cm, function () { + applyTextInput(cm, text.slice(same), prevInput.length - same, + null, this$1.composing ? "*compose" : null) + + // Don't leave long text in the textarea, since it makes further polling slow + if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = "" } + else { this$1.prevInput = text } + + if (this$1.composing) { + this$1.composing.range.clear() + this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"), + {className: "CodeMirror-composing"}) + } + }) + return true +}; + +TextareaInput.prototype.ensurePolled = function () { + if (this.pollingFast && this.poll()) { this.pollingFast = false } +}; + +TextareaInput.prototype.onKeyPress = function () { + if (ie && ie_version >= 9) { this.hasSelection = null } + this.fastPoll() +}; + +TextareaInput.prototype.onContextMenu = function (e) { + var input = this, cm = input.cm, display = cm.display, te = input.textarea + var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop + if (!pos || presto) { return } // Opera is difficult. + + // Reset the current text selection only if the click is done outside of the selection + // and 'resetSelectionOnContextMenu' option is true. + var reset = cm.options.resetSelectionOnContextMenu + if (reset && cm.doc.sel.contains(pos) == -1) + { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll) } + + var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText + input.wrapper.style.cssText = "position: absolute" + var wrapperBox = input.wrapper.getBoundingClientRect() + te.style.cssText = "position: absolute; width: 30px; height: 30px;\n top: " + (e.clientY - wrapperBox.top - 5) + "px; left: " + (e.clientX - wrapperBox.left - 5) + "px;\n z-index: 1000; background: " + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + ";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);" + var oldScrollY + if (webkit) { oldScrollY = window.scrollY } // Work around Chrome issue (#2712) + display.input.focus() + if (webkit) { window.scrollTo(null, oldScrollY) } + display.input.reset() + // Adds "Select all" to context menu in FF + if (!cm.somethingSelected()) { te.value = input.prevInput = " " } + input.contextMenuPending = true + display.selForContextMenu = cm.doc.sel + clearTimeout(display.detectingSelectAll) + + // Select-all will be greyed out if there's nothing to select, so + // this adds a zero-width space so that we can later check whether + // it got selected. + function prepareSelectAllHack() { + if (te.selectionStart != null) { + var selected = cm.somethingSelected() + var extval = "\u200b" + (selected ? te.value : "") + te.value = "\u21da"; // Used to catch context-menu undo + te.value = extval + input.prevInput = selected ? "" : "\u200b" + te.selectionStart = 1; te.selectionEnd = extval.length + // Re-set this, in case some other handler touched the + // selection in the meantime. + display.selForContextMenu = cm.doc.sel + } + } + function rehide() { + input.contextMenuPending = false + input.wrapper.style.cssText = oldWrapperCSS + te.style.cssText = oldCSS + if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos) } + + // Try to detect the user choosing select-all + if (te.selectionStart != null) { + if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack() } + var i = 0, poll = function () { + if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 && + te.selectionEnd > 0 && input.prevInput == "\u200b") + { operation(cm, selectAll)(cm) } + else if (i++ < 10) { display.detectingSelectAll = setTimeout(poll, 500) } + else { display.input.reset() } } + display.detectingSelectAll = setTimeout(poll, 200) } + } - if (min != null && cm) regChange(cm, min, max + 1); - this.lines.length = 0; - this.explicitlyCleared = true; - if (this.atomic && this.doc.cantEdit) { - this.doc.cantEdit = false; - if (cm) reCheckSelection(cm); + if (ie && ie_version >= 9) { prepareSelectAllHack() } + if (captureRightClick) { + e_stop(e) + var mouseup = function () { + off(window, "mouseup", mouseup) + setTimeout(rehide, 20) } - if (withOp) endOperation(cm); - }; + on(window, "mouseup", mouseup) + } else { + setTimeout(rehide, 50) + } +}; - TextMarker.prototype.find = function() { - var from, to; - for (var i = 0; i < this.lines.length; ++i) { - var line = this.lines[i]; - var span = getMarkedSpanFor(line.markedSpans, this); - if (span.from != null || span.to != null) { - var found = lineNo(line); - if (span.from != null) from = Pos(found, span.from); - if (span.to != null) to = Pos(found, span.to); - } - } - if (this.type == "bookmark") return from; - return from && {from: from, to: to}; - }; +TextareaInput.prototype.readOnlyChanged = function (val) { + if (!val) { this.reset() } +}; - TextMarker.prototype.changed = function() { - var pos = this.find(), cm = this.doc.cm; - if (!pos || !cm) return; - if (this.type != "bookmark") pos = pos.from; - var line = getLine(this.doc, pos.line); - clearCachedMeasurement(cm, line); - if (pos.line >= cm.display.showingFrom && pos.line < cm.display.showingTo) { - for (var node = cm.display.lineDiv.firstChild; node; node = node.nextSibling) if (node.lineObj == line) { - if (node.offsetHeight != line.height) updateLineHeight(line, node.offsetHeight); - break; - } - runInOp(cm, function() { - cm.curOp.selectionChanged = cm.curOp.forceUpdate = cm.curOp.updateMaxLine = true; - }); - } - }; +TextareaInput.prototype.setUneditable = function () {}; - TextMarker.prototype.attachLine = function(line) { - if (!this.lines.length && this.doc.cm) { - var op = this.doc.cm.curOp; - if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) - (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); - } - this.lines.push(line); - }; - TextMarker.prototype.detachLine = function(line) { - this.lines.splice(indexOf(this.lines, line), 1); - if (!this.lines.length && this.doc.cm) { - var op = this.doc.cm.curOp; - (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this); - } - }; +TextareaInput.prototype.needsContentAttribute = false - function markText(doc, from, to, options, type) { - if (options && options.shared) return markTextShared(doc, from, to, options, type); - if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type); - - var marker = new TextMarker(doc, type); - if (posLess(to, from) || posEq(from, to) && type == "range" && - !(options.inclusiveLeft && options.inclusiveRight)) - return marker; - if (options) copyObj(options, marker); - if (marker.replacedWith) { - marker.collapsed = true; - marker.replacedWith = elt("span", [marker.replacedWith], "CodeMirror-widget"); - if (!options.handleMouseEvents) marker.replacedWith.ignoreEvents = true; - } - if (marker.collapsed) sawCollapsedSpans = true; - - if (marker.addToHistory) - addToHistory(doc, {from: from, to: to, origin: "markText"}, - {head: doc.sel.head, anchor: doc.sel.anchor}, NaN); - - var curLine = from.line, size = 0, collapsedAtStart, collapsedAtEnd, cm = doc.cm, updateMaxLine; - doc.iter(curLine, to.line + 1, function(line) { - if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(doc, line) == cm.display.maxLine) - updateMaxLine = true; - var span = {from: null, to: null, marker: marker}; - size += line.text.length; - if (curLine == from.line) {span.from = from.ch; size -= from.ch;} - if (curLine == to.line) {span.to = to.ch; size -= line.text.length - to.ch;} - if (marker.collapsed) { - if (curLine == to.line) collapsedAtEnd = collapsedSpanAt(line, to.ch); - if (curLine == from.line) collapsedAtStart = collapsedSpanAt(line, from.ch); - else updateLineHeight(line, 0); - } - addMarkedSpan(line, span); - ++curLine; - }); - if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) { - if (lineIsHidden(doc, line)) updateLineHeight(line, 0); - }); - - if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); }); - - if (marker.readOnly) { - sawReadOnlySpans = true; - if (doc.history.done.length || doc.history.undone.length) - doc.clearHistory(); - } - if (marker.collapsed) { - if (collapsedAtStart != collapsedAtEnd) - throw new Error("Inserting collapsed marker overlapping an existing one"); - marker.size = size; - marker.atomic = true; - } - if (cm) { - if (updateMaxLine) cm.curOp.updateMaxLine = true; - if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.collapsed) - regChange(cm, from.line, to.line + 1); - if (marker.atomic) reCheckSelection(cm); - } - return marker; - } - - // SHARED TEXTMARKERS - - function SharedTextMarker(markers, primary) { - this.markers = markers; - this.primary = primary; - for (var i = 0, me = this; i < markers.length; ++i) { - markers[i].parent = this; - on(markers[i], "clear", function(){me.clear();}); - } - } - CodeMirror.SharedTextMarker = SharedTextMarker; - eventMixin(SharedTextMarker); - - SharedTextMarker.prototype.clear = function() { - if (this.explicitlyCleared) return; - this.explicitlyCleared = true; - for (var i = 0; i < this.markers.length; ++i) - this.markers[i].clear(); - signalLater(this, "clear"); - }; - SharedTextMarker.prototype.find = function() { - return this.primary.find(); - }; +function fromTextArea(textarea, options) { + options = options ? copyObj(options) : {} + options.value = textarea.value + if (!options.tabindex && textarea.tabIndex) + { options.tabindex = textarea.tabIndex } + if (!options.placeholder && textarea.placeholder) + { options.placeholder = textarea.placeholder } + // Set autofocus to true if this textarea is focused, or if it has + // autofocus and no other element is focused. + if (options.autofocus == null) { + var hasFocus = activeElt() + options.autofocus = hasFocus == textarea || + textarea.getAttribute("autofocus") != null && hasFocus == document.body + } - function markTextShared(doc, from, to, options, type) { - options = copyObj(options); - options.shared = false; - var markers = [markText(doc, from, to, options, type)], primary = markers[0]; - var widget = options.replacedWith; - linkedDocs(doc, function(doc) { - if (widget) options.replacedWith = widget.cloneNode(true); - markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type)); - for (var i = 0; i < doc.linked.length; ++i) - if (doc.linked[i].isParent) return; - primary = lst(markers); - }); - return new SharedTextMarker(markers, primary); - } - - // TEXTMARKER SPANS - - function getMarkedSpanFor(spans, marker) { - if (spans) for (var i = 0; i < spans.length; ++i) { - var span = spans[i]; - if (span.marker == marker) return span; - } - } - function removeMarkedSpan(spans, span) { - for (var r, i = 0; i < spans.length; ++i) - if (spans[i] != span) (r || (r = [])).push(spans[i]); - return r; - } - function addMarkedSpan(line, span) { - line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]; - span.marker.attachLine(line); - } - - function markedSpansBefore(old, startCh, isInsert) { - if (old) for (var i = 0, nw; i < old.length; ++i) { - var span = old[i], marker = span.marker; - var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh); - if (startsBefore || - (marker.inclusiveLeft && marker.inclusiveRight || marker.type == "bookmark") && - span.from == startCh && (!isInsert || !span.marker.insertLeft)) { - var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh); - (nw || (nw = [])).push({from: span.from, - to: endsAfter ? null : span.to, - marker: marker}); - } + function save() {textarea.value = cm.getValue()} + + var realSubmit + if (textarea.form) { + on(textarea.form, "submit", save) + // Deplorable hack to make the submit method do the right thing. + if (!options.leaveSubmitMethodAlone) { + var form = textarea.form + realSubmit = form.submit + try { + var wrappedSubmit = form.submit = function () { + save() + form.submit = realSubmit + form.submit() + form.submit = wrappedSubmit + } + } catch(e) {} } - return nw; } - function markedSpansAfter(old, endCh, isInsert) { - if (old) for (var i = 0, nw; i < old.length; ++i) { - var span = old[i], marker = span.marker; - var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh); - if (endsAfter || marker.type == "bookmark" && span.from == endCh && (!isInsert || span.marker.insertLeft)) { - var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh); - (nw || (nw = [])).push({from: startsBefore ? null : span.from - endCh, - to: span.to == null ? null : span.to - endCh, - marker: marker}); - } - } - return nw; - } - - function stretchSpansOverChange(doc, change) { - var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans; - var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans; - if (!oldFirst && !oldLast) return null; - - var startCh = change.from.ch, endCh = change.to.ch, isInsert = posEq(change.from, change.to); - // Get the spans that 'stick out' on both sides - var first = markedSpansBefore(oldFirst, startCh, isInsert); - var last = markedSpansAfter(oldLast, endCh, isInsert); - - // Next, merge those two ends - var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0); - if (first) { - // Fix up .to properties of first - for (var i = 0; i < first.length; ++i) { - var span = first[i]; - if (span.to == null) { - var found = getMarkedSpanFor(last, span.marker); - if (!found) span.to = startCh; - else if (sameLine) span.to = found.to == null ? null : found.to + offset; - } + options.finishInit = function (cm) { + cm.save = save + cm.getTextArea = function () { return textarea; } + cm.toTextArea = function () { + cm.toTextArea = isNaN // Prevent this from being ran twice + save() + textarea.parentNode.removeChild(cm.getWrapperElement()) + textarea.style.display = "" + if (textarea.form) { + off(textarea.form, "submit", save) + if (typeof textarea.form.submit == "function") + { textarea.form.submit = realSubmit } } } - if (last) { - // Fix up .from in last (or move them into first in case of sameLine) - for (var i = 0; i < last.length; ++i) { - var span = last[i]; - if (span.to != null) span.to += offset; - if (span.from == null) { - var found = getMarkedSpanFor(first, span.marker); - if (!found) { - span.from = offset; - if (sameLine) (first || (first = [])).push(span); - } - } else { - span.from += offset; - if (sameLine) (first || (first = [])).push(span); - } - } - } - if (sameLine && first) { - // Make sure we didn't create any zero-length spans - for (var i = 0; i < first.length; ++i) - if (first[i].from != null && first[i].from == first[i].to && first[i].marker.type != "bookmark") - first.splice(i--, 1); - if (!first.length) first = null; - } - - var newMarkers = [first]; - if (!sameLine) { - // Fill gap with whole-line-spans - var gap = change.text.length - 2, gapMarkers; - if (gap > 0 && first) - for (var i = 0; i < first.length; ++i) - if (first[i].to == null) - (gapMarkers || (gapMarkers = [])).push({from: null, to: null, marker: first[i].marker}); - for (var i = 0; i < gap; ++i) - newMarkers.push(gapMarkers); - newMarkers.push(last); - } - return newMarkers; - } - - function mergeOldSpans(doc, change) { - var old = getOldSpans(doc, change); - var stretched = stretchSpansOverChange(doc, change); - if (!old) return stretched; - if (!stretched) return old; - - for (var i = 0; i < old.length; ++i) { - var oldCur = old[i], stretchCur = stretched[i]; - if (oldCur && stretchCur) { - spans: for (var j = 0; j < stretchCur.length; ++j) { - var span = stretchCur[j]; - for (var k = 0; k < oldCur.length; ++k) - if (oldCur[k].marker == span.marker) continue spans; - oldCur.push(span); - } - } else if (stretchCur) { - old[i] = stretchCur; - } - } - return old; - } - - function removeReadOnlyRanges(doc, from, to) { - var markers = null; - doc.iter(from.line, to.line + 1, function(line) { - if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) { - var mark = line.markedSpans[i].marker; - if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) - (markers || (markers = [])).push(mark); - } - }); - if (!markers) return null; - var parts = [{from: from, to: to}]; - for (var i = 0; i < markers.length; ++i) { - var mk = markers[i], m = mk.find(); - for (var j = 0; j < parts.length; ++j) { - var p = parts[j]; - if (posLess(p.to, m.from) || posLess(m.to, p.from)) continue; - var newParts = [j, 1]; - if (posLess(p.from, m.from) || !mk.inclusiveLeft && posEq(p.from, m.from)) - newParts.push({from: p.from, to: m.from}); - if (posLess(m.to, p.to) || !mk.inclusiveRight && posEq(p.to, m.to)) - newParts.push({from: m.to, to: p.to}); - parts.splice.apply(parts, newParts); - j += newParts.length - 1; - } - } - return parts; - } - - function collapsedSpanAt(line, ch) { - var sps = sawCollapsedSpans && line.markedSpans, found; - if (sps) for (var sp, i = 0; i < sps.length; ++i) { - sp = sps[i]; - if (!sp.marker.collapsed) continue; - if ((sp.from == null || sp.from < ch) && - (sp.to == null || sp.to > ch) && - (!found || found.width < sp.marker.width)) - found = sp.marker; - } - return found; - } - function collapsedSpanAtStart(line) { return collapsedSpanAt(line, -1); } - function collapsedSpanAtEnd(line) { return collapsedSpanAt(line, line.text.length + 1); } - - function visualLine(doc, line) { - var merged; - while (merged = collapsedSpanAtStart(line)) - line = getLine(doc, merged.find().from.line); - return line; - } - - function lineIsHidden(doc, line) { - var sps = sawCollapsedSpans && line.markedSpans; - if (sps) for (var sp, i = 0; i < sps.length; ++i) { - sp = sps[i]; - if (!sp.marker.collapsed) continue; - if (sp.from == null) return true; - if (sp.marker.replacedWith) continue; - if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) - return true; - } - } - function lineIsHiddenInner(doc, line, span) { - if (span.to == null) { - var end = span.marker.find().to, endLine = getLine(doc, end.line); - return lineIsHiddenInner(doc, endLine, getMarkedSpanFor(endLine.markedSpans, span.marker)); - } - if (span.marker.inclusiveRight && span.to == line.text.length) - return true; - for (var sp, i = 0; i < line.markedSpans.length; ++i) { - sp = line.markedSpans[i]; - if (sp.marker.collapsed && !sp.marker.replacedWith && sp.from == span.to && - (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && - lineIsHiddenInner(doc, line, sp)) return true; - } - } - - function detachMarkedSpans(line) { - var spans = line.markedSpans; - if (!spans) return; - for (var i = 0; i < spans.length; ++i) - spans[i].marker.detachLine(line); - line.markedSpans = null; - } - - function attachMarkedSpans(line, spans) { - if (!spans) return; - for (var i = 0; i < spans.length; ++i) - spans[i].marker.attachLine(line); - line.markedSpans = spans; - } - - // LINE WIDGETS - - var LineWidget = CodeMirror.LineWidget = function(cm, node, options) { - if (options) for (var opt in options) if (options.hasOwnProperty(opt)) - this[opt] = options[opt]; - this.cm = cm; - this.node = node; - }; - eventMixin(LineWidget); - function widgetOperation(f) { - return function() { - var withOp = !this.cm.curOp; - if (withOp) startOperation(this.cm); - try {var result = f.apply(this, arguments);} - finally {if (withOp) endOperation(this.cm);} - return result; - }; - } - LineWidget.prototype.clear = widgetOperation(function() { - var ws = this.line.widgets, no = lineNo(this.line); - if (no == null || !ws) return; - for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1); - if (!ws.length) this.line.widgets = null; - var aboveVisible = heightAtLine(this.cm, this.line) < this.cm.doc.scrollTop; - updateLineHeight(this.line, Math.max(0, this.line.height - widgetHeight(this))); - if (aboveVisible) addToScrollPos(this.cm, 0, -this.height); - regChange(this.cm, no, no + 1); - }); - LineWidget.prototype.changed = widgetOperation(function() { - var oldH = this.height; - this.height = null; - var diff = widgetHeight(this) - oldH; - if (!diff) return; - updateLineHeight(this.line, this.line.height + diff); - var no = lineNo(this.line); - regChange(this.cm, no, no + 1); - }); - - function widgetHeight(widget) { - if (widget.height != null) return widget.height; - if (!widget.node.parentNode || widget.node.parentNode.nodeType != 1) - removeChildrenAndAdd(widget.cm.display.measure, elt("div", [widget.node], null, "position: relative")); - return widget.height = widget.node.offsetHeight; - } - - function addLineWidget(cm, handle, node, options) { - var widget = new LineWidget(cm, node, options); - if (widget.noHScroll) cm.display.alignWidgets = true; - changeLine(cm, handle, function(line) { - var widgets = line.widgets || (line.widgets = []); - if (widget.insertAt == null) widgets.push(widget); - else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); - widget.line = line; - if (!lineIsHidden(cm.doc, line) || widget.showIfHidden) { - var aboveVisible = heightAtLine(cm, line) < cm.doc.scrollTop; - updateLineHeight(line, line.height + widgetHeight(widget)); - if (aboveVisible) addToScrollPos(cm, 0, widget.height); - } - return true; - }); - return widget; - } - - // LINE DATA STRUCTURE - - // Line objects. These hold state related to a line, including - // highlighting info (the styles array). - var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) { - this.text = text; - attachMarkedSpans(this, markedSpans); - this.height = estimateHeight ? estimateHeight(this) : 1; - }; - eventMixin(Line); - Line.prototype.lineNo = function() { return lineNo(this); }; - - function updateLine(line, text, markedSpans, estimateHeight) { - line.text = text; - if (line.stateAfter) line.stateAfter = null; - if (line.styles) line.styles = null; - if (line.order != null) line.order = null; - detachMarkedSpans(line); - attachMarkedSpans(line, markedSpans); - var estHeight = estimateHeight ? estimateHeight(line) : 1; - if (estHeight != line.height) updateLineHeight(line, estHeight); - } - - function cleanUpLine(line) { - line.parent = null; - detachMarkedSpans(line); - } - - // Run the given mode's parser over a line, update the styles - // array, which contains alternating fragments of text and CSS - // classes. - function runMode(cm, text, mode, state, f, forceToEnd) { - var flattenSpans = mode.flattenSpans; - if (flattenSpans == null) flattenSpans = cm.options.flattenSpans; - var curStart = 0, curStyle = null; - var stream = new StringStream(text, cm.options.tabSize), style; - if (text == "" && mode.blankLine) mode.blankLine(state); - while (!stream.eol()) { - if (stream.pos > cm.options.maxHighlightLength) { - flattenSpans = false; - if (forceToEnd) processLine(cm, text, state, stream.pos); - stream.pos = text.length; - style = null; - } else { - style = mode.token(stream, state); - } - if (!flattenSpans || curStyle != style) { - if (curStart < stream.start) f(stream.start, curStyle); - curStart = stream.start; curStyle = style; - } - stream.start = stream.pos; - } - while (curStart < stream.pos) { - // Webkit seems to refuse to render text nodes longer than 57444 characters - var pos = Math.min(stream.pos, curStart + 50000); - f(pos, curStyle); - curStart = pos; - } - } - - function highlightLine(cm, line, state, forceToEnd) { - // A styles array always starts with a number identifying the - // mode/overlays that it is based on (for easy invalidation). - var st = [cm.state.modeGen]; - // Compute the base array of styles - runMode(cm, line.text, cm.doc.mode, state, function(end, style) { - st.push(end, style); - }, forceToEnd); - - // Run overlays, adjust style array. - for (var o = 0; o < cm.state.overlays.length; ++o) { - var overlay = cm.state.overlays[o], i = 1, at = 0; - runMode(cm, line.text, overlay.mode, true, function(end, style) { - var start = i; - // Ensure there's a token end at the current position, and that i points at it - while (at < end) { - var i_end = st[i]; - if (i_end > end) - st.splice(i, 1, end, st[i+1], i_end); - i += 2; - at = Math.min(end, i_end); - } - if (!style) return; - if (overlay.opaque) { - st.splice(start, i - start, end, style); - i = start + 2; - } else { - for (; start < i; start += 2) { - var cur = st[start+1]; - st[start+1] = cur ? cur + " " + style : style; - } - } - }); - } - - return st; - } - - function getLineStyles(cm, line) { - if (!line.styles || line.styles[0] != cm.state.modeGen) - line.styles = highlightLine(cm, line, line.stateAfter = getStateBefore(cm, lineNo(line))); - return line.styles; - } - - // Lightweight form of highlight -- proceed over this line and - // update state, but don't save a style array. - function processLine(cm, text, state, startAt) { - var mode = cm.doc.mode; - var stream = new StringStream(text, cm.options.tabSize); - stream.start = stream.pos = startAt || 0; - if (text == "" && mode.blankLine) mode.blankLine(state); - while (!stream.eol() && stream.pos <= cm.options.maxHighlightLength) { - mode.token(stream, state); - stream.start = stream.pos; - } - } - - var styleToClassCache = {}; - function interpretTokenStyle(style, builder) { - if (!style) return null; - for (;;) { - var lineClass = style.match(/(?:^|\s)line-(background-)?(\S+)/); - if (!lineClass) break; - style = style.slice(0, lineClass.index) + style.slice(lineClass.index + lineClass[0].length); - var prop = lineClass[1] ? "bgClass" : "textClass"; - if (builder[prop] == null) - builder[prop] = lineClass[2]; - else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(builder[prop])) - builder[prop] += " " + lineClass[2]; - } - return styleToClassCache[style] || - (styleToClassCache[style] = "cm-" + style.replace(/ +/g, " cm-")); - } - - function buildLineContent(cm, realLine, measure, copyWidgets) { - var merged, line = realLine, empty = true; - while (merged = collapsedSpanAtStart(line)) - line = getLine(cm.doc, merged.find().from.line); - - var builder = {pre: elt("pre"), col: 0, pos: 0, - measure: null, measuredSomething: false, cm: cm, - copyWidgets: copyWidgets}; - - do { - if (line.text) empty = false; - builder.measure = line == realLine && measure; - builder.pos = 0; - builder.addToken = builder.measure ? buildTokenMeasure : buildToken; - if ((ie || webkit) && cm.getOption("lineWrapping")) - builder.addToken = buildTokenSplitSpaces(builder.addToken); - var next = insertLineContent(line, builder, getLineStyles(cm, line)); - if (measure && line == realLine && !builder.measuredSomething) { - measure[0] = builder.pre.appendChild(zeroWidthElement(cm.display.measure)); - builder.measuredSomething = true; - } - if (next) line = getLine(cm.doc, next.to.line); - } while (next); - - if (measure && !builder.measuredSomething && !measure[0]) - measure[0] = builder.pre.appendChild(empty ? elt("span", "\u00a0") : zeroWidthElement(cm.display.measure)); - if (!builder.pre.firstChild && !lineIsHidden(cm.doc, realLine)) - builder.pre.appendChild(document.createTextNode("\u00a0")); - - var order; - // Work around problem with the reported dimensions of single-char - // direction spans on IE (issue #1129). See also the comment in - // cursorCoords. - if (measure && (ie || ie_gt10) && (order = getOrder(line))) { - var l = order.length - 1; - if (order[l].from == order[l].to) --l; - var last = order[l], prev = order[l - 1]; - if (last.from + 1 == last.to && prev && last.level < prev.level) { - var span = measure[builder.pos - 1]; - if (span) span.parentNode.insertBefore(span.measureRight = zeroWidthElement(cm.display.measure), - span.nextSibling); - } - } - - var textClass = builder.textClass ? builder.textClass + " " + (realLine.textClass || "") : realLine.textClass; - if (textClass) builder.pre.className = textClass; - - signal(cm, "renderLine", cm, realLine, builder.pre); - return builder; - } - - function defaultSpecialCharPlaceholder(ch) { - var token = elt("span", "\u2022", "cm-invalidchar"); - token.title = "\\u" + ch.charCodeAt(0).toString(16); - return token; - } - - function buildToken(builder, text, style, startStyle, endStyle, title) { - if (!text) return; - var special = builder.cm.options.specialChars; - if (!special.test(text)) { - builder.col += text.length; - var content = document.createTextNode(text); - } else { - var content = document.createDocumentFragment(), pos = 0; - while (true) { - special.lastIndex = pos; - var m = special.exec(text); - var skipped = m ? m.index - pos : text.length - pos; - if (skipped) { - content.appendChild(document.createTextNode(text.slice(pos, pos + skipped))); - builder.col += skipped; - } - if (!m) break; - pos += skipped + 1; - if (m[0] == "\t") { - var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize; - content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); - builder.col += tabWidth; - } else { - var token = builder.cm.options.specialCharPlaceholder(m[0]); - content.appendChild(token); - builder.col += 1; - } - } - } - if (style || startStyle || endStyle || builder.measure) { - var fullStyle = style || ""; - if (startStyle) fullStyle += startStyle; - if (endStyle) fullStyle += endStyle; - var token = elt("span", [content], fullStyle); - if (title) token.title = title; - return builder.pre.appendChild(token); - } - builder.pre.appendChild(content); - } - - function buildTokenMeasure(builder, text, style, startStyle, endStyle) { - var wrapping = builder.cm.options.lineWrapping; - for (var i = 0; i < text.length; ++i) { - var ch = text.charAt(i), start = i == 0; - if (ch >= "\ud800" && ch < "\udbff" && i < text.length - 1) { - ch = text.slice(i, i + 2); - ++i; - } else if (i && wrapping && spanAffectsWrapping(text, i)) { - builder.pre.appendChild(elt("wbr")); - } - var old = builder.measure[builder.pos]; - var span = builder.measure[builder.pos] = - buildToken(builder, ch, style, - start && startStyle, i == text.length - 1 && endStyle); - if (old) span.leftSide = old.leftSide || old; - // In IE single-space nodes wrap differently than spaces - // embedded in larger text nodes, except when set to - // white-space: normal (issue #1268). - if (ie && wrapping && ch == " " && i && !/\s/.test(text.charAt(i - 1)) && - i < text.length - 1 && !/\s/.test(text.charAt(i + 1))) - span.style.whiteSpace = "normal"; - builder.pos += ch.length; - } - if (text.length) builder.measuredSomething = true; - } - - function buildTokenSplitSpaces(inner) { - function split(old) { - var out = " "; - for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0"; - out += " "; - return out; - } - return function(builder, text, style, startStyle, endStyle, title) { - return inner(builder, text.replace(/ {3,}/g, split), style, startStyle, endStyle, title); - }; - } - - function buildCollapsedSpan(builder, size, marker, ignoreWidget) { - var widget = !ignoreWidget && marker.replacedWith; - if (widget) { - if (builder.copyWidgets) widget = widget.cloneNode(true); - builder.pre.appendChild(widget); - if (builder.measure) { - if (size) { - builder.measure[builder.pos] = widget; - } else { - var elt = zeroWidthElement(builder.cm.display.measure); - if (marker.type == "bookmark" && !marker.insertLeft) - builder.measure[builder.pos] = builder.pre.appendChild(elt); - else if (builder.measure[builder.pos]) - return; - else - builder.measure[builder.pos] = builder.pre.insertBefore(elt, widget); - } - builder.measuredSomething = true; - } - } - builder.pos += size; - } - - // Outputs a number of spans to make up a line, taking highlighting - // and marked text into account. - function insertLineContent(line, builder, styles) { - var spans = line.markedSpans, allText = line.text, at = 0; - if (!spans) { - for (var i = 1; i < styles.length; i+=2) - builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder)); - return; - } - - var len = allText.length, pos = 0, i = 1, text = "", style; - var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed; - for (;;) { - if (nextChange == pos) { // Update current marker set - spanStyle = spanEndStyle = spanStartStyle = title = ""; - collapsed = null; nextChange = Infinity; - var foundBookmarks = []; - for (var j = 0; j < spans.length; ++j) { - var sp = spans[j], m = sp.marker; - if (sp.from <= pos && (sp.to == null || sp.to > pos)) { - if (sp.to != null && nextChange > sp.to) { nextChange = sp.to; spanEndStyle = ""; } - if (m.className) spanStyle += " " + m.className; - if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle; - if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle; - if (m.title && !title) title = m.title; - if (m.collapsed && (!collapsed || collapsed.marker.size < m.size)) - collapsed = sp; - } else if (sp.from > pos && nextChange > sp.from) { - nextChange = sp.from; - } - if (m.type == "bookmark" && sp.from == pos && m.replacedWith) foundBookmarks.push(m); - } - if (collapsed && (collapsed.from || 0) == pos) { - buildCollapsedSpan(builder, (collapsed.to == null ? len : collapsed.to) - pos, - collapsed.marker, collapsed.from == null); - if (collapsed.to == null) return collapsed.marker.find(); - } - if (!collapsed && foundBookmarks.length) for (var j = 0; j < foundBookmarks.length; ++j) - buildCollapsedSpan(builder, 0, foundBookmarks[j]); - } - if (pos >= len) break; - - var upto = Math.min(len, nextChange); - while (true) { - if (text) { - var end = pos + text.length; - if (!collapsed) { - var tokenText = end > upto ? text.slice(0, upto - pos) : text; - builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, - spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title); - } - if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;} - pos = end; - spanStartStyle = ""; - } - text = allText.slice(at, at = styles[i++]); - style = interpretTokenStyle(styles[i++], builder); - } - } - } - - // DOCUMENT DATA STRUCTURE - - function updateDoc(doc, change, markedSpans, selAfter, estimateHeight) { - function spansFor(n) {return markedSpans ? markedSpans[n] : null;} - function update(line, text, spans) { - updateLine(line, text, spans, estimateHeight); - signalLater(line, "change", line, change); - } - - var from = change.from, to = change.to, text = change.text; - var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line); - var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line; - - // First adjust the line structure - if (from.ch == 0 && to.ch == 0 && lastText == "" && - (!doc.cm || doc.cm.options.wholeLineUpdateBefore)) { - // This is a whole-line replace. Treated specially to make - // sure line objects move the way they are supposed to. - for (var i = 0, e = text.length - 1, added = []; i < e; ++i) - added.push(new Line(text[i], spansFor(i), estimateHeight)); - update(lastLine, lastLine.text, lastSpans); - if (nlines) doc.remove(from.line, nlines); - if (added.length) doc.insert(from.line, added); - } else if (firstLine == lastLine) { - if (text.length == 1) { - update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans); - } else { - for (var added = [], i = 1, e = text.length - 1; i < e; ++i) - added.push(new Line(text[i], spansFor(i), estimateHeight)); - added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight)); - update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); - doc.insert(from.line + 1, added); - } - } else if (text.length == 1) { - update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0)); - doc.remove(from.line + 1, nlines); - } else { - update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); - update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans); - for (var i = 1, e = text.length - 1, added = []; i < e; ++i) - added.push(new Line(text[i], spansFor(i), estimateHeight)); - if (nlines > 1) doc.remove(from.line + 1, nlines - 1); - doc.insert(from.line + 1, added); - } - - signalLater(doc, "change", doc, change); - setSelection(doc, selAfter.anchor, selAfter.head, null, true); - } - - function LeafChunk(lines) { - this.lines = lines; - this.parent = null; - for (var i = 0, e = lines.length, height = 0; i < e; ++i) { - lines[i].parent = this; - height += lines[i].height; - } - this.height = height; - } - - LeafChunk.prototype = { - chunkSize: function() { return this.lines.length; }, - removeInner: function(at, n) { - for (var i = at, e = at + n; i < e; ++i) { - var line = this.lines[i]; - this.height -= line.height; - cleanUpLine(line); - signalLater(line, "delete"); - } - this.lines.splice(at, n); - }, - collapse: function(lines) { - lines.splice.apply(lines, [lines.length, 0].concat(this.lines)); - }, - insertInner: function(at, lines, height) { - this.height += height; - this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)); - for (var i = 0, e = lines.length; i < e; ++i) lines[i].parent = this; - }, - iterN: function(at, n, op) { - for (var e = at + n; at < e; ++at) - if (op(this.lines[at])) return true; - } - }; - - function BranchChunk(children) { - this.children = children; - var size = 0, height = 0; - for (var i = 0, e = children.length; i < e; ++i) { - var ch = children[i]; - size += ch.chunkSize(); height += ch.height; - ch.parent = this; - } - this.size = size; - this.height = height; - this.parent = null; - } - - BranchChunk.prototype = { - chunkSize: function() { return this.size; }, - removeInner: function(at, n) { - this.size -= n; - for (var i = 0; i < this.children.length; ++i) { - var child = this.children[i], sz = child.chunkSize(); - if (at < sz) { - var rm = Math.min(n, sz - at), oldHeight = child.height; - child.removeInner(at, rm); - this.height -= oldHeight - child.height; - if (sz == rm) { this.children.splice(i--, 1); child.parent = null; } - if ((n -= rm) == 0) break; - at = 0; - } else at -= sz; - } - if (this.size - n < 25) { - var lines = []; - this.collapse(lines); - this.children = [new LeafChunk(lines)]; - this.children[0].parent = this; - } - }, - collapse: function(lines) { - for (var i = 0, e = this.children.length; i < e; ++i) this.children[i].collapse(lines); - }, - insertInner: function(at, lines, height) { - this.size += lines.length; - this.height += height; - for (var i = 0, e = this.children.length; i < e; ++i) { - var child = this.children[i], sz = child.chunkSize(); - if (at <= sz) { - child.insertInner(at, lines, height); - if (child.lines && child.lines.length > 50) { - while (child.lines.length > 50) { - var spilled = child.lines.splice(child.lines.length - 25, 25); - var newleaf = new LeafChunk(spilled); - child.height -= newleaf.height; - this.children.splice(i + 1, 0, newleaf); - newleaf.parent = this; - } - this.maybeSpill(); - } - break; - } - at -= sz; - } - }, - maybeSpill: function() { - if (this.children.length <= 10) return; - var me = this; - do { - var spilled = me.children.splice(me.children.length - 5, 5); - var sibling = new BranchChunk(spilled); - if (!me.parent) { // Become the parent node - var copy = new BranchChunk(me.children); - copy.parent = me; - me.children = [copy, sibling]; - me = copy; - } else { - me.size -= sibling.size; - me.height -= sibling.height; - var myIndex = indexOf(me.parent.children, me); - me.parent.children.splice(myIndex + 1, 0, sibling); - } - sibling.parent = me.parent; - } while (me.children.length > 10); - me.parent.maybeSpill(); - }, - iterN: function(at, n, op) { - for (var i = 0, e = this.children.length; i < e; ++i) { - var child = this.children[i], sz = child.chunkSize(); - if (at < sz) { - var used = Math.min(n, sz - at); - if (child.iterN(at, used, op)) return true; - if ((n -= used) == 0) break; - at = 0; - } else at -= sz; - } - } - }; - - var nextDocId = 0; - var Doc = CodeMirror.Doc = function(text, mode, firstLine) { - if (!(this instanceof Doc)) return new Doc(text, mode, firstLine); - if (firstLine == null) firstLine = 0; - - BranchChunk.call(this, [new LeafChunk([new Line("", null)])]); - this.first = firstLine; - this.scrollTop = this.scrollLeft = 0; - this.cantEdit = false; - this.history = makeHistory(); - this.cleanGeneration = 1; - this.frontier = firstLine; - var start = Pos(firstLine, 0); - this.sel = {from: start, to: start, head: start, anchor: start, shift: false, extend: false, goalColumn: null}; - this.id = ++nextDocId; - this.modeOption = mode; - - if (typeof text == "string") text = splitLines(text); - updateDoc(this, {from: start, to: start, text: text}, null, {head: start, anchor: start}); - }; - - Doc.prototype = createObj(BranchChunk.prototype, { - constructor: Doc, - iter: function(from, to, op) { - if (op) this.iterN(from - this.first, to - from, op); - else this.iterN(this.first, this.first + this.size, from); - }, - - insert: function(at, lines) { - var height = 0; - for (var i = 0, e = lines.length; i < e; ++i) height += lines[i].height; - this.insertInner(at - this.first, lines, height); - }, - remove: function(at, n) { this.removeInner(at - this.first, n); }, - - getValue: function(lineSep) { - var lines = getLines(this, this.first, this.first + this.size); - if (lineSep === false) return lines; - return lines.join(lineSep || "\n"); - }, - setValue: function(code) { - var top = Pos(this.first, 0), last = this.first + this.size - 1; - makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length), - text: splitLines(code), origin: "setValue"}, - {head: top, anchor: top}, true); - }, - replaceRange: function(code, from, to, origin) { - from = clipPos(this, from); - to = to ? clipPos(this, to) : from; - replaceRange(this, code, from, to, origin); - }, - getRange: function(from, to, lineSep) { - var lines = getBetween(this, clipPos(this, from), clipPos(this, to)); - if (lineSep === false) return lines; - return lines.join(lineSep || "\n"); - }, - - getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;}, - setLine: function(line, text) { - if (isLine(this, line)) - replaceRange(this, text, Pos(line, 0), clipPos(this, Pos(line))); - }, - removeLine: function(line) { - if (line) replaceRange(this, "", clipPos(this, Pos(line - 1)), clipPos(this, Pos(line))); - else replaceRange(this, "", Pos(0, 0), clipPos(this, Pos(1, 0))); - }, - - getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);}, - getLineNumber: function(line) {return lineNo(line);}, - - getLineHandleVisualStart: function(line) { - if (typeof line == "number") line = getLine(this, line); - return visualLine(this, line); - }, - - lineCount: function() {return this.size;}, - firstLine: function() {return this.first;}, - lastLine: function() {return this.first + this.size - 1;}, - - clipPos: function(pos) {return clipPos(this, pos);}, - - getCursor: function(start) { - var sel = this.sel, pos; - if (start == null || start == "head") pos = sel.head; - else if (start == "anchor") pos = sel.anchor; - else if (start == "end" || start === false) pos = sel.to; - else pos = sel.from; - return copyPos(pos); - }, - somethingSelected: function() {return !posEq(this.sel.head, this.sel.anchor);}, - - setCursor: docOperation(function(line, ch, extend) { - var pos = clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line); - if (extend) extendSelection(this, pos); - else setSelection(this, pos, pos); - }), - setSelection: docOperation(function(anchor, head, bias) { - setSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), bias); - }), - extendSelection: docOperation(function(from, to, bias) { - extendSelection(this, clipPos(this, from), to && clipPos(this, to), bias); - }), - - getSelection: function(lineSep) {return this.getRange(this.sel.from, this.sel.to, lineSep);}, - replaceSelection: function(code, collapse, origin) { - makeChange(this, {from: this.sel.from, to: this.sel.to, text: splitLines(code), origin: origin}, collapse || "around"); - }, - undo: docOperation(function() {makeChangeFromHistory(this, "undo");}), - redo: docOperation(function() {makeChangeFromHistory(this, "redo");}), - - setExtending: function(val) {this.sel.extend = val;}, - - historySize: function() { - var hist = this.history; - return {undo: hist.done.length, redo: hist.undone.length}; - }, - clearHistory: function() {this.history = makeHistory(this.history.maxGeneration);}, - - markClean: function() { - this.cleanGeneration = this.changeGeneration(); - }, - changeGeneration: function() { - this.history.lastOp = this.history.lastOrigin = null; - return this.history.generation; - }, - isClean: function (gen) { - return this.history.generation == (gen || this.cleanGeneration); - }, - - getHistory: function() { - return {done: copyHistoryArray(this.history.done), - undone: copyHistoryArray(this.history.undone)}; - }, - setHistory: function(histData) { - var hist = this.history = makeHistory(this.history.maxGeneration); - hist.done = histData.done.slice(0); - hist.undone = histData.undone.slice(0); - }, - - markText: function(from, to, options) { - return markText(this, clipPos(this, from), clipPos(this, to), options, "range"); - }, - setBookmark: function(pos, options) { - var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options), - insertLeft: options && options.insertLeft}; - pos = clipPos(this, pos); - return markText(this, pos, pos, realOpts, "bookmark"); - }, - findMarksAt: function(pos) { - pos = clipPos(this, pos); - var markers = [], spans = getLine(this, pos.line).markedSpans; - if (spans) for (var i = 0; i < spans.length; ++i) { - var span = spans[i]; - if ((span.from == null || span.from <= pos.ch) && - (span.to == null || span.to >= pos.ch)) - markers.push(span.marker.parent || span.marker); - } - return markers; - }, - getAllMarks: function() { - var markers = []; - this.iter(function(line) { - var sps = line.markedSpans; - if (sps) for (var i = 0; i < sps.length; ++i) - if (sps[i].from != null) markers.push(sps[i].marker); - }); - return markers; - }, - - posFromIndex: function(off) { - var ch, lineNo = this.first; - this.iter(function(line) { - var sz = line.text.length + 1; - if (sz > off) { ch = off; return true; } - off -= sz; - ++lineNo; - }); - return clipPos(this, Pos(lineNo, ch)); - }, - indexFromPos: function (coords) { - coords = clipPos(this, coords); - var index = coords.ch; - if (coords.line < this.first || coords.ch < 0) return 0; - this.iter(this.first, coords.line, function (line) { - index += line.text.length + 1; - }); - return index; - }, - - copy: function(copyHistory) { - var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first); - doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft; - doc.sel = {from: this.sel.from, to: this.sel.to, head: this.sel.head, anchor: this.sel.anchor, - shift: this.sel.shift, extend: false, goalColumn: this.sel.goalColumn}; - if (copyHistory) { - doc.history.undoDepth = this.history.undoDepth; - doc.setHistory(this.getHistory()); - } - return doc; - }, - - linkedDoc: function(options) { - if (!options) options = {}; - var from = this.first, to = this.first + this.size; - if (options.from != null && options.from > from) from = options.from; - if (options.to != null && options.to < to) to = options.to; - var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from); - if (options.sharedHist) copy.history = this.history; - (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist}); - copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}]; - return copy; - }, - unlinkDoc: function(other) { - if (other instanceof CodeMirror) other = other.doc; - if (this.linked) for (var i = 0; i < this.linked.length; ++i) { - var link = this.linked[i]; - if (link.doc != other) continue; - this.linked.splice(i, 1); - other.unlinkDoc(this); - break; - } - // If the histories were shared, split them again - if (other.history == this.history) { - var splitIds = [other.id]; - linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true); - other.history = makeHistory(); - other.history.done = copyHistoryArray(this.history.done, splitIds); - other.history.undone = copyHistoryArray(this.history.undone, splitIds); - } - }, - iterLinkedDocs: function(f) {linkedDocs(this, f);}, - - getMode: function() {return this.mode;}, - getEditor: function() {return this.cm;} - }); - - Doc.prototype.eachLine = Doc.prototype.iter; - - // The Doc methods that should be available on CodeMirror instances - var dontDelegate = "iter insert remove copy getEditor".split(" "); - for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) - CodeMirror.prototype[prop] = (function(method) { - return function() {return method.apply(this.doc, arguments);}; - })(Doc.prototype[prop]); - - eventMixin(Doc); - - function linkedDocs(doc, f, sharedHistOnly) { - function propagate(doc, skip, sharedHist) { - if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) { - var rel = doc.linked[i]; - if (rel.doc == skip) continue; - var shared = sharedHist && rel.sharedHist; - if (sharedHistOnly && !shared) continue; - f(rel.doc, shared); - propagate(rel.doc, doc, shared); - } - } - propagate(doc, null, true); - } - - function attachDoc(cm, doc) { - if (doc.cm) throw new Error("This document is already in use."); - cm.doc = doc; - doc.cm = cm; - estimateLineHeights(cm); - loadMode(cm); - if (!cm.options.lineWrapping) computeMaxLength(cm); - cm.options.mode = doc.modeOption; - regChange(cm); - } - - // LINE UTILITIES - - function getLine(chunk, n) { - n -= chunk.first; - while (!chunk.lines) { - for (var i = 0;; ++i) { - var child = chunk.children[i], sz = child.chunkSize(); - if (n < sz) { chunk = child; break; } - n -= sz; - } - } - return chunk.lines[n]; - } - - function getBetween(doc, start, end) { - var out = [], n = start.line; - doc.iter(start.line, end.line + 1, function(line) { - var text = line.text; - if (n == end.line) text = text.slice(0, end.ch); - if (n == start.line) text = text.slice(start.ch); - out.push(text); - ++n; - }); - return out; - } - function getLines(doc, from, to) { - var out = []; - doc.iter(from, to, function(line) { out.push(line.text); }); - return out; - } - - function updateLineHeight(line, height) { - var diff = height - line.height; - for (var n = line; n; n = n.parent) n.height += diff; - } - - function lineNo(line) { - if (line.parent == null) return null; - var cur = line.parent, no = indexOf(cur.lines, line); - for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { - for (var i = 0;; ++i) { - if (chunk.children[i] == cur) break; - no += chunk.children[i].chunkSize(); - } - } - return no + cur.first; - } - - function lineAtHeight(chunk, h) { - var n = chunk.first; - outer: do { - for (var i = 0, e = chunk.children.length; i < e; ++i) { - var child = chunk.children[i], ch = child.height; - if (h < ch) { chunk = child; continue outer; } - h -= ch; - n += child.chunkSize(); - } - return n; - } while (!chunk.lines); - for (var i = 0, e = chunk.lines.length; i < e; ++i) { - var line = chunk.lines[i], lh = line.height; - if (h < lh) break; - h -= lh; - } - return n + i; - } - - function heightAtLine(cm, lineObj) { - lineObj = visualLine(cm.doc, lineObj); - - var h = 0, chunk = lineObj.parent; - for (var i = 0; i < chunk.lines.length; ++i) { - var line = chunk.lines[i]; - if (line == lineObj) break; - else h += line.height; - } - for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { - for (var i = 0; i < p.children.length; ++i) { - var cur = p.children[i]; - if (cur == chunk) break; - else h += cur.height; - } - } - return h; - } - - function getOrder(line) { - var order = line.order; - if (order == null) order = line.order = bidiOrdering(line.text); - return order; - } - - // HISTORY - - function makeHistory(startGen) { - return { - // Arrays of history events. Doing something adds an event to - // done and clears undo. Undoing moves events from done to - // undone, redoing moves them in the other direction. - done: [], undone: [], undoDepth: Infinity, - // Used to track when changes can be merged into a single undo - // event - lastTime: 0, lastOp: null, lastOrigin: null, - // Used by the isClean() method - generation: startGen || 1, maxGeneration: startGen || 1 - }; - } - - function attachLocalSpans(doc, change, from, to) { - var existing = change["spans_" + doc.id], n = 0; - doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) { - if (line.markedSpans) - (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; - ++n; - }); - } - - function historyChangeFromChange(doc, change) { - var from = { line: change.from.line, ch: change.from.ch }; - var histChange = {from: from, to: changeEnd(change), text: getBetween(doc, change.from, change.to)}; - attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); - linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true); - return histChange; - } - - function addToHistory(doc, change, selAfter, opId) { - var hist = doc.history; - hist.undone.length = 0; - var time = +new Date, cur = lst(hist.done); - - if (cur && - (hist.lastOp == opId || - hist.lastOrigin == change.origin && change.origin && - ((change.origin.charAt(0) == "+" && doc.cm && hist.lastTime > time - doc.cm.options.historyEventDelay) || - change.origin.charAt(0) == "*"))) { - // Merge this change into the last event - var last = lst(cur.changes); - if (posEq(change.from, change.to) && posEq(change.from, last.to)) { - // Optimized case for simple insertion -- don't want to add - // new changesets for every character typed - last.to = changeEnd(change); - } else { - // Add new sub-event - cur.changes.push(historyChangeFromChange(doc, change)); - } - cur.anchorAfter = selAfter.anchor; cur.headAfter = selAfter.head; - } else { - // Can not be merged, start a new event. - cur = {changes: [historyChangeFromChange(doc, change)], - generation: hist.generation, - anchorBefore: doc.sel.anchor, headBefore: doc.sel.head, - anchorAfter: selAfter.anchor, headAfter: selAfter.head}; - hist.done.push(cur); - hist.generation = ++hist.maxGeneration; - while (hist.done.length > hist.undoDepth) - hist.done.shift(); - } - hist.lastTime = time; - hist.lastOp = opId; - hist.lastOrigin = change.origin; - } - - function removeClearedSpans(spans) { - if (!spans) return null; - for (var i = 0, out; i < spans.length; ++i) { - if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); } - else if (out) out.push(spans[i]); - } - return !out ? spans : out.length ? out : null; - } - - function getOldSpans(doc, change) { - var found = change["spans_" + doc.id]; - if (!found) return null; - for (var i = 0, nw = []; i < change.text.length; ++i) - nw.push(removeClearedSpans(found[i])); - return nw; - } - - // Used both to provide a JSON-safe object in .getHistory, and, when - // detaching a document, to split the history in two - function copyHistoryArray(events, newGroup) { - for (var i = 0, copy = []; i < events.length; ++i) { - var event = events[i], changes = event.changes, newChanges = []; - copy.push({changes: newChanges, anchorBefore: event.anchorBefore, headBefore: event.headBefore, - anchorAfter: event.anchorAfter, headAfter: event.headAfter}); - for (var j = 0; j < changes.length; ++j) { - var change = changes[j], m; - newChanges.push({from: change.from, to: change.to, text: change.text}); - if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) { - if (indexOf(newGroup, Number(m[1])) > -1) { - lst(newChanges)[prop] = change[prop]; - delete change[prop]; - } - } - } - } - return copy; - } - - // Rebasing/resetting history to deal with externally-sourced changes - - function rebaseHistSel(pos, from, to, diff) { - if (to < pos.line) { - pos.line += diff; - } else if (from < pos.line) { - pos.line = from; - pos.ch = 0; - } - } - - // Tries to rebase an array of history events given a change in the - // document. If the change touches the same lines as the event, the - // event, and everything 'behind' it, is discarded. If the change is - // before the event, the event's positions are updated. Uses a - // copy-on-write scheme for the positions, to avoid having to - // reallocate them all on every rebase, but also avoid problems with - // shared position objects being unsafely updated. - function rebaseHistArray(array, from, to, diff) { - for (var i = 0; i < array.length; ++i) { - var sub = array[i], ok = true; - for (var j = 0; j < sub.changes.length; ++j) { - var cur = sub.changes[j]; - if (!sub.copied) { cur.from = copyPos(cur.from); cur.to = copyPos(cur.to); } - if (to < cur.from.line) { - cur.from.line += diff; - cur.to.line += diff; - } else if (from <= cur.to.line) { - ok = false; - break; - } - } - if (!sub.copied) { - sub.anchorBefore = copyPos(sub.anchorBefore); sub.headBefore = copyPos(sub.headBefore); - sub.anchorAfter = copyPos(sub.anchorAfter); sub.readAfter = copyPos(sub.headAfter); - sub.copied = true; - } - if (!ok) { - array.splice(0, i + 1); - i = 0; - } else { - rebaseHistSel(sub.anchorBefore); rebaseHistSel(sub.headBefore); - rebaseHistSel(sub.anchorAfter); rebaseHistSel(sub.headAfter); - } - } - } - - function rebaseHist(hist, change) { - var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1; - rebaseHistArray(hist.done, from, to, diff); - rebaseHistArray(hist.undone, from, to, diff); - } - - // EVENT OPERATORS - - function stopMethod() {e_stop(this);} - // Ensure an event has a stop method. - function addStop(event) { - if (!event.stop) event.stop = stopMethod; - return event; - } - - function e_preventDefault(e) { - if (e.preventDefault) e.preventDefault(); - else e.returnValue = false; } - function e_stopPropagation(e) { - if (e.stopPropagation) e.stopPropagation(); - else e.cancelBubble = true; - } - function e_defaultPrevented(e) { - return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false; - } - function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);} - CodeMirror.e_stop = e_stop; - CodeMirror.e_preventDefault = e_preventDefault; - CodeMirror.e_stopPropagation = e_stopPropagation; - - function e_target(e) {return e.target || e.srcElement;} - function e_button(e) { - var b = e.which; - if (b == null) { - if (e.button & 1) b = 1; - else if (e.button & 2) b = 3; - else if (e.button & 4) b = 2; - } - if (mac && e.ctrlKey && b == 1) b = 3; - return b; - } - - // EVENT HANDLING - - function on(emitter, type, f) { - if (emitter.addEventListener) - emitter.addEventListener(type, f, false); - else if (emitter.attachEvent) - emitter.attachEvent("on" + type, f); - else { - var map = emitter._handlers || (emitter._handlers = {}); - var arr = map[type] || (map[type] = []); - arr.push(f); - } - } - - function off(emitter, type, f) { - if (emitter.removeEventListener) - emitter.removeEventListener(type, f, false); - else if (emitter.detachEvent) - emitter.detachEvent("on" + type, f); - else { - var arr = emitter._handlers && emitter._handlers[type]; - if (!arr) return; - for (var i = 0; i < arr.length; ++i) - if (arr[i] == f) { arr.splice(i, 1); break; } - } - } - - function signal(emitter, type /*, values...*/) { - var arr = emitter._handlers && emitter._handlers[type]; - if (!arr) return; - var args = Array.prototype.slice.call(arguments, 2); - for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args); - } - - var delayedCallbacks, delayedCallbackDepth = 0; - function signalLater(emitter, type /*, values...*/) { - var arr = emitter._handlers && emitter._handlers[type]; - if (!arr) return; - var args = Array.prototype.slice.call(arguments, 2); - if (!delayedCallbacks) { - ++delayedCallbackDepth; - delayedCallbacks = []; - setTimeout(fireDelayed, 0); - } - function bnd(f) {return function(){f.apply(null, args);};}; - for (var i = 0; i < arr.length; ++i) - delayedCallbacks.push(bnd(arr[i])); - } - - function signalDOMEvent(cm, e, override) { - signal(cm, override || e.type, cm, e); - return e_defaultPrevented(e) || e.codemirrorIgnore; - } - - function fireDelayed() { - --delayedCallbackDepth; - var delayed = delayedCallbacks; - delayedCallbacks = null; - for (var i = 0; i < delayed.length; ++i) delayed[i](); - } - - function hasHandler(emitter, type) { - var arr = emitter._handlers && emitter._handlers[type]; - return arr && arr.length > 0; - } - - CodeMirror.on = on; CodeMirror.off = off; CodeMirror.signal = signal; - - function eventMixin(ctor) { - ctor.prototype.on = function(type, f) {on(this, type, f);}; - ctor.prototype.off = function(type, f) {off(this, type, f);}; - } - - // MISC UTILITIES - - // Number of pixels added to scroller and sizer to hide scrollbar - var scrollerCutOff = 30; - - // Returned or thrown by various protocols to signal 'I'm not - // handling this'. - var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}}; - - function Delayed() {this.id = null;} - Delayed.prototype = {set: function(ms, f) {clearTimeout(this.id); this.id = setTimeout(f, ms);}}; - - // Counts the column offset in a string, taking tabs into account. - // Used mostly to find indentation. - function countColumn(string, end, tabSize, startIndex, startValue) { - if (end == null) { - end = string.search(/[^\s\u00a0]/); - if (end == -1) end = string.length; - } - for (var i = startIndex || 0, n = startValue || 0; i < end; ++i) { - if (string.charAt(i) == "\t") n += tabSize - (n % tabSize); - else ++n; - } - return n; - } - CodeMirror.countColumn = countColumn; - - var spaceStrs = [""]; - function spaceStr(n) { - while (spaceStrs.length <= n) - spaceStrs.push(lst(spaceStrs) + " "); - return spaceStrs[n]; - } - - function lst(arr) { return arr[arr.length-1]; } - - function selectInput(node) { - if (ios) { // Mobile Safari apparently has a bug where select() is broken. - node.selectionStart = 0; - node.selectionEnd = node.value.length; - } else { - // Suppress mysterious IE10 errors - try { node.select(); } - catch(_e) {} - } - } - - function indexOf(collection, elt) { - if (collection.indexOf) return collection.indexOf(elt); - for (var i = 0, e = collection.length; i < e; ++i) - if (collection[i] == elt) return i; - return -1; - } - - function createObj(base, props) { - function Obj() {} - Obj.prototype = base; - var inst = new Obj(); - if (props) copyObj(props, inst); - return inst; - } - - function copyObj(obj, target) { - if (!target) target = {}; - for (var prop in obj) if (obj.hasOwnProperty(prop)) target[prop] = obj[prop]; - return target; - } - - function emptyArray(size) { - for (var a = [], i = 0; i < size; ++i) a.push(undefined); - return a; - } - - function bind(f) { - var args = Array.prototype.slice.call(arguments, 1); - return function(){return f.apply(null, args);}; - } - - var nonASCIISingleCaseWordChar = /[\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; - function isWordChar(ch) { - return /\w/.test(ch) || ch > "\x80" && - (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)); - } - - function isEmpty(obj) { - for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false; - return true; - } - - var isExtendingChar = /[\u0300-\u036F\u0483-\u0487\u0488-\u0489\u0591-\u05BD\u05BF\u05C1-\u05C2\u05C4-\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7-\u06E8\u06EA-\u06ED\uA66F\u1DC0–\u1DFF\u20D0–\u20FF\uA670-\uA672\uA674-\uA67D\uA69F\udc00-\udfff\uFE20–\uFE2F]/; - - // DOM UTILITIES - - function elt(tag, content, className, style) { - var e = document.createElement(tag); - if (className) e.className = className; - if (style) e.style.cssText = style; - if (typeof content == "string") setTextContent(e, content); - else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]); - return e; - } - - function removeChildren(e) { - for (var count = e.childNodes.length; count > 0; --count) - e.removeChild(e.firstChild); - return e; - } - - function removeChildrenAndAdd(parent, e) { - return removeChildren(parent).appendChild(e); - } - - function setTextContent(e, str) { - if (ie_lt9) { - e.innerHTML = ""; - e.appendChild(document.createTextNode(str)); - } else e.textContent = str; - } - - function getRect(node) { - return node.getBoundingClientRect(); - } - CodeMirror.replaceGetRect = function(f) { getRect = f; }; - - // FEATURE DETECTION - - // Detect drag-and-drop - var dragAndDrop = function() { - // There is *some* kind of drag-and-drop support in IE6-8, but I - // couldn't get it to work yet. - if (ie_lt9) return false; - var div = elt('div'); - return "draggable" in div || "dragDrop" in div; - }(); - - // For a reason I have yet to figure out, some browsers disallow - // word wrapping between certain characters *only* if a new inline - // element is started between them. This makes it hard to reliably - // measure the position of things, since that requires inserting an - // extra span. This terribly fragile set of tests matches the - // character combinations that suffer from this phenomenon on the - // various browsers. - function spanAffectsWrapping() { return false; } - if (gecko) // Only for "$'" - spanAffectsWrapping = function(str, i) { - return str.charCodeAt(i - 1) == 36 && str.charCodeAt(i) == 39; - }; - else if (safari && !/Version\/([6-9]|\d\d)\b/.test(navigator.userAgent)) - spanAffectsWrapping = function(str, i) { - var result = /\-[^ \-?]|\?[^ !\'\"\),.\-\/:;\?\]\}]/.test(str.slice(i - 1, i + 1)); - return result; - }; - else if (webkit && /Chrome\/(?:29|[3-9]\d|\d\d\d)\./.test(navigator.userAgent)) - spanAffectsWrapping = function(str, i) { - var code = str.charCodeAt(i - 1); - return code >= 8208 && code <= 8212; - }; - else if (webkit) - spanAffectsWrapping = function(str, i) { - if (i > 1 && str.charCodeAt(i - 1) == 45) { - if (/\w/.test(str.charAt(i - 2)) && /[^\-?\.]/.test(str.charAt(i))) return true; - if (i > 2 && /[\d\.,]/.test(str.charAt(i - 2)) && /[\d\.,]/.test(str.charAt(i))) return false; - } - var result = /[~!#%&*)=+}\]\\|\"\.>,:;][({[<]|-[^\-?\.\u2010-\u201f\u2026]|\?[\w~`@#$%\^&*(_=+{[|><]|…[\w~`@#$%\^&*(_=+{[><]/.test(str.slice(i - 1, i + 1)); - return result; - }; - - var knownScrollbarWidth; - function scrollbarWidth(measure) { - if (knownScrollbarWidth != null) return knownScrollbarWidth; - var test = elt("div", null, null, "width: 50px; height: 50px; overflow-x: scroll"); - removeChildrenAndAdd(measure, test); - if (test.offsetWidth) - knownScrollbarWidth = test.offsetHeight - test.clientHeight; - return knownScrollbarWidth || 0; - } - - var zwspSupported; - function zeroWidthElement(measure) { - if (zwspSupported == null) { - var test = elt("span", "\u200b"); - removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])); - if (measure.firstChild.offsetHeight != 0) - zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !ie_lt8; - } - if (zwspSupported) return elt("span", "\u200b"); - else return elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px"); - } - - // See if "".split is the broken IE version, if so, provide an - // alternative way to split lines. - var splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) { - var pos = 0, result = [], l = string.length; - while (pos <= l) { - var nl = string.indexOf("\n", pos); - if (nl == -1) nl = string.length; - var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl); - var rt = line.indexOf("\r"); - if (rt != -1) { - result.push(line.slice(0, rt)); - pos += rt + 1; - } else { - result.push(line); - pos = nl + 1; - } - } - return result; - } : function(string){return string.split(/\r\n?|\n/);}; - CodeMirror.splitLines = splitLines; - - var hasSelection = window.getSelection ? function(te) { - try { return te.selectionStart != te.selectionEnd; } - catch(e) { return false; } - } : function(te) { - try {var range = te.ownerDocument.selection.createRange();} - catch(e) {} - if (!range || range.parentElement() != te) return false; - return range.compareEndPoints("StartToEnd", range) != 0; - }; - - var hasCopyEvent = (function() { - var e = elt("div"); - if ("oncopy" in e) return true; - e.setAttribute("oncopy", "return;"); - return typeof e.oncopy == 'function'; - })(); - - // KEY NAMING - - var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt", - 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End", - 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert", - 46: "Delete", 59: ";", 91: "Mod", 92: "Mod", 93: "Mod", 109: "-", 107: "=", 127: "Delete", - 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", - 221: "]", 222: "'", 63276: "PageUp", 63277: "PageDown", 63275: "End", 63273: "Home", - 63234: "Left", 63232: "Up", 63235: "Right", 63233: "Down", 63302: "Insert", 63272: "Delete"}; - CodeMirror.keyNames = keyNames; - (function() { - // Number keys - for (var i = 0; i < 10; i++) keyNames[i + 48] = String(i); - // Alphabetic keys - for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i); - // Function keys - for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i; - })(); - - // BIDI HELPERS - - function iterateBidiSections(order, from, to, f) { - if (!order) return f(from, to, "ltr"); - var found = false; - for (var i = 0; i < order.length; ++i) { - var part = order[i]; - if (part.from < to && part.to > from || from == to && part.to == from) { - f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr"); - found = true; - } - } - if (!found) f(from, to, "ltr"); - } - - function bidiLeft(part) { return part.level % 2 ? part.to : part.from; } - function bidiRight(part) { return part.level % 2 ? part.from : part.to; } - - function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; } - function lineRight(line) { - var order = getOrder(line); - if (!order) return line.text.length; - return bidiRight(lst(order)); - } - - function lineStart(cm, lineN) { - var line = getLine(cm.doc, lineN); - var visual = visualLine(cm.doc, line); - if (visual != line) lineN = lineNo(visual); - var order = getOrder(visual); - var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual); - return Pos(lineN, ch); - } - function lineEnd(cm, lineN) { - var merged, line; - while (merged = collapsedSpanAtEnd(line = getLine(cm.doc, lineN))) - lineN = merged.find().to.line; - var order = getOrder(line); - var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line); - return Pos(lineN, ch); - } - - function compareBidiLevel(order, a, b) { - var linedir = order[0].level; - if (a == linedir) return true; - if (b == linedir) return false; - return a < b; - } - var bidiOther; - function getBidiPartAt(order, pos) { - for (var i = 0, found; i < order.length; ++i) { - var cur = order[i]; - if (cur.from < pos && cur.to > pos) { bidiOther = null; return i; } - if (cur.from == pos || cur.to == pos) { - if (found == null) { - found = i; - } else if (compareBidiLevel(order, cur.level, order[found].level)) { - bidiOther = found; - return i; - } else { - bidiOther = i; - return found; - } - } - } - bidiOther = null; - return found; - } - - function moveInLine(line, pos, dir, byUnit) { - if (!byUnit) return pos + dir; - do pos += dir; - while (pos > 0 && isExtendingChar.test(line.text.charAt(pos))); - return pos; - } - - // This is somewhat involved. It is needed in order to move - // 'visually' through bi-directional text -- i.e., pressing left - // should make the cursor go left, even when in RTL text. The - // tricky part is the 'jumps', where RTL and LTR text touch each - // other. This often requires the cursor offset to move more than - // one unit, in order to visually move one unit. - function moveVisually(line, start, dir, byUnit) { - var bidi = getOrder(line); - if (!bidi) return moveLogically(line, start, dir, byUnit); - var pos = getBidiPartAt(bidi, start), part = bidi[pos]; - var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit); - - for (;;) { - if (target > part.from && target < part.to) return target; - if (target == part.from || target == part.to) { - if (getBidiPartAt(bidi, target) == pos) return target; - part = bidi[pos += dir]; - return (dir > 0) == part.level % 2 ? part.to : part.from; - } else { - part = bidi[pos += dir]; - if (!part) return null; - if ((dir > 0) == part.level % 2) - target = moveInLine(line, part.to, -1, byUnit); - else - target = moveInLine(line, part.from, 1, byUnit); - } - } - } - - function moveLogically(line, start, dir, byUnit) { - var target = start + dir; - if (byUnit) while (target > 0 && isExtendingChar.test(line.text.charAt(target))) target += dir; - return target < 0 || target > line.text.length ? null : target; - } - - // Bidirectional ordering algorithm - // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm - // that this (partially) implements. - - // One-char codes used for character types: - // L (L): Left-to-Right - // R (R): Right-to-Left - // r (AL): Right-to-Left Arabic - // 1 (EN): European Number - // + (ES): European Number Separator - // % (ET): European Number Terminator - // n (AN): Arabic Number - // , (CS): Common Number Separator - // m (NSM): Non-Spacing Mark - // b (BN): Boundary Neutral - // s (B): Paragraph Separator - // t (S): Segment Separator - // w (WS): Whitespace - // N (ON): Other Neutrals - - // Returns null if characters are ordered as they appear - // (left-to-right), or an array of sections ({from, to, level} - // objects) in the order in which they occur visually. - var bidiOrdering = (function() { - // Character types for codepoints 0 to 0xff - var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLL"; - // Character types for codepoints 0x600 to 0x6ff - var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmmrrrrrrrrrrrrrrrrrr"; - function charType(code) { - if (code <= 0xff) return lowTypes.charAt(code); - else if (0x590 <= code && code <= 0x5f4) return "R"; - else if (0x600 <= code && code <= 0x6ff) return arabicTypes.charAt(code - 0x600); - else if (0x700 <= code && code <= 0x8ac) return "r"; - else return "L"; - } - - var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; - var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/; - // Browsers seem to always treat the boundaries of block elements as being L. - var outerType = "L"; - - return function(str) { - if (!bidiRE.test(str)) return false; - var len = str.length, types = []; - for (var i = 0, type; i < len; ++i) - types.push(type = charType(str.charCodeAt(i))); - - // W1. Examine each non-spacing mark (NSM) in the level run, and - // change the type of the NSM to the type of the previous - // character. If the NSM is at the start of the level run, it will - // get the type of sor. - for (var i = 0, prev = outerType; i < len; ++i) { - var type = types[i]; - if (type == "m") types[i] = prev; - else prev = type; - } - - // W2. Search backwards from each instance of a European number - // until the first strong type (R, L, AL, or sor) is found. If an - // AL is found, change the type of the European number to Arabic - // number. - // W3. Change all ALs to R. - for (var i = 0, cur = outerType; i < len; ++i) { - var type = types[i]; - if (type == "1" && cur == "r") types[i] = "n"; - else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; } - } - - // W4. A single European separator between two European numbers - // changes to a European number. A single common separator between - // two numbers of the same type changes to that type. - for (var i = 1, prev = types[0]; i < len - 1; ++i) { - var type = types[i]; - if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1"; - else if (type == "," && prev == types[i+1] && - (prev == "1" || prev == "n")) types[i] = prev; - prev = type; - } - - // W5. A sequence of European terminators adjacent to European - // numbers changes to all European numbers. - // W6. Otherwise, separators and terminators change to Other - // Neutral. - for (var i = 0; i < len; ++i) { - var type = types[i]; - if (type == ",") types[i] = "N"; - else if (type == "%") { - for (var end = i + 1; end < len && types[end] == "%"; ++end) {} - var replace = (i && types[i-1] == "!") || (end < len - 1 && types[end] == "1") ? "1" : "N"; - for (var j = i; j < end; ++j) types[j] = replace; - i = end - 1; - } - } - - // W7. Search backwards from each instance of a European number - // until the first strong type (R, L, or sor) is found. If an L is - // found, then change the type of the European number to L. - for (var i = 0, cur = outerType; i < len; ++i) { - var type = types[i]; - if (cur == "L" && type == "1") types[i] = "L"; - else if (isStrong.test(type)) cur = type; - } - - // N1. A sequence of neutrals takes the direction of the - // surrounding strong text if the text on both sides has the same - // direction. European and Arabic numbers act as if they were R in - // terms of their influence on neutrals. Start-of-level-run (sor) - // and end-of-level-run (eor) are used at level run boundaries. - // N2. Any remaining neutrals take the embedding direction. - for (var i = 0; i < len; ++i) { - if (isNeutral.test(types[i])) { - for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {} - var before = (i ? types[i-1] : outerType) == "L"; - var after = (end < len - 1 ? types[end] : outerType) == "L"; - var replace = before || after ? "L" : "R"; - for (var j = i; j < end; ++j) types[j] = replace; - i = end - 1; - } - } - - // Here we depart from the documented algorithm, in order to avoid - // building up an actual levels array. Since there are only three - // levels (0, 1, 2) in an implementation that doesn't take - // explicit embedding into account, we can build up the order on - // the fly, without following the level-based algorithm. - var order = [], m; - for (var i = 0; i < len;) { - if (countsAsLeft.test(types[i])) { - var start = i; - for (++i; i < len && countsAsLeft.test(types[i]); ++i) {} - order.push({from: start, to: i, level: 0}); - } else { - var pos = i, at = order.length; - for (++i; i < len && types[i] != "L"; ++i) {} - for (var j = pos; j < i;) { - if (countsAsNum.test(types[j])) { - if (pos < j) order.splice(at, 0, {from: pos, to: j, level: 1}); - var nstart = j; - for (++j; j < i && countsAsNum.test(types[j]); ++j) {} - order.splice(at, 0, {from: nstart, to: j, level: 2}); - pos = j; - } else ++j; - } - if (pos < i) order.splice(at, 0, {from: pos, to: i, level: 1}); - } - } - if (order[0].level == 1 && (m = str.match(/^\s+/))) { - order[0].from = m[0].length; - order.unshift({from: 0, to: m[0].length, level: 0}); - } - if (lst(order).level == 1 && (m = str.match(/\s+$/))) { - lst(order).to -= m[0].length; - order.push({from: len - m[0].length, to: len, level: 0}); - } - if (order[0].level != lst(order).level) - order.push({from: len, to: len, level: order[0].level}); - - return order; - }; - })(); - - // THE END - - CodeMirror.version = "3.20.0"; - return CodeMirror; -})(); + textarea.style.display = "none" + var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); }, + options) + return cm +} + +function addLegacyProps(CodeMirror) { + CodeMirror.off = off + CodeMirror.on = on + CodeMirror.wheelEventPixels = wheelEventPixels + CodeMirror.Doc = Doc + CodeMirror.splitLines = splitLinesAuto + CodeMirror.countColumn = countColumn + CodeMirror.findColumn = findColumn + CodeMirror.isWordChar = isWordCharBasic + CodeMirror.Pass = Pass + CodeMirror.signal = signal + CodeMirror.Line = Line + CodeMirror.changeEnd = changeEnd + CodeMirror.scrollbarModel = scrollbarModel + CodeMirror.Pos = Pos + CodeMirror.cmpPos = cmp + CodeMirror.modes = modes + CodeMirror.mimeModes = mimeModes + CodeMirror.resolveMode = resolveMode + CodeMirror.getMode = getMode + CodeMirror.modeExtensions = modeExtensions + CodeMirror.extendMode = extendMode + CodeMirror.copyState = copyState + CodeMirror.startState = startState + CodeMirror.innerMode = innerMode + CodeMirror.commands = commands + CodeMirror.keyMap = keyMap + CodeMirror.keyName = keyName + CodeMirror.isModifierKey = isModifierKey + CodeMirror.lookupKey = lookupKey + CodeMirror.normalizeKeyMap = normalizeKeyMap + CodeMirror.StringStream = StringStream + CodeMirror.SharedTextMarker = SharedTextMarker + CodeMirror.TextMarker = TextMarker + CodeMirror.LineWidget = LineWidget + CodeMirror.e_preventDefault = e_preventDefault + CodeMirror.e_stopPropagation = e_stopPropagation + CodeMirror.e_stop = e_stop + CodeMirror.addClass = addClass + CodeMirror.contains = contains + CodeMirror.rmClass = rmClass + CodeMirror.keyNames = keyNames +} + +// EDITOR CONSTRUCTOR + +defineOptions(CodeMirror) + +addEditorMethods(CodeMirror) + +// Set up methods on CodeMirror's prototype to redirect to the editor's document. +var dontDelegate = "iter insert remove copy getEditor constructor".split(" ") +for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) + { CodeMirror.prototype[prop] = (function(method) { + return function() {return method.apply(this.doc, arguments)} + })(Doc.prototype[prop]) } } + +eventMixin(Doc) + +// INPUT HANDLING + +CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput} + +// MODE DEFINITION AND QUERYING + +// Extra arguments are stored as the mode's dependencies, which is +// used by (legacy) mechanisms like loadmode.js to automatically +// load a mode. (Preferred mechanism is the require/define calls.) +CodeMirror.defineMode = function(name/*, mode, …*/) { + if (!CodeMirror.defaults.mode && name != "null") { CodeMirror.defaults.mode = name } + defineMode.apply(this, arguments) +} + +CodeMirror.defineMIME = defineMIME + +// Minimal default mode. +CodeMirror.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); }) +CodeMirror.defineMIME("text/plain", "null") + +// EXTENSIONS + +CodeMirror.defineExtension = function (name, func) { + CodeMirror.prototype[name] = func +} +CodeMirror.defineDocExtension = function (name, func) { + Doc.prototype[name] = func +} + +CodeMirror.fromTextArea = fromTextArea + +addLegacyProps(CodeMirror) + +CodeMirror.version = "5.21.1" + +return CodeMirror; + +}))); \ No newline at end of file diff --git a/Source/WebInspectorUI/UserInterface/External/CodeMirror/coffeescript.js b/Source/WebInspectorUI/UserInterface/External/CodeMirror/coffeescript.js index e8bfe48a2..adf2184fd 100644 --- a/Source/WebInspectorUI/UserInterface/External/CodeMirror/coffeescript.js +++ b/Source/WebInspectorUI/UserInterface/External/CodeMirror/coffeescript.js @@ -1,18 +1,31 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + /** * Link to the project's GitHub page: * https://github.com/pickhardt/coffeescript-codemirror-mode */ -CodeMirror.defineMode("coffeescript", function(conf) { +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +CodeMirror.defineMode("coffeescript", function(conf, parserConf) { var ERRORCLASS = "error"; function wordRegexp(words) { return new RegExp("^((" + words.join(")|(") + "))\\b"); } - var operators = /^(?:->|=>|\+[+=]?|-[\-=]?|\*[\*=]?|\/[\/=]?|[=!]=|<[><]?=?|>>?=?|%=?|&=?|\|=?|\^=?|\~|!|\?)/; + var operators = /^(?:->|=>|\+[+=]?|-[\-=]?|\*[\*=]?|\/[\/=]?|[=!]=|<[><]?=?|>>?=?|%=?|&=?|\|=?|\^=?|\~|!|\?|(or|and|\|\||&&|\?)=)/; var delimiters = /^(?:[()\[\]{},:`=;]|\.\.?\.?)/; var identifiers = /^[_A-Za-z$][_A-Za-z$0-9]*/; - var properties = /^(@|this\.)[_A-Za-z$][_A-Za-z$0-9]*/; + var atProp = /^@[_A-Za-z$][_A-Za-z$0-9]*/; var wordOperators = wordRegexp(["and", "or", "not", "is", "isnt", "in", @@ -21,7 +34,7 @@ CodeMirror.defineMode("coffeescript", function(conf) { "switch", "try", "catch", "finally", "class"]; var commonKeywords = ["break", "by", "continue", "debugger", "delete", "do", "in", "of", "new", "return", "then", - "this", "throw", "when", "until"]; + "this", "@", "throw", "when", "until", "extends"]; var keywords = wordRegexp(indentKeywords.concat(commonKeywords)); @@ -119,19 +132,21 @@ CodeMirror.defineMode("coffeescript", function(conf) { // Handle strings if (stream.match(stringPrefixes)) { - state.tokenize = tokenFactory(stream.current(), "string"); + state.tokenize = tokenFactory(stream.current(), false, "string"); return state.tokenize(stream, state); } // Handle regex literals if (stream.match(regexPrefixes)) { if (stream.current() != "/" || stream.match(/^.*\//, false)) { // prevent highlight of division - state.tokenize = tokenFactory(stream.current(), "string-2"); + state.tokenize = tokenFactory(stream.current(), true, "string-2"); return state.tokenize(stream, state); } else { stream.backUp(1); } } + + // Handle operators and delimiters if (stream.match(operators) || stream.match(wordOperators)) { return "operator"; @@ -144,6 +159,10 @@ CodeMirror.defineMode("coffeescript", function(conf) { return "atom"; } + if (stream.match(atProp) || state.prop && stream.match(identifiers)) { + return "property"; + } + if (stream.match(keywords)) { return "keyword"; } @@ -152,17 +171,12 @@ CodeMirror.defineMode("coffeescript", function(conf) { return "variable"; } - if (stream.match(properties)) { - return "property"; - } - // Handle non-detected items stream.next(); return ERRORCLASS; } - function tokenFactory(delimiter, outclass) { - var singleline = delimiter.length == 1; + function tokenFactory(delimiter, singleline, outclass) { return function(stream, state) { while (!stream.eol()) { stream.eatWhile(/[^'"\/\\]/); @@ -179,7 +193,7 @@ CodeMirror.defineMode("coffeescript", function(conf) { } } if (singleline) { - if (conf.mode.singleLineStringErrors) { + if (parserConf.singleLineStringErrors) { outclass = ERRORCLASS; } else { state.tokenize = tokenBase; @@ -205,7 +219,7 @@ CodeMirror.defineMode("coffeescript", function(conf) { type = type || "coffee"; var offset = 0, align = false, alignOffset = null; for (var scope = state.scope; scope; scope = scope.prev) { - if (scope.type === "coffee") { + if (scope.type === "coffee" || scope.type == "}") { offset = scope.offset + conf.indentUnit; break; } @@ -253,24 +267,11 @@ CodeMirror.defineMode("coffeescript", function(conf) { var style = state.tokenize(stream, state); var current = stream.current(); - // Handle "." connected identifiers - if (current === ".") { - style = state.tokenize(stream, state); - current = stream.current(); - if (/^\.[\w$]+$/.test(current)) { - return "variable"; - } else { - return ERRORCLASS; - } - } - // Handle scope changes. if (current === "return") { - state.dedent += 1; + state.dedent = true; } - if (((current === "->" || current === "=>") && - !state.lambda && - !stream.peek()) + if (((current === "->" || current === "=>") && stream.eol()) || style === "indent") { indent(stream, state); } @@ -298,9 +299,10 @@ CodeMirror.defineMode("coffeescript", function(conf) { if (state.scope.type == current) state.scope = state.scope.prev; } - if (state.dedent > 0 && stream.eol() && state.scope.type == "coffee") { - if (state.scope.prev) state.scope = state.scope.prev; - state.dedent -= 1; + if (state.dedent && stream.eol()) { + if (state.scope.type == "coffee" && state.scope.prev) + state.scope = state.scope.prev; + state.dedent = false; } return style; @@ -311,8 +313,7 @@ CodeMirror.defineMode("coffeescript", function(conf) { return { tokenize: tokenBase, scope: {offset:basecolumn || 0, type:"coffee", prev: null, align: false}, - lastToken: null, - lambda: false, + prop: false, dedent: 0 }; }, @@ -322,12 +323,9 @@ CodeMirror.defineMode("coffeescript", function(conf) { if (fillAlign && stream.sol()) fillAlign.align = false; var style = tokenLexer(stream, state); - if (fillAlign && style && style != "comment") fillAlign.align = true; - - state.lastToken = {style:style, content: stream.current()}; - - if (stream.eol() && stream.lambda) { - state.lambda = false; + if (style && style != "comment") { + if (fillAlign) fillAlign.align = true; + state.prop = style == "punctuation" && stream.current() == "." } return style; @@ -352,3 +350,6 @@ CodeMirror.defineMode("coffeescript", function(conf) { }); CodeMirror.defineMIME("text/x-coffeescript", "coffeescript"); +CodeMirror.defineMIME("text/coffeescript", "coffeescript"); + +}); diff --git a/Source/WebInspectorUI/UserInterface/External/CodeMirror/comment.js b/Source/WebInspectorUI/UserInterface/External/CodeMirror/comment.js index cd2123e17..d71cf4360 100644 --- a/Source/WebInspectorUI/UserInterface/External/CodeMirror/comment.js +++ b/Source/WebInspectorUI/UserInterface/External/CodeMirror/comment.js @@ -1,4 +1,14 @@ -(function() { +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { "use strict"; var noOptions = {}; @@ -11,13 +21,40 @@ } CodeMirror.commands.toggleComment = function(cm) { - var from = cm.getCursor("start"), to = cm.getCursor("end"); - cm.uncomment(from, to) || cm.lineComment(from, to); + cm.toggleComment(); }; + CodeMirror.defineExtension("toggleComment", function(options) { + if (!options) options = noOptions; + var cm = this; + var minLine = Infinity, ranges = this.listSelections(), mode = null; + for (var i = ranges.length - 1; i >= 0; i--) { + var from = ranges[i].from(), to = ranges[i].to(); + if (from.line >= minLine) continue; + if (to.line >= minLine) to = Pos(minLine, 0); + minLine = from.line; + if (mode == null) { + if (cm.uncomment(from, to, options)) mode = "un"; + else { cm.lineComment(from, to, options); mode = "line"; } + } else if (mode == "un") { + cm.uncomment(from, to, options); + } else { + cm.lineComment(from, to, options); + } + } + }); + + // Rough heuristic to try and detect lines that are part of multi-line string + function probablyInsideString(cm, pos, line) { + return /\bstring\b/.test(cm.getTokenTypeAt(Pos(pos.line, 0))) && !/^[\'\"`]/.test(line) + } + CodeMirror.defineExtension("lineComment", function(from, to, options) { if (!options) options = noOptions; var self = this, mode = self.getModeAt(from); + var firstLine = self.getLine(from.line); + if (firstLine == null || probablyInsideString(self, from, firstLine)) return; + var commentString = options.lineComment || mode.lineComment; if (!commentString) { if (options.blockCommentStart || mode.blockCommentStart) { @@ -26,15 +63,21 @@ } return; } - var firstLine = self.getLine(from.line); - if (firstLine == null) return; + var end = Math.min(to.ch != 0 || to.line == from.line ? to.line + 1 : to.line, self.lastLine() + 1); var pad = options.padding == null ? " " : options.padding; var blankLines = options.commentBlankLines || from.line == to.line; self.operation(function() { if (options.indent) { - var baseString = firstLine.slice(0, firstNonWS(firstLine)); + var baseString = null; + for (var i = from.line; i < end; ++i) { + var line = self.getLine(i); + var whitespace = line.slice(0, firstNonWS(line)); + if (baseString == null || baseString.length > whitespace.length) { + baseString = whitespace; + } + } for (var i = from.line; i < end; ++i) { var line = self.getLine(i), cut = baseString.length; if (!blankLines && !nonWS.test(line)) continue; @@ -60,6 +103,7 @@ self.lineComment(from, to, options); return; } + if (/\bcomment\b/.test(self.getTokenTypeAt(Pos(from.line, 0)))) return var end = Math.min(to.line, self.lastLine()); if (end != from.line && to.ch == 0 && nonWS.test(self.getLine(end))) --end; @@ -86,7 +130,7 @@ CodeMirror.defineExtension("uncomment", function(from, to, options) { if (!options) options = noOptions; var self = this, mode = self.getModeAt(from); - var end = Math.min(to.line, self.lastLine()), start = Math.min(from.line, end); + var end = Math.min(to.ch != 0 || to.line == from.line ? to.line : to.line - 1, self.lastLine()), start = Math.min(from.line, end); // Try finding line comments var lineString = options.lineComment || mode.lineComment, lines = []; @@ -96,8 +140,9 @@ for (var i = start; i <= end; ++i) { var line = self.getLine(i); var found = line.indexOf(lineString); - if (found == -1 && (i != end || i == start) && nonWS.test(line)) break lineComment; - if (i != start && found > -1 && nonWS.test(line.slice(0, found))) break lineComment; + if (found > -1 && !/comment/.test(self.getTokenTypeAt(Pos(i, found + 1)))) found = -1; + if (found == -1 && nonWS.test(line)) break lineComment; + if (found > -1 && nonWS.test(line.slice(0, found))) break lineComment; lines.push(line); } self.operation(function() { @@ -118,13 +163,29 @@ var endString = options.blockCommentEnd || mode.blockCommentEnd; if (!startString || !endString) return false; var lead = options.blockCommentLead || mode.blockCommentLead; - var startLine = self.getLine(start), endLine = end == start ? startLine : self.getLine(end); - var open = startLine.indexOf(startString), close = endLine.lastIndexOf(endString); + var startLine = self.getLine(start), open = startLine.indexOf(startString) + if (open == -1) return false + var endLine = end == start ? startLine : self.getLine(end) + var close = endLine.indexOf(endString, end == start ? open + startString.length : 0); if (close == -1 && start != end) { endLine = self.getLine(--end); - close = endLine.lastIndexOf(endString); + close = endLine.indexOf(endString); } - if (open == -1 || close == -1) return false; + if (close == -1 || + !/comment/.test(self.getTokenTypeAt(Pos(start, open + 1))) || + !/comment/.test(self.getTokenTypeAt(Pos(end, close + 1)))) + return false; + + // Avoid killing block comments completely outside the selection. + // Positions of the last startString before the start of the selection, and the first endString after it. + var lastStart = startLine.lastIndexOf(startString, from.ch); + var firstEnd = lastStart == -1 ? -1 : startLine.slice(0, from.ch).indexOf(endString, lastStart + startString.length); + if (lastStart != -1 && firstEnd != -1 && firstEnd + endString.length != from.ch) return false; + // Positions of the first endString after the end of the selection, and the last startString before it. + firstEnd = endLine.indexOf(endString, to.ch); + var almostLastStart = endLine.slice(to.ch).lastIndexOf(startString, firstEnd - to.ch); + lastStart = (firstEnd == -1 || almostLastStart == -1) ? -1 : to.ch + almostLastStart; + if (firstEnd != -1 && lastStart != -1 && lastStart != to.ch) return false; self.operation(function() { self.replaceRange("", Pos(end, close - (pad && endLine.slice(close - pad.length, close) == pad ? pad.length : 0)), @@ -142,4 +203,4 @@ }); return true; }); -})(); +}); diff --git a/Source/WebInspectorUI/UserInterface/External/CodeMirror/css.js b/Source/WebInspectorUI/UserInterface/External/CodeMirror/css.js index d8c30cf33..a1d5a388e 100644 --- a/Source/WebInspectorUI/UserInterface/External/CodeMirror/css.js +++ b/Source/WebInspectorUI/UserInterface/External/CodeMirror/css.js @@ -1,308 +1,407 @@ -CodeMirror.defineMode("css", function(config, parserConfig) { - "use strict"; +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; +CodeMirror.defineMode("css", function(config, parserConfig) { + var inline = parserConfig.inline if (!parserConfig.propertyKeywords) parserConfig = CodeMirror.resolveMode("text/css"); - var indentUnit = config.indentUnit || config.tabSize || 2, - hooks = parserConfig.hooks || {}, - atMediaTypes = parserConfig.atMediaTypes || {}, - atMediaFeatures = parserConfig.atMediaFeatures || {}, + var indentUnit = config.indentUnit, + tokenHooks = parserConfig.tokenHooks, + documentTypes = parserConfig.documentTypes || {}, + mediaTypes = parserConfig.mediaTypes || {}, + mediaFeatures = parserConfig.mediaFeatures || {}, + mediaValueKeywords = parserConfig.mediaValueKeywords || {}, propertyKeywords = parserConfig.propertyKeywords || {}, + nonStandardPropertyKeywords = parserConfig.nonStandardPropertyKeywords || {}, + fontProperties = parserConfig.fontProperties || {}, + counterDescriptors = parserConfig.counterDescriptors || {}, colorKeywords = parserConfig.colorKeywords || {}, valueKeywords = parserConfig.valueKeywords || {}, - allowNested = !!parserConfig.allowNested, - type = null; + allowNested = parserConfig.allowNested, + supportsAtComponent = parserConfig.supportsAtComponent === true; + var type, override; function ret(style, tp) { type = tp; return style; } + // Tokenizers + function tokenBase(stream, state) { var ch = stream.next(); - if (hooks[ch]) { - // result[0] is style and result[1] is type - var result = hooks[ch](stream, state); + if (tokenHooks[ch]) { + var result = tokenHooks[ch](stream, state); if (result !== false) return result; } - if (ch == "@") {stream.eatWhile(/[\w\\\-]/); return ret("def", stream.current());} - else if (ch == "=") ret(null, "compare"); - else if ((ch == "~" || ch == "|") && stream.eat("=")) return ret(null, "compare"); - else if (ch == "\"" || ch == "'") { + if (ch == "@") { + stream.eatWhile(/[\w\\\-]/); + return ret("def", stream.current()); + } else if (ch == "=" || (ch == "~" || ch == "|") && stream.eat("=")) { + return ret(null, "compare"); + } else if (ch == "\"" || ch == "'") { state.tokenize = tokenString(ch); return state.tokenize(stream, state); - } - else if (ch == "#") { + } else if (ch == "#") { stream.eatWhile(/[\w\\\-]/); return ret("atom", "hash"); - } - else if (ch == "!") { + } else if (ch == "!") { stream.match(/^\s*\w*/); return ret("keyword", "important"); - } - else if (/\d/.test(ch) || ch == "." && stream.eat(/\d/)) { + } else if (/\d/.test(ch) || ch == "." && stream.eat(/\d/)) { stream.eatWhile(/[\w.%]/); return ret("number", "unit"); - } - else if (ch === "-") { - if (/\d/.test(stream.peek())) { + } else if (ch === "-") { + if (/[\d.]/.test(stream.peek())) { stream.eatWhile(/[\w.%]/); return ret("number", "unit"); - } else if (stream.match(/^[^-]+-/)) { + } else if (stream.match(/^-[\w\\\-]+/)) { + stream.eatWhile(/[\w\\\-]/); + if (stream.match(/^\s*:/, false)) + return ret("variable-2", "variable-definition"); + return ret("variable-2", "variable"); + } else if (stream.match(/^\w+-/)) { return ret("meta", "meta"); } - } - else if (/[,+>*\/]/.test(ch)) { + } else if (/[,+>*\/]/.test(ch)) { return ret(null, "select-op"); - } - else if (ch == "." && stream.match(/^-?[_a-z][_a-z0-9-]*/i)) { + } else if (ch == "." && stream.match(/^-?[_a-z][_a-z0-9-]*/i)) { return ret("qualifier", "qualifier"); - } - else if (ch == ":") { - return ret("operator", ch); - } - else if (/[;{}\[\]\(\)]/.test(ch)) { + } else if (/[:;{}\[\]\(\)]/.test(ch)) { return ret(null, ch); - } - else if (ch == "u" && stream.match("rl(")) { + } else if ((ch == "u" && stream.match(/rl(-prefix)?\(/)) || + (ch == "d" && stream.match("omain(")) || + (ch == "r" && stream.match("egexp("))) { stream.backUp(1); state.tokenize = tokenParenthesized; - return ret("property", "variable"); - } - else { + return ret("property", "word"); + } else if (/[\w\\\-]/.test(ch)) { stream.eatWhile(/[\w\\\-]/); - return ret("property", "variable"); + return ret("property", "word"); + } else { + return ret(null, null); } } - function tokenString(quote, nonInclusive) { + function tokenString(quote) { return function(stream, state) { var escaped = false, ch; while ((ch = stream.next()) != null) { - if (ch == quote && !escaped) + if (ch == quote && !escaped) { + if (quote == ")") stream.backUp(1); break; + } escaped = !escaped && ch == "\\"; } - if (!escaped) { - if (nonInclusive) stream.backUp(1); - state.tokenize = tokenBase; - } + if (ch == quote || !escaped && quote != ")") state.tokenize = null; return ret("string", "string"); }; } function tokenParenthesized(stream, state) { stream.next(); // Must be '(' - if (!stream.match(/\s*[\"\']/, false)) - state.tokenize = tokenString(")", true); + if (!stream.match(/\s*[\"\')]/, false)) + state.tokenize = tokenString(")"); else - state.tokenize = tokenBase; + state.tokenize = null; return ret(null, "("); } + // Context management + + function Context(type, indent, prev) { + this.type = type; + this.indent = indent; + this.prev = prev; + } + + function pushContext(state, stream, type, indent) { + state.context = new Context(type, stream.indentation() + (indent === false ? 0 : indentUnit), state.context); + return type; + } + + function popContext(state) { + if (state.context.prev) + state.context = state.context.prev; + return state.context.type; + } + + function pass(type, stream, state) { + return states[state.context.type](type, stream, state); + } + function popAndPass(type, stream, state, n) { + for (var i = n || 1; i > 0; i--) + state.context = state.context.prev; + return pass(type, stream, state); + } + + // Parser + + function wordAsValue(stream) { + var word = stream.current().toLowerCase(); + if (valueKeywords.hasOwnProperty(word)) + override = "atom"; + else if (colorKeywords.hasOwnProperty(word)) + override = "keyword"; + else + override = "variable"; + } + + var states = {}; + + states.top = function(type, stream, state) { + if (type == "{") { + return pushContext(state, stream, "block"); + } else if (type == "}" && state.context.prev) { + return popContext(state); + } else if (supportsAtComponent && /@component/.test(type)) { + return pushContext(state, stream, "atComponentBlock"); + } else if (/^@(-moz-)?document$/.test(type)) { + return pushContext(state, stream, "documentTypes"); + } else if (/^@(media|supports|(-moz-)?document|import)$/.test(type)) { + return pushContext(state, stream, "atBlock"); + } else if (/^@(font-face|counter-style)/.test(type)) { + state.stateArg = type; + return "restricted_atBlock_before"; + } else if (/^@(-(moz|ms|o|webkit)-)?keyframes$/.test(type)) { + return "keyframes"; + } else if (type && type.charAt(0) == "@") { + return pushContext(state, stream, "at"); + } else if (type == "hash") { + override = "builtin"; + } else if (type == "word") { + override = "tag"; + } else if (type == "variable-definition") { + return "maybeprop"; + } else if (type == "interpolation") { + return pushContext(state, stream, "interpolation"); + } else if (type == ":") { + return "pseudo"; + } else if (allowNested && type == "(") { + return pushContext(state, stream, "parens"); + } + return state.context.type; + }; + + states.block = function(type, stream, state) { + if (type == "word") { + var word = stream.current().toLowerCase(); + if (propertyKeywords.hasOwnProperty(word)) { + override = "property"; + return "maybeprop"; + } else if (nonStandardPropertyKeywords.hasOwnProperty(word)) { + override = "string-2"; + return "maybeprop"; + } else if (allowNested) { + override = stream.match(/^\s*:(?:\s|$)/, false) ? "property" : "tag"; + return "block"; + } else { + override += " error"; + return "maybeprop"; + } + } else if (type == "meta") { + return "block"; + } else if (!allowNested && (type == "hash" || type == "qualifier")) { + override = "error"; + return "block"; + } else { + return states.top(type, stream, state); + } + }; + + states.maybeprop = function(type, stream, state) { + if (type == ":") return pushContext(state, stream, "prop"); + return pass(type, stream, state); + }; + + states.prop = function(type, stream, state) { + if (type == ";") return popContext(state); + if (type == "{" && allowNested) return pushContext(state, stream, "propBlock"); + if (type == "}" || type == "{") return popAndPass(type, stream, state); + if (type == "(") return pushContext(state, stream, "parens"); + + if (type == "hash" && !/^#([0-9a-fA-f]{3,4}|[0-9a-fA-f]{6}|[0-9a-fA-f]{8})$/.test(stream.current())) { + override += " error"; + } else if (type == "word") { + wordAsValue(stream); + } else if (type == "interpolation") { + return pushContext(state, stream, "interpolation"); + } + return "prop"; + }; + + states.propBlock = function(type, _stream, state) { + if (type == "}") return popContext(state); + if (type == "word") { override = "property"; return "maybeprop"; } + return state.context.type; + }; + + states.parens = function(type, stream, state) { + if (type == "{" || type == "}") return popAndPass(type, stream, state); + if (type == ")") return popContext(state); + if (type == "(") return pushContext(state, stream, "parens"); + if (type == "interpolation") return pushContext(state, stream, "interpolation"); + if (type == "word") wordAsValue(stream); + return "parens"; + }; + + states.pseudo = function(type, stream, state) { + if (type == "word") { + override = "variable-3"; + return state.context.type; + } + return pass(type, stream, state); + }; + + states.documentTypes = function(type, stream, state) { + if (type == "word" && documentTypes.hasOwnProperty(stream.current())) { + override = "tag"; + return state.context.type; + } else { + return states.atBlock(type, stream, state); + } + }; + + states.atBlock = function(type, stream, state) { + if (type == "(") return pushContext(state, stream, "atBlock_parens"); + if (type == "}" || type == ";") return popAndPass(type, stream, state); + if (type == "{") return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top"); + + if (type == "interpolation") return pushContext(state, stream, "interpolation"); + + if (type == "word") { + var word = stream.current().toLowerCase(); + if (word == "only" || word == "not" || word == "and" || word == "or") + override = "keyword"; + else if (mediaTypes.hasOwnProperty(word)) + override = "attribute"; + else if (mediaFeatures.hasOwnProperty(word)) + override = "property"; + else if (mediaValueKeywords.hasOwnProperty(word)) + override = "keyword"; + else if (propertyKeywords.hasOwnProperty(word)) + override = "property"; + else if (nonStandardPropertyKeywords.hasOwnProperty(word)) + override = "string-2"; + else if (valueKeywords.hasOwnProperty(word)) + override = "atom"; + else if (colorKeywords.hasOwnProperty(word)) + override = "keyword"; + else + override = "error"; + } + return state.context.type; + }; + + states.atComponentBlock = function(type, stream, state) { + if (type == "}") + return popAndPass(type, stream, state); + if (type == "{") + return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top", false); + if (type == "word") + override = "error"; + return state.context.type; + }; + + states.atBlock_parens = function(type, stream, state) { + if (type == ")") return popContext(state); + if (type == "{" || type == "}") return popAndPass(type, stream, state, 2); + return states.atBlock(type, stream, state); + }; + + states.restricted_atBlock_before = function(type, stream, state) { + if (type == "{") + return pushContext(state, stream, "restricted_atBlock"); + if (type == "word" && state.stateArg == "@counter-style") { + override = "variable"; + return "restricted_atBlock_before"; + } + return pass(type, stream, state); + }; + + states.restricted_atBlock = function(type, stream, state) { + if (type == "}") { + state.stateArg = null; + return popContext(state); + } + if (type == "word") { + if ((state.stateArg == "@font-face" && !fontProperties.hasOwnProperty(stream.current().toLowerCase())) || + (state.stateArg == "@counter-style" && !counterDescriptors.hasOwnProperty(stream.current().toLowerCase()))) + override = "error"; + else + override = "property"; + return "maybeprop"; + } + return "restricted_atBlock"; + }; + + states.keyframes = function(type, stream, state) { + if (type == "word") { override = "variable"; return "keyframes"; } + if (type == "{") return pushContext(state, stream, "top"); + return pass(type, stream, state); + }; + + states.at = function(type, stream, state) { + if (type == ";") return popContext(state); + if (type == "{" || type == "}") return popAndPass(type, stream, state); + if (type == "word") override = "tag"; + else if (type == "hash") override = "builtin"; + return "at"; + }; + + states.interpolation = function(type, stream, state) { + if (type == "}") return popContext(state); + if (type == "{" || type == ";") return popAndPass(type, stream, state); + if (type == "word") override = "variable"; + else if (type != "variable" && type != "(" && type != ")") override = "error"; + return "interpolation"; + }; + return { startState: function(base) { - return {tokenize: tokenBase, - baseIndent: base || 0, - stack: [], - lastToken: null}; + return {tokenize: null, + state: inline ? "block" : "top", + stateArg: null, + context: new Context(inline ? "block" : "top", base || 0, null)}; }, token: function(stream, state) { - - // Use these terms when applicable (see http://www.xanthir.com/blog/b4E50) - // - // rule** or **ruleset: - // A selector + braces combo, or an at-rule. - // - // declaration block: - // A sequence of declarations. - // - // declaration: - // A property + colon + value combo. - // - // property value: - // The entire value of a property. - // - // component value: - // A single piece of a property value. Like the 5px in - // text-shadow: 0 0 5px blue;. Can also refer to things that are - // multiple terms, like the 1-4 terms that make up the background-size - // portion of the background shorthand. - // - // term: - // The basic unit of author-facing CSS, like a single number (5), - // dimension (5px), string ("foo"), or function. Officially defined - // by the CSS 2.1 grammar (look for the 'term' production) - // - // - // simple selector: - // A single atomic selector, like a type selector, an attr selector, a - // class selector, etc. - // - // compound selector: - // One or more simple selectors without a combinator. div.example is - // compound, div > .example is not. - // - // complex selector: - // One or more compound selectors chained with combinators. - // - // combinator: - // The parts of selectors that express relationships. There are four - // currently - the space (descendant combinator), the greater-than - // bracket (child combinator), the plus sign (next sibling combinator), - // and the tilda (following sibling combinator). - // - // sequence of selectors: - // One or more of the named type of selector chained with commas. - - state.tokenize = state.tokenize || tokenBase; - if (state.tokenize == tokenBase && stream.eatSpace()) return null; - var style = state.tokenize(stream, state); - if (style && typeof style != "string") style = ret(style[0], style[1]); - - // Changing style returned based on context - var context = state.stack[state.stack.length-1]; - if (style == "variable") { - if (type == "variable-definition") state.stack.push("propertyValue"); - return state.lastToken = "variable-2"; - } else if (style == "property") { - var word = stream.current().toLowerCase(); - if (context == "propertyValue") { - if (valueKeywords.hasOwnProperty(word)) { - style = "string-2"; - } else if (colorKeywords.hasOwnProperty(word)) { - style = "keyword"; - } else { - style = "variable-2"; - } - } else if (context == "rule") { - if (!propertyKeywords.hasOwnProperty(word)) { - style += " error"; - } - } else if (context == "block") { - // if a value is present in both property, value, or color, the order - // of preference is property -> color -> value - if (propertyKeywords.hasOwnProperty(word)) { - style = "property"; - } else if (colorKeywords.hasOwnProperty(word)) { - style = "keyword"; - } else if (valueKeywords.hasOwnProperty(word)) { - style = "string-2"; - } else { - style = "tag"; - } - } else if (!context || context == "@media{") { - style = "tag"; - } else if (context == "@media") { - if (atMediaTypes[stream.current()]) { - style = "attribute"; // Known attribute - } else if (/^(only|not)$/.test(word)) { - style = "keyword"; - } else if (word == "and") { - style = "error"; // "and" is only allowed in @mediaType - } else if (atMediaFeatures.hasOwnProperty(word)) { - style = "error"; // Known property, should be in @mediaType( - } else { - // Unknown, expecting keyword or attribute, assuming attribute - style = "attribute error"; - } - } else if (context == "@mediaType") { - if (atMediaTypes.hasOwnProperty(word)) { - style = "attribute"; - } else if (word == "and") { - style = "operator"; - } else if (/^(only|not)$/.test(word)) { - style = "error"; // Only allowed in @media - } else { - // Unknown attribute or property, but expecting property (preceded - // by "and"). Should be in parentheses - style = "error"; - } - } else if (context == "@mediaType(") { - if (propertyKeywords.hasOwnProperty(word)) { - // do nothing, remains "property" - } else if (atMediaTypes.hasOwnProperty(word)) { - style = "error"; // Known property, should be in parentheses - } else if (word == "and") { - style = "operator"; - } else if (/^(only|not)$/.test(word)) { - style = "error"; // Only allowed in @media - } else { - style += " error"; - } - } else if (context == "@import") { - style = "tag"; - } else { - style = "error"; - } - } else if (style == "atom") { - if(!context || context == "@media{" || context == "block") { - style = "builtin"; - } else if (context == "propertyValue") { - if (!/^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/.test(stream.current())) { - style += " error"; - } - } else { - style = "error"; - } - } else if (context == "@media" && type == "{") { - style = "error"; + if (!state.tokenize && stream.eatSpace()) return null; + var style = (state.tokenize || tokenBase)(stream, state); + if (style && typeof style == "object") { + type = style[1]; + style = style[0]; } - - // Push/pop context stack - if (type == "{") { - if (context == "@media" || context == "@mediaType") { - state.stack[state.stack.length-1] = "@media{"; - } - else { - var newContext = allowNested ? "block" : "rule"; - state.stack.push(newContext); - } - } - else if (type == "}") { - if (context == "interpolation") style = "operator"; - // Pop off end of array until { is reached - while(state.stack.length){ - var removed = state.stack.pop(); - if(removed.indexOf("{") > -1 || removed == "block" || removed == "rule"){ - break; - } - } - } - else if (type == "interpolation") state.stack.push("interpolation"); - else if (type == "@media") state.stack.push("@media"); - else if (type == "@import") state.stack.push("@import"); - else if (context == "@media" && /\b(keyword|attribute)\b/.test(style)) - state.stack[state.stack.length-1] = "@mediaType"; - else if (context == "@mediaType" && stream.current() == ",") - state.stack[state.stack.length-1] = "@media"; - else if (type == "(") { - if (context == "@media" || context == "@mediaType") { - // Make sure @mediaType is used to avoid error on { - state.stack[state.stack.length-1] = "@mediaType"; - state.stack.push("@mediaType("); - } - else state.stack.push("("); - } - else if (type == ")") { - // Pop off end of array until ( is reached - while(state.stack.length){ - var removed = state.stack.pop(); - if(removed.indexOf("(") > -1){ - break; - } - } - } - else if (type == ":" && state.lastToken == "property") state.stack.push("propertyValue"); - else if (context == "propertyValue" && type == ";") state.stack.pop(); - else if (context == "@import" && type == ";") state.stack.pop(); - - return state.lastToken = style; + override = style; + state.state = states[state.state](type, stream, state); + return override; }, indent: function(state, textAfter) { - var n = state.stack.length; - if (/^\}/.test(textAfter)) - n -= state.stack[n-1] == "propertyValue" ? 2 : 1; - return state.baseIndent + n * indentUnit; + var cx = state.context, ch = textAfter && textAfter.charAt(0); + var indent = cx.indent; + if (cx.type == "prop" && (ch == "}" || ch == ")")) cx = cx.prev; + if (cx.prev) { + if (ch == "}" && (cx.type == "block" || cx.type == "top" || + cx.type == "interpolation" || cx.type == "restricted_atBlock")) { + // Resume indentation from parent context. + cx = cx.prev; + indent = cx.indent; + } else if (ch == ")" && (cx.type == "parens" || cx.type == "atBlock_parens") || + ch == "{" && (cx.type == "at" || cx.type == "atBlock")) { + // Dedent relative to current context. + indent = Math.max(0, cx.indent - indentUnit); + cx = cx.prev; + } + } + return indent; }, electricChars: "}", @@ -312,21 +411,24 @@ CodeMirror.defineMode("css", function(config, parserConfig) { }; }); -(function() { function keySet(array) { var keys = {}; for (var i = 0; i < array.length; ++i) { - keys[array[i]] = true; + keys[array[i].toLowerCase()] = true; } return keys; } - var atMediaTypes = keySet([ + var documentTypes_ = [ + "domain", "regexp", "url", "url-prefix" + ], documentTypes = keySet(documentTypes_); + + var mediaTypes_ = [ "all", "aural", "braille", "handheld", "print", "projection", "screen", "tty", "tv", "embossed" - ]); + ], mediaTypes = keySet(mediaTypes_); - var atMediaFeatures = keySet([ + var mediaFeatures_ = [ "width", "min-width", "max-width", "height", "min-height", "max-height", "device-width", "min-device-width", "max-device-width", "device-height", "min-device-height", "max-device-height", "aspect-ratio", @@ -334,17 +436,24 @@ CodeMirror.defineMode("css", function(config, parserConfig) { "min-device-aspect-ratio", "max-device-aspect-ratio", "color", "min-color", "max-color", "color-index", "min-color-index", "max-color-index", "monochrome", "min-monochrome", "max-monochrome", "resolution", - "min-resolution", "max-resolution", "scan", "grid" - ]); + "min-resolution", "max-resolution", "scan", "grid", "orientation", + "device-pixel-ratio", "min-device-pixel-ratio", "max-device-pixel-ratio", + "pointer", "any-pointer", "hover", "any-hover" + ], mediaFeatures = keySet(mediaFeatures_); - var propertyKeywords = keySet([ + var mediaValueKeywords_ = [ + "landscape", "portrait", "none", "coarse", "fine", "on-demand", "hover", + "interlace", "progressive" + ], mediaValueKeywords = keySet(mediaValueKeywords_); + + var propertyKeywords_ = [ "align-content", "align-items", "align-self", "alignment-adjust", "alignment-baseline", "anchor-point", "animation", "animation-delay", - "animation-direction", "animation-duration", "animation-iteration-count", - "animation-name", "animation-play-state", "animation-timing-function", - "appearance", "azimuth", "backface-visibility", "background", - "background-attachment", "background-clip", "background-color", - "background-image", "background-origin", "background-position", + "animation-direction", "animation-duration", "animation-fill-mode", + "animation-iteration-count", "animation-name", "animation-play-state", + "animation-timing-function", "appearance", "azimuth", "backface-visibility", + "background", "background-attachment", "background-blend-mode", "background-clip", + "background-color", "background-image", "background-origin", "background-position", "background-repeat", "background-size", "baseline-shift", "binding", "bleed", "bookmark-label", "bookmark-level", "bookmark-state", "bookmark-target", "border", "border-bottom", "border-bottom-color", @@ -374,20 +483,22 @@ CodeMirror.defineMode("css", function(config, parserConfig) { "font-stretch", "font-style", "font-synthesis", "font-variant", "font-variant-alternates", "font-variant-caps", "font-variant-east-asian", "font-variant-ligatures", "font-variant-numeric", "font-variant-position", - "font-weight", "grid-cell", "grid-column", "grid-column-align", - "grid-column-sizing", "grid-column-span", "grid-columns", "grid-flow", - "grid-row", "grid-row-align", "grid-row-sizing", "grid-row-span", - "grid-rows", "grid-template", "hanging-punctuation", "height", "hyphens", + "font-weight", "grid", "grid-area", "grid-auto-columns", "grid-auto-flow", + "grid-auto-rows", "grid-column", "grid-column-end", "grid-column-gap", + "grid-column-start", "grid-gap", "grid-row", "grid-row-end", "grid-row-gap", + "grid-row-start", "grid-template", "grid-template-areas", "grid-template-columns", + "grid-template-rows", "hanging-punctuation", "height", "hyphens", "icon", "image-orientation", "image-rendering", "image-resolution", "inline-box-align", "justify-content", "left", "letter-spacing", "line-break", "line-height", "line-stacking", "line-stacking-ruby", "line-stacking-shift", "line-stacking-strategy", "list-style", "list-style-image", "list-style-position", "list-style-type", "margin", "margin-bottom", "margin-left", "margin-right", "margin-top", - "marker-offset", "marks", "marquee-direction", "marquee-loop", + "marks", "marquee-direction", "marquee-loop", "marquee-play-count", "marquee-speed", "marquee-style", "max-height", "max-width", "min-height", "min-width", "move-to", "nav-down", "nav-index", - "nav-left", "nav-right", "nav-up", "opacity", "order", "orphans", "outline", + "nav-left", "nav-right", "nav-up", "object-fit", "object-position", + "opacity", "order", "orphans", "outline", "outline-color", "outline-offset", "outline-style", "outline-width", "overflow", "overflow-style", "overflow-wrap", "overflow-x", "overflow-y", "padding", "padding-bottom", "padding-left", "padding-right", "padding-top", @@ -398,8 +509,8 @@ CodeMirror.defineMode("css", function(config, parserConfig) { "region-break-before", "region-break-inside", "region-fragment", "rendering-intent", "resize", "rest", "rest-after", "rest-before", "richness", "right", "rotation", "rotation-point", "ruby-align", "ruby-overhang", - "ruby-position", "ruby-span", "shape-inside", "shape-outside", "size", - "speak", "speak-as", "speak-header", + "ruby-position", "ruby-span", "shape-image-threshold", "shape-inside", "shape-margin", + "shape-outside", "size", "speak", "speak-as", "speak-header", "speak-numeral", "speak-punctuation", "speech-rate", "stress", "string-set", "tab-size", "table-layout", "target", "target-name", "target-new", "target-position", "text-align", "text-align-last", "text-decoration", @@ -411,23 +522,41 @@ CodeMirror.defineMode("css", function(config, parserConfig) { "text-wrap", "top", "transform", "transform-origin", "transform-style", "transition", "transition-delay", "transition-duration", "transition-property", "transition-timing-function", "unicode-bidi", - "vertical-align", "visibility", "voice-balance", "voice-duration", + "user-select", "vertical-align", "visibility", "voice-balance", "voice-duration", "voice-family", "voice-pitch", "voice-range", "voice-rate", "voice-stress", - "voice-volume", "volume", "white-space", "widows", "width", "word-break", - "word-spacing", "word-wrap", "z-index", "zoom", + "voice-volume", "volume", "white-space", "widows", "width", "will-change", "word-break", + "word-spacing", "word-wrap", "z-index", // SVG-specific "clip-path", "clip-rule", "mask", "enable-background", "filter", "flood-color", "flood-opacity", "lighting-color", "stop-color", "stop-opacity", "pointer-events", - "color-interpolation", "color-interpolation-filters", "color-profile", + "color-interpolation", "color-interpolation-filters", "color-rendering", "fill", "fill-opacity", "fill-rule", "image-rendering", "marker", "marker-end", "marker-mid", "marker-start", "shape-rendering", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "text-rendering", "baseline-shift", "dominant-baseline", "glyph-orientation-horizontal", - "glyph-orientation-vertical", "kerning", "text-anchor", "writing-mode" - ]); + "glyph-orientation-vertical", "text-anchor", "writing-mode" + ], propertyKeywords = keySet(propertyKeywords_); + + var nonStandardPropertyKeywords_ = [ + "scrollbar-arrow-color", "scrollbar-base-color", "scrollbar-dark-shadow-color", + "scrollbar-face-color", "scrollbar-highlight-color", "scrollbar-shadow-color", + "scrollbar-3d-light-color", "scrollbar-track-color", "shape-inside", + "searchfield-cancel-button", "searchfield-decoration", "searchfield-results-button", + "searchfield-results-decoration", "zoom" + ], nonStandardPropertyKeywords = keySet(nonStandardPropertyKeywords_); - var colorKeywords = keySet([ + var fontProperties_ = [ + "font-family", "src", "unicode-range", "font-variant", "font-feature-settings", + "font-stretch", "font-weight", "font-style" + ], fontProperties = keySet(fontProperties_); + + var counterDescriptors_ = [ + "additive-symbols", "fallback", "negative", "pad", "prefix", "range", + "speak-as", "suffix", "symbols", "system" + ], counterDescriptors = keySet(counterDescriptors_); + + var colorKeywords_ = [ "aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige", "bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown", "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue", @@ -449,54 +578,58 @@ CodeMirror.defineMode("css", function(config, parserConfig) { "navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered", "orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred", "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue", - "purple", "red", "rosybrown", "royalblue", "saddlebrown", "salmon", - "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue", + "purple", "rebeccapurple", "red", "rosybrown", "royalblue", "saddlebrown", + "salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue", "slateblue", "slategray", "snow", "springgreen", "steelblue", "tan", "teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white", "whitesmoke", "yellow", "yellowgreen" - ]); + ], colorKeywords = keySet(colorKeywords_); - var valueKeywords = keySet([ - "above", "absolute", "activeborder", "activecaption", "afar", - "after-white-space", "ahead", "alias", "all", "all-scroll", "alternate", + var valueKeywords_ = [ + "above", "absolute", "activeborder", "additive", "activecaption", "afar", + "after-white-space", "ahead", "alias", "all", "all-scroll", "alphabetic", "alternate", "always", "amharic", "amharic-abegede", "antialiased", "appworkspace", - "arabic-indic", "armenian", "asterisks", "auto", "avoid", "avoid-column", "avoid-page", + "arabic-indic", "armenian", "asterisks", "attr", "auto", "avoid", "avoid-column", "avoid-page", "avoid-region", "background", "backwards", "baseline", "below", "bidi-override", "binary", "bengali", "blink", "block", "block-axis", "bold", "bolder", "border", "border-box", - "both", "bottom", "break", "break-all", "break-word", "button", "button-bevel", - "buttonface", "buttonhighlight", "buttonshadow", "buttontext", "cambodian", + "both", "bottom", "break", "break-all", "break-word", "bullets", "button", "button-bevel", + "buttonface", "buttonhighlight", "buttonshadow", "buttontext", "calc", "cambodian", "capitalize", "caps-lock-indicator", "caption", "captiontext", "caret", - "cell", "center", "checkbox", "circle", "cjk-earthly-branch", + "cell", "center", "checkbox", "circle", "cjk-decimal", "cjk-earthly-branch", "cjk-heavenly-stem", "cjk-ideographic", "clear", "clip", "close-quote", - "col-resize", "collapse", "column", "compact", "condensed", "contain", "content", - "content-box", "context-menu", "continuous", "copy", "cover", "crop", - "cross", "crosshair", "currentcolor", "cursive", "dashed", "decimal", - "decimal-leading-zero", "default", "default-button", "destination-atop", - "destination-in", "destination-out", "destination-over", "devanagari", - "disc", "discard", "document", "dot-dash", "dot-dot-dash", "dotted", - "double", "down", "e-resize", "ease", "ease-in", "ease-in-out", "ease-out", + "col-resize", "collapse", "color", "color-burn", "color-dodge", "column", "column-reverse", + "compact", "condensed", "contain", "content", "contents", + "content-box", "context-menu", "continuous", "copy", "counter", "counters", "cover", "crop", + "cross", "crosshair", "currentcolor", "cursive", "cyclic", "darken", "dashed", "decimal", + "decimal-leading-zero", "default", "default-button", "dense", "destination-atop", + "destination-in", "destination-out", "destination-over", "devanagari", "difference", + "disc", "discard", "disclosure-closed", "disclosure-open", "document", + "dot-dash", "dot-dot-dash", + "dotted", "double", "down", "e-resize", "ease", "ease-in", "ease-in-out", "ease-out", "element", "ellipse", "ellipsis", "embed", "end", "ethiopic", "ethiopic-abegede", "ethiopic-abegede-am-et", "ethiopic-abegede-gez", "ethiopic-abegede-ti-er", "ethiopic-abegede-ti-et", "ethiopic-halehame-aa-er", "ethiopic-halehame-aa-et", "ethiopic-halehame-am-et", "ethiopic-halehame-gez", "ethiopic-halehame-om-et", "ethiopic-halehame-sid-et", "ethiopic-halehame-so-et", - "ethiopic-halehame-ti-er", "ethiopic-halehame-ti-et", - "ethiopic-halehame-tig", "ew-resize", "expanded", "extra-condensed", - "extra-expanded", "fantasy", "fast", "fill", "fixed", "flat", "footnotes", - "forwards", "from", "geometricPrecision", "georgian", "graytext", "groove", - "gujarati", "gurmukhi", "hand", "hangul", "hangul-consonant", "hebrew", + "ethiopic-halehame-ti-er", "ethiopic-halehame-ti-et", "ethiopic-halehame-tig", + "ethiopic-numeric", "ew-resize", "exclusion", "expanded", "extends", "extra-condensed", + "extra-expanded", "fantasy", "fast", "fill", "fixed", "flat", "flex", "flex-end", "flex-start", "footnotes", + "forwards", "from", "geometricPrecision", "georgian", "graytext", "grid", "groove", + "gujarati", "gurmukhi", "hand", "hangul", "hangul-consonant", "hard-light", "hebrew", "help", "hidden", "hide", "higher", "highlight", "highlighttext", - "hiragana", "hiragana-iroha", "horizontal", "hsl", "hsla", "icon", "ignore", + "hiragana", "hiragana-iroha", "horizontal", "hsl", "hsla", "hue", "icon", "ignore", "inactiveborder", "inactivecaption", "inactivecaptiontext", "infinite", "infobackground", "infotext", "inherit", "initial", "inline", "inline-axis", - "inline-block", "inline-table", "inset", "inside", "intrinsic", "invert", - "italic", "justify", "kannada", "katakana", "katakana-iroha", "keep-all", "khmer", - "landscape", "lao", "large", "larger", "left", "level", "lighter", - "line-through", "linear", "lines", "list-item", "listbox", "listitem", + "inline-block", "inline-flex", "inline-grid", "inline-table", "inset", "inside", "intrinsic", "invert", + "italic", "japanese-formal", "japanese-informal", "justify", "kannada", + "katakana", "katakana-iroha", "keep-all", "khmer", + "korean-hangul-formal", "korean-hanja-formal", "korean-hanja-informal", + "landscape", "lao", "large", "larger", "left", "level", "lighter", "lighten", + "line-through", "linear", "linear-gradient", "lines", "list-item", "listbox", "listitem", "local", "logical", "loud", "lower", "lower-alpha", "lower-armenian", "lower-greek", "lower-hexadecimal", "lower-latin", "lower-norwegian", - "lower-roman", "lowercase", "ltr", "malayalam", "match", + "lower-roman", "lowercase", "ltr", "luminosity", "malayalam", "match", "matrix", "matrix3d", "media-controls-background", "media-current-time-display", "media-fullscreen-button", "media-mute-button", "media-play-button", "media-return-to-realtime-button", "media-rewind-button", @@ -505,41 +638,54 @@ CodeMirror.defineMode("css", function(config, parserConfig) { "media-volume-slider-container", "media-volume-sliderthumb", "medium", "menu", "menulist", "menulist-button", "menulist-text", "menulist-textfield", "menutext", "message-box", "middle", "min-intrinsic", - "mix", "mongolian", "monospace", "move", "multiple", "myanmar", "n-resize", + "mix", "mongolian", "monospace", "move", "multiple", "multiply", "myanmar", "n-resize", "narrower", "ne-resize", "nesw-resize", "no-close-quote", "no-drop", "no-open-quote", "no-repeat", "none", "normal", "not-allowed", "nowrap", - "ns-resize", "nw-resize", "nwse-resize", "oblique", "octal", "open-quote", + "ns-resize", "numbers", "numeric", "nw-resize", "nwse-resize", "oblique", "octal", "opacity", "open-quote", "optimizeLegibility", "optimizeSpeed", "oriya", "oromo", "outset", "outside", "outside-shape", "overlay", "overline", "padding", "padding-box", - "painted", "page", "paused", "persian", "plus-darker", "plus-lighter", "pointer", - "polygon", "portrait", "pre", "pre-line", "pre-wrap", "preserve-3d", "progress", "push-button", - "radio", "read-only", "read-write", "read-write-plaintext-only", "rectangle", "region", - "relative", "repeat", "repeat-x", "repeat-y", "reset", "reverse", "rgb", "rgba", - "ridge", "right", "round", "row-resize", "rtl", "run-in", "running", - "s-resize", "sans-serif", "scroll", "scrollbar", "se-resize", "searchfield", + "painted", "page", "paused", "persian", "perspective", "plus-darker", "plus-lighter", + "pointer", "polygon", "portrait", "pre", "pre-line", "pre-wrap", "preserve-3d", + "progress", "push-button", "radial-gradient", "radio", "read-only", + "read-write", "read-write-plaintext-only", "rectangle", "region", + "relative", "repeat", "repeating-linear-gradient", + "repeating-radial-gradient", "repeat-x", "repeat-y", "reset", "reverse", + "rgb", "rgba", "ridge", "right", "rotate", "rotate3d", "rotateX", "rotateY", + "rotateZ", "round", "row", "row-resize", "row-reverse", "rtl", "run-in", "running", + "s-resize", "sans-serif", "saturation", "scale", "scale3d", "scaleX", "scaleY", "scaleZ", "screen", + "scroll", "scrollbar", "scroll-position", "se-resize", "searchfield", "searchfield-cancel-button", "searchfield-decoration", "searchfield-results-button", "searchfield-results-decoration", "semi-condensed", "semi-expanded", "separate", "serif", "show", "sidama", - "single", "skip-white-space", "slide", "slider-horizontal", + "simp-chinese-formal", "simp-chinese-informal", "single", + "skew", "skewX", "skewY", "skip-white-space", "slide", "slider-horizontal", "slider-vertical", "sliderthumb-horizontal", "sliderthumb-vertical", "slow", - "small", "small-caps", "small-caption", "smaller", "solid", "somali", - "source-atop", "source-in", "source-out", "source-over", "space", "square", - "square-button", "start", "static", "status-bar", "stretch", "stroke", - "sub", "subpixel-antialiased", "super", "sw-resize", "table", + "small", "small-caps", "small-caption", "smaller", "soft-light", "solid", "somali", + "source-atop", "source-in", "source-out", "source-over", "space", "space-around", "space-between", "spell-out", "square", + "square-button", "start", "static", "status-bar", "stretch", "stroke", "sub", + "subpixel-antialiased", "super", "sw-resize", "symbolic", "symbols", "table", "table-caption", "table-cell", "table-column", "table-column-group", "table-footer-group", "table-header-group", "table-row", "table-row-group", + "tamil", "telugu", "text", "text-bottom", "text-top", "textarea", "textfield", "thai", "thick", "thin", "threeddarkshadow", "threedface", "threedhighlight", "threedlightshadow", "threedshadow", "tibetan", "tigre", "tigrinya-er", "tigrinya-er-abegede", "tigrinya-et", "tigrinya-et-abegede", "to", "top", - "transparent", "ultra-condensed", "ultra-expanded", "underline", "up", + "trad-chinese-formal", "trad-chinese-informal", "transform", + "translate", "translate3d", "translateX", "translateY", "translateZ", + "transparent", "ultra-condensed", "ultra-expanded", "underline", "unset", "up", "upper-alpha", "upper-armenian", "upper-greek", "upper-hexadecimal", "upper-latin", "upper-norwegian", "upper-roman", "uppercase", "urdu", "url", - "vertical", "vertical-text", "visible", "visibleFill", "visiblePainted", + "var", "vertical", "vertical-text", "visible", "visibleFill", "visiblePainted", "visibleStroke", "visual", "w-resize", "wait", "wave", "wider", - "window", "windowframe", "windowtext", "x-large", "x-small", "xor", + "window", "windowframe", "windowtext", "words", "wrap", "wrap-reverse", "x-large", "x-small", "xor", "xx-large", "xx-small" - ]); + ], valueKeywords = keySet(valueKeywords_); + + var allWords = documentTypes_.concat(mediaTypes_).concat(mediaFeatures_).concat(mediaValueKeywords_) + .concat(propertyKeywords_).concat(nonStandardPropertyKeywords_).concat(colorKeywords_) + .concat(valueKeywords_); + CodeMirror.registerHelper("hintWords", "css", allWords); function tokenCComment(stream, state) { var maybeEnd = false, ch; @@ -554,66 +700,79 @@ CodeMirror.defineMode("css", function(config, parserConfig) { } CodeMirror.defineMIME("text/css", { - atMediaTypes: atMediaTypes, - atMediaFeatures: atMediaFeatures, + documentTypes: documentTypes, + mediaTypes: mediaTypes, + mediaFeatures: mediaFeatures, + mediaValueKeywords: mediaValueKeywords, propertyKeywords: propertyKeywords, + nonStandardPropertyKeywords: nonStandardPropertyKeywords, + fontProperties: fontProperties, + counterDescriptors: counterDescriptors, colorKeywords: colorKeywords, valueKeywords: valueKeywords, - hooks: { - "<": function(stream, state) { - function tokenSGMLComment(stream, state) { - var dashes = 0, ch; - while ((ch = stream.next()) != null) { - if (dashes >= 2 && ch == ">") { - state.tokenize = null; - break; - } - dashes = (ch == "-") ? dashes + 1 : 0; - } - return ["comment", "comment"]; - } - if (stream.eat("!")) { - state.tokenize = tokenSGMLComment; - return tokenSGMLComment(stream, state); - } - }, + tokenHooks: { "/": function(stream, state) { - if (stream.eat("*")) { - state.tokenize = tokenCComment; - return tokenCComment(stream, state); - } - return false; + if (!stream.eat("*")) return false; + state.tokenize = tokenCComment; + return tokenCComment(stream, state); } }, name: "css" }); CodeMirror.defineMIME("text/x-scss", { - atMediaTypes: atMediaTypes, - atMediaFeatures: atMediaFeatures, + mediaTypes: mediaTypes, + mediaFeatures: mediaFeatures, + mediaValueKeywords: mediaValueKeywords, propertyKeywords: propertyKeywords, + nonStandardPropertyKeywords: nonStandardPropertyKeywords, colorKeywords: colorKeywords, valueKeywords: valueKeywords, + fontProperties: fontProperties, allowNested: true, - hooks: { + tokenHooks: { + "/": function(stream, state) { + if (stream.eat("/")) { + stream.skipToEnd(); + return ["comment", "comment"]; + } else if (stream.eat("*")) { + state.tokenize = tokenCComment; + return tokenCComment(stream, state); + } else { + return ["operator", "operator"]; + } + }, ":": function(stream) { - if (stream.match(/\s*{/)) { + if (stream.match(/\s*\{/)) return [null, "{"]; - } return false; }, "$": function(stream) { stream.match(/^[\w-]+/); - if (stream.peek() == ":") { - return ["variable", "variable-definition"]; - } - return ["variable", "variable"]; - }, - ",": function(stream, state) { - if (state.stack[state.stack.length - 1] == "propertyValue" && stream.match(/^ *\$/, false)) { - return ["operator", ";"]; - } + if (stream.match(/^\s*:/, false)) + return ["variable-2", "variable-definition"]; + return ["variable-2", "variable"]; }, + "#": function(stream) { + if (!stream.eat("{")) return false; + return [null, "interpolation"]; + } + }, + name: "css", + helperType: "scss" + }); + + CodeMirror.defineMIME("text/x-less", { + mediaTypes: mediaTypes, + mediaFeatures: mediaFeatures, + mediaValueKeywords: mediaValueKeywords, + propertyKeywords: propertyKeywords, + nonStandardPropertyKeywords: nonStandardPropertyKeywords, + colorKeywords: colorKeywords, + valueKeywords: valueKeywords, + fontProperties: fontProperties, + allowNested: true, + tokenHooks: { "/": function(stream, state) { if (stream.eat("/")) { stream.skipToEnd(); @@ -625,15 +784,42 @@ CodeMirror.defineMode("css", function(config, parserConfig) { return ["operator", "operator"]; } }, - "#": function(stream) { - if (stream.eat("{")) { - return ["operator", "interpolation"]; - } else { - stream.eatWhile(/[\w\\\-]/); - return ["atom", "hash"]; - } + "@": function(stream) { + if (stream.eat("{")) return [null, "interpolation"]; + if (stream.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/, false)) return false; + stream.eatWhile(/[\w\\\-]/); + if (stream.match(/^\s*:/, false)) + return ["variable-2", "variable-definition"]; + return ["variable-2", "variable"]; + }, + "&": function() { + return ["atom", "atom"]; } }, - name: "css" + name: "css", + helperType: "less" + }); + + CodeMirror.defineMIME("text/x-gss", { + documentTypes: documentTypes, + mediaTypes: mediaTypes, + mediaFeatures: mediaFeatures, + propertyKeywords: propertyKeywords, + nonStandardPropertyKeywords: nonStandardPropertyKeywords, + fontProperties: fontProperties, + counterDescriptors: counterDescriptors, + colorKeywords: colorKeywords, + valueKeywords: valueKeywords, + supportsAtComponent: true, + tokenHooks: { + "/": function(stream, state) { + if (!stream.eat("*")) return false; + state.tokenize = tokenCComment; + return tokenCComment(stream, state); + } + }, + name: "css", + helperType: "gss" }); -})(); + +}); diff --git a/Source/WebInspectorUI/UserInterface/External/CodeMirror/htmlmixed.js b/Source/WebInspectorUI/UserInterface/External/CodeMirror/htmlmixed.js index b59ef37ed..eb21fcc14 100644 --- a/Source/WebInspectorUI/UserInterface/External/CodeMirror/htmlmixed.js +++ b/Source/WebInspectorUI/UserInterface/External/CodeMirror/htmlmixed.js @@ -1,104 +1,152 @@ -CodeMirror.defineMode("htmlmixed", function(config, parserConfig) { - var htmlMode = CodeMirror.getMode(config, {name: "xml", htmlMode: true}); - var cssMode = CodeMirror.getMode(config, "css"); - - var scriptTypes = [], scriptTypesConf = parserConfig && parserConfig.scriptTypes; - scriptTypes.push({matches: /^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^$/i, - mode: CodeMirror.getMode(config, "javascript")}); - if (scriptTypesConf) for (var i = 0; i < scriptTypesConf.length; ++i) { - var conf = scriptTypesConf[i]; - scriptTypes.push({matches: conf.matches, mode: conf.mode && CodeMirror.getMode(config, conf.mode)}); - } - scriptTypes.push({matches: /./, - mode: CodeMirror.getMode(config, "text/plain")}); - - function html(stream, state) { - var tagName = state.htmlState.tagName; - var style = htmlMode.token(stream, state.htmlState); - if (tagName == "script" && /\btag\b/.test(style) && stream.current() == ">") { - // Script block: mode to change to depends on type attribute - var scriptType = stream.string.slice(Math.max(0, stream.pos - 100), stream.pos).match(/\btype\s*=\s*("[^"]+"|'[^']+'|\S+)[^<]*$/i); - scriptType = scriptType ? scriptType[1] : ""; - if (scriptType && /[\"\']/.test(scriptType.charAt(0))) scriptType = scriptType.slice(1, scriptType.length - 1); - for (var i = 0; i < scriptTypes.length; ++i) { - var tp = scriptTypes[i]; - if (typeof tp.matches == "string" ? scriptType == tp.matches : tp.matches.test(scriptType)) { - if (tp.mode) { - state.token = script; - state.localMode = tp.mode; - state.localState = tp.mode.startState && tp.mode.startState(htmlMode.indent(state.htmlState, "")); - } - break; - } - } - } else if (tagName == "style" && /\btag\b/.test(style) && stream.current() == ">") { - state.token = css; - state.localMode = cssMode; - state.localState = cssMode.startState(htmlMode.indent(state.htmlState, "")); - } - return style; - } +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror"), require("../xml/xml"), require("../javascript/javascript"), require("../css/css")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror", "../xml/xml", "../javascript/javascript", "../css/css"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + "use strict"; + + var defaultTags = { + script: [ + ["lang", /(javascript|babel)/i, "javascript"], + ["type", /^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^$/i, "javascript"], + ["type", /./, "text/plain"], + [null, null, "javascript"] + ], + style: [ + ["lang", /^css$/i, "css"], + ["type", /^(text\/)?(x-)?(stylesheet|css)$/i, "css"], + ["type", /./, "text/plain"], + [null, null, "css"] + ] + }; + function maybeBackup(stream, pat, style) { - var cur = stream.current(); - var close = cur.search(pat), m; - if (close > -1) stream.backUp(cur.length - close); - else if (m = cur.match(/<\/?$/)) { + var cur = stream.current(), close = cur.search(pat); + if (close > -1) { + stream.backUp(cur.length - close); + } else if (cur.match(/<\/?$/)) { stream.backUp(cur.length); if (!stream.match(pat, false)) stream.match(cur); } return style; } - function script(stream, state) { - if (stream.match(/^<\/\s*script\s*>/i, false)) { - state.token = html; - state.localState = state.localMode = null; - return html(stream, state); - } - return maybeBackup(stream, /<\/\s*script\s*>/, - state.localMode.token(stream, state.localState)); + + var attrRegexpCache = {}; + function getAttrRegexp(attr) { + var regexp = attrRegexpCache[attr]; + if (regexp) return regexp; + return attrRegexpCache[attr] = new RegExp("\\s+" + attr + "\\s*=\\s*('|\")?([^'\"]+)('|\")?\\s*"); + } + + function getAttrValue(text, attr) { + var match = text.match(getAttrRegexp(attr)) + return match ? /^\s*(.*?)\s*$/.exec(match[2])[1] : "" + } + + function getTagRegexp(tagName, anchored) { + return new RegExp((anchored ? "^" : "") + "<\/\s*" + tagName + "\s*>", "i"); } - function css(stream, state) { - if (stream.match(/^<\/\s*style\s*>/i, false)) { - state.token = html; - state.localState = state.localMode = null; - return html(stream, state); + + function addTags(from, to) { + for (var tag in from) { + var dest = to[tag] || (to[tag] = []); + var source = from[tag]; + for (var i = source.length - 1; i >= 0; i--) + dest.unshift(source[i]) } - return maybeBackup(stream, /<\/\s*style\s*>/, - cssMode.token(stream, state.localState)); } - return { - startState: function() { - var state = htmlMode.startState(); - return {token: html, localMode: null, localState: null, htmlState: state}; - }, - - copyState: function(state) { - if (state.localState) - var local = CodeMirror.copyState(state.localMode, state.localState); - return {token: state.token, localMode: state.localMode, localState: local, - htmlState: CodeMirror.copyState(htmlMode, state.htmlState)}; - }, - - token: function(stream, state) { - return state.token(stream, state); - }, - - indent: function(state, textAfter) { - if (!state.localMode || /^\s*<\//.test(textAfter)) - return htmlMode.indent(state.htmlState, textAfter); - else if (state.localMode.indent) - return state.localMode.indent(state.localState, textAfter); - else - return CodeMirror.Pass; - }, - - electricChars: "/{}:", - - innerMode: function(state) { - return {state: state.localState || state.htmlState, mode: state.localMode || htmlMode}; + function findMatchingMode(tagInfo, tagText) { + for (var i = 0; i < tagInfo.length; i++) { + var spec = tagInfo[i]; + if (!spec[0] || spec[1].test(getAttrValue(tagText, spec[0]))) return spec[2]; } - }; -}, "xml", "javascript", "css"); + } + + CodeMirror.defineMode("htmlmixed", function (config, parserConfig) { + var htmlMode = CodeMirror.getMode(config, { + name: "xml", + htmlMode: true, + multilineTagIndentFactor: parserConfig.multilineTagIndentFactor, + multilineTagIndentPastTag: parserConfig.multilineTagIndentPastTag + }); + + var tags = {}; + var configTags = parserConfig && parserConfig.tags, configScript = parserConfig && parserConfig.scriptTypes; + addTags(defaultTags, tags); + if (configTags) addTags(configTags, tags); + if (configScript) for (var i = configScript.length - 1; i >= 0; i--) + tags.script.unshift(["type", configScript[i].matches, configScript[i].mode]) + + function html(stream, state) { + var style = htmlMode.token(stream, state.htmlState), tag = /\btag\b/.test(style), tagName + if (tag && !/[<>\s\/]/.test(stream.current()) && + (tagName = state.htmlState.tagName && state.htmlState.tagName.toLowerCase()) && + tags.hasOwnProperty(tagName)) { + state.inTag = tagName + " " + } else if (state.inTag && tag && />$/.test(stream.current())) { + var inTag = /^([\S]+) (.*)/.exec(state.inTag) + state.inTag = null + var modeSpec = stream.current() == ">" && findMatchingMode(tags[inTag[1]], inTag[2]) + var mode = CodeMirror.getMode(config, modeSpec) + var endTagA = getTagRegexp(inTag[1], true), endTag = getTagRegexp(inTag[1], false); + state.token = function (stream, state) { + if (stream.match(endTagA, false)) { + state.token = html; + state.localState = state.localMode = null; + return null; + } + return maybeBackup(stream, endTag, state.localMode.token(stream, state.localState)); + }; + state.localMode = mode; + state.localState = CodeMirror.startState(mode, htmlMode.indent(state.htmlState, "")); + } else if (state.inTag) { + state.inTag += stream.current() + if (stream.eol()) state.inTag += " " + } + return style; + }; + + return { + startState: function () { + var state = CodeMirror.startState(htmlMode); + return {token: html, inTag: null, localMode: null, localState: null, htmlState: state}; + }, + + copyState: function (state) { + var local; + if (state.localState) { + local = CodeMirror.copyState(state.localMode, state.localState); + } + return {token: state.token, inTag: state.inTag, + localMode: state.localMode, localState: local, + htmlState: CodeMirror.copyState(htmlMode, state.htmlState)}; + }, + + token: function (stream, state) { + return state.token(stream, state); + }, + + indent: function (state, textAfter) { + if (!state.localMode || /^\s*<\//.test(textAfter)) + return htmlMode.indent(state.htmlState, textAfter); + else if (state.localMode.indent) + return state.localMode.indent(state.localState, textAfter); + else + return CodeMirror.Pass; + }, + + innerMode: function (state) { + return {state: state.localState || state.htmlState, mode: state.localMode || htmlMode}; + } + }; + }, "xml", "javascript", "css"); -CodeMirror.defineMIME("text/html", "htmlmixed"); + CodeMirror.defineMIME("text/html", "htmlmixed"); +}); diff --git a/Source/WebInspectorUI/UserInterface/External/CodeMirror/javascript.js b/Source/WebInspectorUI/UserInterface/External/CodeMirror/javascript.js index f27c06346..10419bf9d 100644 --- a/Source/WebInspectorUI/UserInterface/External/CodeMirror/javascript.js +++ b/Source/WebInspectorUI/UserInterface/External/CodeMirror/javascript.js @@ -1,10 +1,28 @@ -// TODO actually recognize syntax of TypeScript constructs +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +function expressionAllowed(stream, state, backUp) { + return /^(?:operator|sof|keyword c|case|new|[\[{}\(,;:]|=>)$/.test(state.lastType) || + (state.lastType == "quasi" && /\{\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0)))) +} CodeMirror.defineMode("javascript", function(config, parserConfig) { var indentUnit = config.indentUnit; var statementIndent = parserConfig.statementIndent; - var jsonMode = parserConfig.json; + var jsonldMode = parserConfig.jsonld; + var jsonMode = parserConfig.json || jsonldMode; var isTS = parserConfig.typescript; + var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/; // Tokenizer @@ -15,14 +33,15 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) { var jsKeywords = { "if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B, - "return": C, "break": C, "continue": C, "new": C, "delete": C, "throw": C, + "return": C, "break": C, "continue": C, "new": kw("new"), "delete": C, "throw": C, "debugger": C, "var": kw("var"), "const": kw("var"), "let": kw("var"), "function": kw("function"), "catch": kw("catch"), "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"), "in": operator, "typeof": operator, "instanceof": operator, "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom, - "this": kw("this"), "module": kw("module"), "class": kw("class"), "super": kw("atom"), - "yield": C, "export": kw("export"), "import": kw("import"), "extends": C + "this": kw("this"), "class": kw("class"), "super": kw("atom"), + "yield": C, "export": kw("export"), "import": kw("import"), "extends": C, + "await": C, "async": kw("async") }; // Extend the 'normal' keywords with the TypeScript language extensions @@ -30,18 +49,24 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) { var type = {type: "variable", style: "variable-3"}; var tsKeywords = { // object-like things - "interface": kw("interface"), - "extends": kw("extends"), - "constructor": kw("constructor"), + "interface": kw("class"), + "implements": C, + "namespace": C, + "module": kw("module"), + "enum": kw("module"), + "type": kw("type"), // scope modifiers - "public": kw("public"), - "private": kw("private"), - "protected": kw("protected"), - "static": kw("static"), + "public": kw("modifier"), + "private": kw("modifier"), + "protected": kw("modifier"), + "abstract": kw("modifier"), + + // operators + "as": operator, // types - "string": type, "number": type, "bool": type, "any": type + "string": type, "number": type, "boolean": type, "any": type }; for (var attr in tsKeywords) { @@ -53,15 +78,18 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) { }(); var isOperatorChar = /[+\-*&%=<>!?|~^]/; + var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/; - function nextUntilUnescaped(stream, end) { - var escaped = false, next; + function readRegexp(stream) { + var escaped = false, next, inSet = false; while ((next = stream.next()) != null) { - if (next == end && !escaped) - return false; + if (!escaped) { + if (next == "/" && !inSet) return; + if (next == "[") inSet = true; + else if (inSet && next == "]") inSet = false; + } escaped = !escaped && next == "\\"; } - return escaped; } // Used as scratch variables to communicate multiple values without @@ -83,10 +111,16 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) { } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) { return ret(ch); } else if (ch == "=" && stream.eat(">")) { - return ret("=>"); + return ret("=>", "operator"); } else if (ch == "0" && stream.eat(/x/i)) { stream.eatWhile(/[\da-f]/i); return ret("number", "number"); + } else if (ch == "0" && stream.eat(/o/i)) { + stream.eatWhile(/[0-7]/i); + return ret("number", "number"); + } else if (ch == "0" && stream.eat(/b/i)) { + stream.eatWhile(/[01]/i); + return ret("number", "number"); } else if (/\d/.test(ch)) { stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/); return ret("number", "number"); @@ -97,14 +131,13 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) { } else if (stream.eat("/")) { stream.skipToEnd(); return ret("comment", "comment"); - } else if (state.lastType == "operator" || state.lastType == "keyword c" || - state.lastType == "sof" || /^[\[{}\(,;:]$/.test(state.lastType)) { - nextUntilUnescaped(stream, "/"); - stream.eatWhile(/[gimy]/); // 'y' is "sticky" option in Mozilla + } else if (expressionAllowed(stream, state, 1)) { + readRegexp(stream); + stream.match(/^\b(([gimyu])(?![gimyu]*\2))+\b/); return ret("regexp", "string-2"); } else { stream.eatWhile(isOperatorChar); - return ret("operator", null, stream.current()); + return ret("operator", "operator", stream.current()); } } else if (ch == "`") { state.tokenize = tokenQuasi; @@ -113,10 +146,11 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) { stream.skipToEnd(); return ret("error", "error"); } else if (isOperatorChar.test(ch)) { - stream.eatWhile(isOperatorChar); - return ret("operator", null, stream.current()); - } else { - stream.eatWhile(/[\w\$_]/); + if (ch != ">" || !state.lexical || state.lexical.type != ">") + stream.eatWhile(isOperatorChar); + return ret("operator", "operator", stream.current()); + } else if (wordRE.test(ch)) { + stream.eatWhile(wordRE); var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word]; return (known && state.lastType != ".") ? ret(known.type, known.style, word) : ret("variable", "variable", word); @@ -125,8 +159,16 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) { function tokenString(quote) { return function(stream, state) { - if (!nextUntilUnescaped(stream, quote)) + var escaped = false, next; + if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){ state.tokenize = tokenBase; + return ret("jsonld-keyword", "meta"); + } + while ((next = stream.next()) != null) { + if (next == quote && !escaped) break; + escaped = !escaped && next == "\\"; + } + if (!escaped) state.tokenize = tokenBase; return ret("string", "string"); }; } @@ -168,17 +210,24 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) { var arrow = stream.string.indexOf("=>", stream.start); if (arrow < 0) return; + if (isTS) { // Try to skip TypeScript return type declarations after the arguments + var m = /:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(stream.string.slice(stream.start, arrow)) + if (m) arrow = m.index + } + var depth = 0, sawSomething = false; for (var pos = arrow - 1; pos >= 0; --pos) { var ch = stream.string.charAt(pos); var bracket = brackets.indexOf(ch); if (bracket >= 0 && bracket < 3) { if (!depth) { ++pos; break; } - if (--depth == 0) break; + if (--depth == 0) { if (ch == "(") sawSomething = true; break; } } else if (bracket >= 3 && bracket < 6) { ++depth; - } else if (/[$\w]/.test(ch)) { + } else if (wordRE.test(ch)) { sawSomething = true; + } else if (/["'\/]/.test(ch)) { + return; } else if (sawSomething && !depth) { ++pos; break; @@ -189,7 +238,7 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) { // Parser - var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true}; + var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true, "jsonld-keyword": true}; function JSLexical(indented, column, type, align, prev, info) { this.indented = indented; @@ -213,7 +262,7 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) { var cc = state.cc; // Communicate our context to the combinators. // (Less wasteful than consing up a hundred closures on every call.) - cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; + cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style; if (!state.lexical.hasOwnProperty("align")) state.lexical.align = true; @@ -247,8 +296,8 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) { return false; } var state = cx.state; + cx.marked = "def"; if (state.context) { - cx.marked = "def"; if (inList(state.localVars)) return; state.localVars = {name: varname, next: state.localVars}; } else { @@ -273,6 +322,8 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) { var result = function() { var state = cx.state, indent = state.indented; if (state.lexical.type == "stat") indent = state.lexical.indented; + else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev) + indent = outer.indented; state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info); }; result.lex = true; @@ -289,33 +340,40 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) { poplex.lex = true; function expect(wanted) { - return function(type) { + function exp(type) { if (type == wanted) return cont(); else if (wanted == ";") return pass(); - else return cont(arguments.callee); + else return cont(exp); }; + return exp; } function statement(type, value) { if (type == "var") return cont(pushlex("vardef", value.length), vardef, expect(";"), poplex); - if (type == "keyword a") return cont(pushlex("form"), expression, statement, poplex); + if (type == "keyword a") return cont(pushlex("form"), parenExpr, statement, poplex); if (type == "keyword b") return cont(pushlex("form"), statement, poplex); if (type == "{") return cont(pushlex("}"), block, poplex); if (type == ";") return cont(); - if (type == "if") return cont(pushlex("form"), expression, statement, poplex, maybeelse); + if (type == "if") { + if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex) + cx.state.cc.pop()(); + return cont(pushlex("form"), parenExpr, statement, poplex, maybeelse); + } if (type == "function") return cont(functiondef); - if (type == "for") return cont(pushlex("form"), forspec, poplex, statement, poplex); + if (type == "for") return cont(pushlex("form"), forspec, statement, poplex); if (type == "variable") return cont(pushlex("stat"), maybelabel); - if (type == "switch") return cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"), + if (type == "switch") return cont(pushlex("form"), parenExpr, pushlex("}", "switch"), expect("{"), block, poplex, poplex); if (type == "case") return cont(expression, expect(":")); if (type == "default") return cont(expect(":")); if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"), statement, poplex, popcontext); - if (type == "module") return cont(pushlex("form"), pushcontext, afterModule, popcontext, poplex); - if (type == "class") return cont(pushlex("form"), className, objlit, poplex); - if (type == "export") return cont(pushlex("form"), afterExport, poplex); - if (type == "import") return cont(pushlex("form"), afterImport, poplex); + if (type == "class") return cont(pushlex("form"), className, poplex); + if (type == "export") return cont(pushlex("stat"), afterExport, poplex); + if (type == "import") return cont(pushlex("stat"), afterImport, poplex); + if (type == "module") return cont(pushlex("form"), pattern, pushlex("}"), expect("{"), block, poplex, poplex) + if (type == "type") return cont(typeexpr, expect("operator"), typeexpr, expect(";")); + if (type == "async") return cont(statement) return pass(pushlex("stat"), expression, expect(";"), poplex); } function expression(type) { @@ -324,21 +382,28 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) { function expressionNoComma(type) { return expressionInner(type, true); } + function parenExpr(type) { + if (type != "(") return pass() + return cont(pushlex(")"), expression, expect(")"), poplex) + } function expressionInner(type, noComma) { if (cx.state.fatArrowAt == cx.stream.start) { var body = noComma ? arrowBodyNoComma : arrowBody; - if (type == "(") return cont(pushcontext, commasep(pattern, ")"), expect("=>"), body, popcontext); + if (type == "(") return cont(pushcontext, pushlex(")"), commasep(pattern, ")"), poplex, expect("=>"), body, popcontext); else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext); } var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma; if (atomicTypes.hasOwnProperty(type)) return cont(maybeop); - if (type == "function") return cont(functiondef); - if (type == "keyword c") return cont(noComma ? maybeexpressionNoComma : maybeexpression); - if (type == "(") return cont(pushlex(")"), maybeexpression, comprehension, expect(")"), poplex, maybeop); + if (type == "function") return cont(functiondef, maybeop); + if (type == "class") return cont(pushlex("form"), classExpression, poplex); + if (type == "keyword c" || type == "async") return cont(noComma ? maybeexpressionNoComma : maybeexpression); + if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeop); if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression); - if (type == "[") return cont(pushlex("]"), expressionNoComma, maybeArrayComprehension, poplex, maybeop); - if (type == "{") return cont(commasep(objprop, "}"), maybeop); + if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop); + if (type == "{") return contCommasep(objprop, "}", null, maybeop); + if (type == "quasi") return pass(quasi, maybeop); + if (type == "new") return cont(maybeTarget(noComma)); return cont(); } function maybeexpression(type) { @@ -357,39 +422,49 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) { function maybeoperatorNoComma(type, value, noComma) { var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma; var expr = noComma == false ? expression : expressionNoComma; - if (value == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext); + if (type == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext); if (type == "operator") { if (/\+\+|--/.test(value)) return cont(me); if (value == "?") return cont(expression, expect(":"), expr); return cont(expr); } - if (type == "quasi") { cx.cc.push(me); return quasi(value); } + if (type == "quasi") { return pass(quasi, me); } if (type == ";") return; - if (type == "(") return cont(commasep(expressionNoComma, ")", "call"), me); + if (type == "(") return contCommasep(expressionNoComma, ")", "call", me); if (type == ".") return cont(property, me); if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me); } - function quasi(value) { - if (!value) debugger; - if (value.slice(value.length - 2) != "${") return cont(); + function quasi(type, value) { + if (type != "quasi") return pass(); + if (value.slice(value.length - 2) != "${") return cont(quasi); return cont(expression, continueQuasi); } function continueQuasi(type) { if (type == "}") { cx.marked = "string-2"; cx.state.tokenize = tokenQuasi; - return cont(); + return cont(quasi); } } function arrowBody(type) { findFatArrow(cx.stream, cx.state); - if (type == "{") return pass(statement); - return pass(expression); + return pass(type == "{" ? statement : expression); } function arrowBodyNoComma(type) { findFatArrow(cx.stream, cx.state); - if (type == "{") return pass(statement); - return pass(expressionNoComma); + return pass(type == "{" ? statement : expressionNoComma); + } + function maybeTarget(noComma) { + return function(type) { + if (type == ".") return cont(noComma ? targetNoComma : target); + else return pass(noComma ? expressionNoComma : expression); + }; + } + function target(_, value) { + if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorComma); } + } + function targetNoComma(_, value) { + if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorNoComma); } } function maybelabel(type) { if (type == ":") return cont(poplex, statement); @@ -399,15 +474,27 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) { if (type == "variable") {cx.marked = "property"; return cont();} } function objprop(type, value) { - if (type == "variable") { + if (type == "async") { + cx.marked = "property"; + return cont(objprop); + } else if (type == "variable" || cx.style == "keyword") { cx.marked = "property"; if (value == "get" || value == "set") return cont(getterSetter); + return cont(afterprop); } else if (type == "number" || type == "string") { - cx.marked = type + " property"; + cx.marked = jsonldMode ? "property" : (cx.style + " property"); + return cont(afterprop); + } else if (type == "jsonld-keyword") { + return cont(afterprop); + } else if (type == "modifier") { + return cont(objprop) } else if (type == "[") { return cont(expression, expect("]"), afterprop); + } else if (type == "spread") { + return cont(expression); + } else if (type == ":") { + return pass(afterprop) } - if (atomicTypes.hasOwnProperty(type)) return cont(afterprop); } function getterSetter(type) { if (type != "variable") return pass(afterprop); @@ -418,39 +505,74 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) { if (type == ":") return cont(expressionNoComma); if (type == "(") return pass(functiondef); } - function commasep(what, end, info) { - function proceed(type) { + function commasep(what, end) { + function proceed(type, value) { if (type == ",") { var lex = cx.state.lexical; if (lex.info == "call") lex.pos = (lex.pos || 0) + 1; - return cont(what, proceed); + return cont(function(type, value) { + if (type == end || value == end) return pass() + return pass(what) + }, proceed); } - if (type == end) return cont(); + if (type == end || value == end) return cont(); return cont(expect(end)); } - return function(type) { - if (type == end) return cont(); - if (info === false) return pass(what, proceed); - return pass(pushlex(end, info), what, proceed, poplex); + return function(type, value) { + if (type == end || value == end) return cont(); + return pass(what, proceed); }; } + function contCommasep(what, end, info) { + for (var i = 3; i < arguments.length; i++) + cx.cc.push(arguments[i]); + return cont(pushlex(end, info), commasep(what, end), poplex); + } function block(type) { if (type == "}") return cont(); return pass(statement, block); } - function maybetype(type) { - if (isTS && type == ":") return cont(typedef); + function maybetype(type, value) { + if (isTS) { + if (type == ":") return cont(typeexpr); + if (value == "?") return cont(maybetype); + } + } + function typeexpr(type) { + if (type == "variable") {cx.marked = "variable-3"; return cont(afterType);} + if (type == "string" || type == "number" || type == "atom") return cont(afterType); + if (type == "{") return cont(commasep(typeprop, "}")) + if (type == "(") return cont(commasep(typearg, ")"), maybeReturnType) + } + function maybeReturnType(type) { + if (type == "=>") return cont(typeexpr) + } + function typeprop(type) { + if (type == "variable" || cx.style == "keyword") { + cx.marked = "property" + return cont(typeprop) + } else if (type == ":") { + return cont(typeexpr) + } + } + function typearg(type) { + if (type == "variable") return cont(typearg) + else if (type == ":") return cont(typeexpr) } - function typedef(type) { - if (type == "variable"){cx.marked = "variable-3"; return cont();} + function afterType(type, value) { + if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType) + if (value == "|" || type == ".") return cont(typeexpr) + if (type == "[") return cont(expect("]"), afterType) } function vardef() { return pass(pattern, maybetype, maybeAssign, vardefCont); } function pattern(type, value) { + if (type == "modifier") return cont(pattern) if (type == "variable") { register(value); return cont(); } - if (type == "[") return cont(commasep(pattern, "]")); - if (type == "{") return cont(commasep(proppattern, "}")); + if (type == "spread") return cont(pattern); + if (type == "[") return contCommasep(pattern, "]"); + if (type == "{") return contCommasep(proppattern, "}"); } function proppattern(type, value) { if (type == "variable" && !cx.stream.match(/^\s*:/, false)) { @@ -458,6 +580,8 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) { return cont(maybeAssign); } if (type == "variable") cx.marked = "property"; + if (type == "spread") return cont(pattern); + if (type == "}") return pass(); return cont(expect(":"), pattern, maybeAssign); } function maybeAssign(_type, value) { @@ -467,10 +591,10 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) { if (type == ",") return cont(vardef); } function maybeelse(type, value) { - if (type == "keyword b" && value == "else") return cont(pushlex("form"), statement, poplex); + if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex); } function forspec(type) { - if (type == "(") return cont(pushlex(")"), forspec1, expect(")")); + if (type == "(") return cont(pushlex(")"), forspec1, expect(")"), poplex); } function forspec1(type) { if (type == "var") return cont(vardef, expect(";"), forspec2); @@ -493,24 +617,46 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) { function functiondef(type, value) { if (value == "*") {cx.marked = "keyword"; return cont(functiondef);} if (type == "variable") {register(value); return cont(functiondef);} - if (type == "(") return cont(pushcontext, commasep(funarg, ")"), statement, popcontext); + if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, maybetype, statement, popcontext); } function funarg(type) { if (type == "spread") return cont(funarg); - return pass(pattern, maybetype); + return pass(pattern, maybetype, maybeAssign); + } + function classExpression(type, value) { + // Class expressions may have an optional name. + if (type == "variable") return className(type, value); + return classNameAfter(type, value); } function className(type, value) { if (type == "variable") {register(value); return cont(classNameAfter);} } - function classNameAfter(_type, value) { - if (value == "extends") return cont(expression); - } - function objlit(type) { - if (type == "{") return cont(commasep(objprop, "}")); + function classNameAfter(type, value) { + if (value == "extends" || value == "implements") return cont(isTS ? typeexpr : expression, classNameAfter); + if (type == "{") return cont(pushlex("}"), classBody, poplex); + } + function classBody(type, value) { + if (type == "variable" || cx.style == "keyword") { + if ((value == "static" || value == "get" || value == "set" || + (isTS && (value == "public" || value == "private" || value == "protected" || value == "readonly" || value == "abstract"))) && + cx.stream.match(/^\s+[\w$\xa1-\uffff]/, false)) { + cx.marked = "keyword"; + return cont(classBody); + } + cx.marked = "property"; + return cont(isTS ? classfield : functiondef, classBody); + } + if (value == "*") { + cx.marked = "keyword"; + return cont(classBody); + } + if (type == ";") return cont(classBody); + if (type == "}") return cont(); } - function afterModule(type, value) { - if (type == "string") return cont(statement); - if (type == "variable") { register(value); return cont(maybeFrom); } + function classfield(type, value) { + if (value == "?") return cont(classfield) + if (type == ":") return cont(typeexpr, maybeAssign) + return pass(functiondef) } function afterExport(_type, value) { if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); } @@ -522,21 +668,26 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) { return pass(importSpec, maybeFrom); } function importSpec(type, value) { - if (type == "{") return cont(commasep(importSpec, "}")); + if (type == "{") return contCommasep(importSpec, "}"); if (type == "variable") register(value); - return cont(); + if (value == "*") cx.marked = "keyword"; + return cont(maybeAs); + } + function maybeAs(_type, value) { + if (value == "as") { cx.marked = "keyword"; return cont(importSpec); } } function maybeFrom(_type, value) { if (value == "from") { cx.marked = "keyword"; return cont(expression); } } - function maybeArrayComprehension(type) { - if (type == "for") return pass(comprehension); - if (type == ",") return cont(commasep(expressionNoComma, "]", false)); - return pass(commasep(expressionNoComma, "]", false)); + function arrayLiteral(type) { + if (type == "]") return cont(); + return pass(commasep(expressionNoComma, "]")); } - function comprehension(type) { - if (type == "for") return cont(forspec, comprehension); - if (type == "if") return cont(expression, comprehension); + + function isContinuedStatement(state, textAfter) { + return state.lastType == "operator" || state.lastType == "," || + isOperatorChar.test(textAfter.charAt(0)) || + /[,.]/.test(textAfter.charAt(0)); } // Interface @@ -550,9 +701,10 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) { lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false), localVars: parserConfig.localVars, context: parserConfig.localVars && {vars: parserConfig.localVars}, - indented: 0 + indented: basecolumn || 0 }; - if (parserConfig.globalVars) state.globalVars = parserConfig.globalVars; + if (parserConfig.globalVars && typeof parserConfig.globalVars == "object") + state.globalVars = parserConfig.globalVars; return state; }, @@ -573,14 +725,18 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) { indent: function(state, textAfter) { if (state.tokenize == tokenComment) return CodeMirror.Pass; if (state.tokenize != tokenBase) return 0; - var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical; + var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical, top // Kludge to prevent 'maybelse' from blocking lexical scope pops - for (var i = state.cc.length - 1; i >= 0; --i) { + if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) { var c = state.cc[i]; if (c == poplex) lexical = lexical.prev; else if (c != maybeelse) break; } - if (lexical.type == "stat" && firstChar == "}") lexical = lexical.prev; + while ((lexical.type == "stat" || lexical.type == "form") && + (firstChar == "}" || ((top = state.cc[state.cc.length - 1]) && + (top == maybeoperatorComma || top == maybeoperatorNoComma) && + !/^[,\.=+\-*:?[\(]/.test(textAfter)))) + lexical = lexical.prev; if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat") lexical = lexical.prev; var type = lexical.type, closing = firstChar == type; @@ -589,29 +745,43 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) { else if (type == "form" && firstChar == "{") return lexical.indented; else if (type == "form") return lexical.indented + indentUnit; else if (type == "stat") - return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? statementIndent || indentUnit : 0); + return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0); else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false) return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit); else if (lexical.align) return lexical.column + (closing ? 0 : 1); else return lexical.indented + (closing ? 0 : indentUnit); }, - electricChars: ":{}", + electricInput: /^\s*(?:case .*?:|default:|\{|\})$/, blockCommentStart: jsonMode ? null : "/*", blockCommentEnd: jsonMode ? null : "*/", lineComment: jsonMode ? null : "//", fold: "brace", + closeBrackets: "()[]{}''\"\"``", helperType: jsonMode ? "json" : "javascript", - jsonMode: jsonMode + jsonldMode: jsonldMode, + jsonMode: jsonMode, + + expressionAllowed: expressionAllowed, + skipExpression: function(state) { + var top = state.cc[state.cc.length - 1] + if (top == expression || top == expressionNoComma) state.cc.pop() + } }; }); +CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/); + CodeMirror.defineMIME("text/javascript", "javascript"); CodeMirror.defineMIME("text/ecmascript", "javascript"); CodeMirror.defineMIME("application/javascript", "javascript"); +CodeMirror.defineMIME("application/x-javascript", "javascript"); CodeMirror.defineMIME("application/ecmascript", "javascript"); CodeMirror.defineMIME("application/json", {name: "javascript", json: true}); CodeMirror.defineMIME("application/x-json", {name: "javascript", json: true}); +CodeMirror.defineMIME("application/ld+json", {name: "javascript", jsonld: true}); CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true }); CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true }); + +}); diff --git a/Source/WebInspectorUI/UserInterface/External/CodeMirror/less.js b/Source/WebInspectorUI/UserInterface/External/CodeMirror/less.js deleted file mode 100644 index da3907485..000000000 --- a/Source/WebInspectorUI/UserInterface/External/CodeMirror/less.js +++ /dev/null @@ -1,346 +0,0 @@ -/* - LESS mode - http://www.lesscss.org/ - Ported to CodeMirror by Peter Kroon - Report bugs/issues here: https://github.com/marijnh/CodeMirror/issues - GitHub: @peterkroon -*/ - -CodeMirror.defineMode("less", function(config) { - var indentUnit = config.indentUnit, type; - function ret(style, tp) {type = tp; return style;} - - var selectors = /(^\:root$|^\:nth\-child$|^\:nth\-last\-child$|^\:nth\-of\-type$|^\:nth\-last\-of\-type$|^\:first\-child$|^\:last\-child$|^\:first\-of\-type$|^\:last\-of\-type$|^\:only\-child$|^\:only\-of\-type$|^\:empty$|^\:link|^\:visited$|^\:active$|^\:hover$|^\:focus$|^\:target$|^\:lang$|^\:enabled^\:disabled$|^\:checked$|^\:first\-line$|^\:first\-letter$|^\:before$|^\:after$|^\:not$|^\:required$|^\:invalid$)/; - - function tokenBase(stream, state) { - var ch = stream.next(); - - if (ch == "@") {stream.eatWhile(/[\w\-]/); return ret("meta", stream.current());} - else if (ch == "/" && stream.eat("*")) { - state.tokenize = tokenCComment; - return tokenCComment(stream, state); - } else if (ch == "<" && stream.eat("!")) { - state.tokenize = tokenSGMLComment; - return tokenSGMLComment(stream, state); - } else if (ch == "=") ret(null, "compare"); - else if (ch == "|" && stream.eat("=")) return ret(null, "compare"); - else if (ch == "\"" || ch == "'") { - state.tokenize = tokenString(ch); - return state.tokenize(stream, state); - } else if (ch == "/") { // e.g.: .png will not be parsed as a class - if(stream.eat("/")){ - state.tokenize = tokenSComment; - return tokenSComment(stream, state); - } else { - if(type == "string" || type == "(") return ret("string", "string"); - if(state.stack[state.stack.length-1] !== undefined) return ret(null, ch); - stream.eatWhile(/[\a-zA-Z0-9\-_.\s]/); - if( /\/|\)|#/.test(stream.peek() || (stream.eatSpace() && stream.peek() === ")")) || stream.eol() )return ret("string", "string"); // let url(/images/logo.png) without quotes return as string - } - } else if (ch == "!") { - stream.match(/^\s*\w*/); - return ret("keyword", "important"); - } else if (/\d/.test(ch)) { - stream.eatWhile(/[\w.%]/); - return ret("number", "unit"); - } else if (/[,+<>*\/]/.test(ch)) { - if(stream.peek() == "=" || type == "a")return ret("string", "string"); - if(ch === ",")return ret(null, ch); - return ret(null, "select-op"); - } else if (/[;{}:\[\]()~\|]/.test(ch)) { - if(ch == ":"){ - stream.eatWhile(/[a-z\\\-]/); - if( selectors.test(stream.current()) ){ - return ret("tag", "tag"); - } else if(stream.peek() == ":"){//::-webkit-search-decoration - stream.next(); - stream.eatWhile(/[a-z\\\-]/); - if(stream.current().match(/\:\:\-(o|ms|moz|webkit)\-/))return ret("string", "string"); - if( selectors.test(stream.current().substring(1)) )return ret("tag", "tag"); - return ret(null, ch); - } else { - return ret(null, ch); - } - } else if(ch == "~"){ - if(type == "r")return ret("string", "string"); - } else { - return ret(null, ch); - } - } else if (ch == ".") { - if(type == "(")return ret("string", "string"); // allow url(../image.png) - stream.eatWhile(/[\a-zA-Z0-9\-_]/); - if(stream.peek() === " ")stream.eatSpace(); - if(stream.peek() === ")" || type === ":")return ret("number", "unit");//rgba(0,0,0,.25); - else if(stream.current().length >1){ - if(state.stack[state.stack.length-1] === "rule" && stream.peek().match(/{|,|\+|\(/) === null)return ret("number", "unit"); - } - return ret("tag", "tag"); - } else if (ch == "#") { - //we don't eat white-space, we want the hex color and or id only - stream.eatWhile(/[A-Za-z0-9]/); - //check if there is a proper hex color length e.g. #eee || #eeeEEE - if(stream.current().length == 4 || stream.current().length == 7){ - if(stream.current().match(/[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3}/,false) != null){//is there a valid hex color value present in the current stream - //when not a valid hex value, parse as id - if(stream.current().substring(1) != stream.current().match(/[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3}/,false))return ret("atom", "tag"); - //eat white-space - stream.eatSpace(); - //when hex value declaration doesn't end with [;,] but is does with a slash/cc comment treat it as an id, just like the other hex values that don't end with[;,] - if( /[\/<>.(){!$%^&*_\-\\?=+\|#'~`]/.test(stream.peek()) ){ - if(type === "select-op")return ret("number", "unit"); else return ret("atom", "tag"); - } - //#time { color: #aaa } - else if(stream.peek() == "}" )return ret("number", "unit"); - //we have a valid hex color value, parse as id whenever an element/class is defined after the hex(id) value e.g. #eee aaa || #eee .aaa - else if( /[a-zA-Z\\]/.test(stream.peek()) )return ret("atom", "tag"); - //when a hex value is on the end of a line, parse as id - else if(stream.eol())return ret("atom", "tag"); - //default - else return ret("number", "unit"); - } else {//when not a valid hexvalue in the current stream e.g. #footer - stream.eatWhile(/[\w\\\-]/); - return ret("atom", stream.current()); - } - } else {//when not a valid hexvalue length - stream.eatWhile(/[\w\\\-]/); - if(state.stack[state.stack.length-1] === "rule")return ret("atom", stream.current());return ret("atom", stream.current()); - return ret("atom", "tag"); - } - } else if (ch == "&") { - stream.eatWhile(/[\w\-]/); - return ret(null, ch); - } else { - stream.eatWhile(/[\w\\\-_%.{]/); - if(stream.current().match(/\\/) !== null){ - if(stream.current().charAt(stream.current().length-1) === "\\"){ - stream.eat(/\'|\"|\)|\(/); - while(stream.eatWhile(/[\w\\\-_%.{]/)){ - stream.eat(/\'|\"|\)|\(/); - } - return ret("string", stream.current()); - } - } //else if(type === "tag")return ret("tag", "tag"); - else if(type == "string"){ - if(state.stack[state.stack.length-1] === "{" && stream.peek() === ":")return ret("variable", "variable"); - if(stream.peek() === "/")stream.eatWhile(/[\w\\\-_%.{:\/]/); - return ret(type, stream.current()); - } else if(stream.current().match(/(^http$|^https$)/) != null){ - stream.eatWhile(/[\w\\\-_%.{:\/]/); - if(stream.peek() === "/")stream.eatWhile(/[\w\\\-_%.{:\/]/); - return ret("string", "string"); - } else if(stream.peek() == "<" || stream.peek() == ">" || stream.peek() == "+"){ - if(type === "(" && (stream.current() === "n" || stream.current() === "-n"))return ret("string", stream.current()); - return ret("tag", "tag"); - } else if( /\(/.test(stream.peek()) ){ - if(stream.current() === "when")return ret("variable","variable"); - else if(state.stack[state.stack.length-1] === "@media" && stream.current() === "and")return ret("variable",stream.current()); - return ret(null, ch); - } else if (stream.peek() == "/" && state.stack[state.stack.length-1] !== undefined){ // url(dir/center/image.png) - if(stream.peek() === "/")stream.eatWhile(/[\w\\\-_%.{:\/]/); - return ret("string", stream.current()); - } else if( stream.current().match(/\-\d|\-.\d/) ){ // match e.g.: -5px -0.4 etc... only colorize the minus sign - //commment out these 2 comment if you want the minus sign to be parsed as null -500px - //stream.backUp(stream.current().length-1); - //return ret(null, ch); - return ret("number", "unit"); - } else if( /\/|[\s\)]/.test(stream.peek() || stream.eol() || (stream.eatSpace() && stream.peek() == "/")) && stream.current().indexOf(".") !== -1){ - if(stream.current().substring(stream.current().length-1,stream.current().length) == "{"){ - stream.backUp(1); - return ret("tag", "tag"); - }//end if - stream.eatSpace(); - if( /[{<>.a-zA-Z\/]/.test(stream.peek()) || stream.eol() )return ret("tag", "tag"); // e.g. button.icon-plus - return ret("string", "string"); // let url(/images/logo.png) without quotes return as string - } else if( stream.eol() || stream.peek() == "[" || stream.peek() == "#" || type == "tag" ){ - - if(stream.current().substring(stream.current().length-1,stream.current().length) == "{")stream.backUp(1); - else if(state.stack[state.stack.length-1] === "border-color" || state.stack[state.stack.length-1] === "background-position" || state.stack[state.stack.length-1] === "font-family")return ret(null, stream.current()); - else if(type === "tag")return ret("tag", "tag"); - else if((type === ":" || type === "unit") && state.stack[state.stack.length-1] === "rule")return ret(null, stream.current()); - else if(state.stack[state.stack.length-1] === "rule" && type === "tag")return ret("string", stream.current()); - else if(state.stack[state.stack.length-1] === ";" && type === ":")return ret(null, stream.current()); - //else if(state.stack[state.stack.length-1] === ";" || type === "")return ret("variable", stream.current()); - else if(stream.peek() === "#" && type !== undefined && type.match(/\+|,|tag|select\-op|}|{|;/g) === null)return ret("string", stream.current()); - else if(type === "variable")return ret(null, stream.current()); - else if(state.stack[state.stack.length-1] === "{" && type === "comment")return ret("variable", stream.current()); - else if(state.stack.length === 0 && (type === ";" || type === "comment"))return ret("tag", stream.current()); - else if((state.stack[state.stack.length-1] === "{" || type === ";") && state.stack[state.stack.length-1] !== "@media{")return ret("variable", stream.current()); - else if(state.stack[state.stack.length-2] === "{" && state.stack[state.stack.length-1] === ";")return ret("variable", stream.current()); - - return ret("tag", "tag"); - } else if(type == "compare" || type == "a" || type == "("){ - return ret("string", "string"); - } else if(type == "|" || stream.current() == "-" || type == "["){ - if(type == "|" && stream.peek().match(/\]|=|\~/) !== null)return ret("number", stream.current()); - else if(type == "|" )return ret("tag", "tag"); - else if(type == "["){ - stream.eatWhile(/\w\-/); - return ret("number", stream.current()); - } - return ret(null, ch); - } else if((stream.peek() == ":") || ( stream.eatSpace() && stream.peek() == ":")) { - stream.next(); - var t_v = stream.peek() == ":" ? true : false; - if(!t_v){ - var old_pos = stream.pos; - var sc = stream.current().length; - stream.eatWhile(/[a-z\\\-]/); - var new_pos = stream.pos; - if(stream.current().substring(sc-1).match(selectors) != null){ - stream.backUp(new_pos-(old_pos-1)); - return ret("tag", "tag"); - } else stream.backUp(new_pos-(old_pos-1)); - } else { - stream.backUp(1); - } - if(t_v)return ret("tag", "tag"); else return ret("variable", "variable"); - } else if(state.stack[state.stack.length-1] === "font-family" || state.stack[state.stack.length-1] === "background-position" || state.stack[state.stack.length-1] === "border-color"){ - return ret(null, null); - } else { - - if(state.stack[state.stack.length-1] === null && type === ":")return ret(null, stream.current()); - - //else if((type === ")" && state.stack[state.stack.length-1] === "rule") || (state.stack[state.stack.length-2] === "{" && state.stack[state.stack.length-1] === "rule" && type === "variable"))return ret(null, stream.current()); - - else if(/\^|\$/.test(stream.current()) && stream.peek().match(/\~|=/) !== null)return ret("string", "string");//att^=val - - else if(type === "unit" && state.stack[state.stack.length-1] === "rule")return ret(null, "unit"); - else if(type === "unit" && state.stack[state.stack.length-1] === ";")return ret(null, "unit"); - else if(type === ")" && state.stack[state.stack.length-1] === "rule")return ret(null, "unit"); - else if(type && type.match("@") !== null && state.stack[state.stack.length-1] === "rule")return ret(null, "unit"); - //else if(type === "unit" && state.stack[state.stack.length-1] === "rule")return ret(null, stream.current()); - - else if((type === ";" || type === "}" || type === ",") && state.stack[state.stack.length-1] === ";")return ret("tag", stream.current()); - else if((type === ";" && stream.peek() !== undefined && stream.peek().match(/{|./) === null) || (type === ";" && stream.eatSpace() && stream.peek().match(/{|./) === null))return ret("variable", stream.current()); - else if((type === "@media" && state.stack[state.stack.length-1] === "@media") || type === "@namespace")return ret("tag", stream.current()); - - else if(type === "{" && state.stack[state.stack.length-1] === ";" && stream.peek() === "{")return ret("tag", "tag"); - else if((type === "{" || type === ":") && state.stack[state.stack.length-1] === ";")return ret(null, stream.current()); - else if((state.stack[state.stack.length-1] === "{" && stream.eatSpace() && stream.peek().match(/.|#/) === null) || type === "select-op" || (state.stack[state.stack.length-1] === "rule" && type === ",") )return ret("tag", "tag"); - else if(type === "variable" && state.stack[state.stack.length-1] === "rule")return ret("tag", "tag"); - else if((stream.eatSpace() && stream.peek() === "{") || stream.eol() || stream.peek() === "{")return ret("tag", "tag"); - //this one messes up indentation - //else if((type === "}" && stream.peek() !== ":") || (type === "}" && stream.eatSpace() && stream.peek() !== ":"))return(type, "tag"); - - else if(type === ")" && (stream.current() == "and" || stream.current() == "and "))return ret("variable", "variable"); - else if(type === ")" && (stream.current() == "when" || stream.current() == "when "))return ret("variable", "variable"); - else if(type === ")" || type === "comment" || type === "{")return ret("tag", "tag"); - else if(stream.sol())return ret("tag", "tag"); - else if((stream.eatSpace() && stream.peek() === "#") || stream.peek() === "#")return ret("tag", "tag"); - else if(state.stack.length === 0)return ret("tag", "tag"); - else if(type === ";" && stream.peek() !== undefined && stream.peek().match(/^[.|\#]/g) !== null)return ret("tag", "tag"); - - else if(type === ":"){stream.eatSpace();return ret(null, stream.current());} - - else if(stream.current() === "and " || stream.current() === "and")return ret("variable", stream.current()); - else if(type === ";" && state.stack[state.stack.length-1] === "{")return ret("variable", stream.current()); - - else if(state.stack[state.stack.length-1] === "rule")return ret(null, stream.current()); - - return ret("tag", stream.current()); - } - } - } - - function tokenSComment(stream, state) { // SComment = Slash comment - stream.skipToEnd(); - state.tokenize = tokenBase; - return ret("comment", "comment"); - } - - function tokenCComment(stream, state) { - var maybeEnd = false, ch; - while ((ch = stream.next()) != null) { - if (maybeEnd && ch == "/") { - state.tokenize = tokenBase; - break; - } - maybeEnd = (ch == "*"); - } - return ret("comment", "comment"); - } - - function tokenSGMLComment(stream, state) { - var dashes = 0, ch; - while ((ch = stream.next()) != null) { - if (dashes >= 2 && ch == ">") { - state.tokenize = tokenBase; - break; - } - dashes = (ch == "-") ? dashes + 1 : 0; - } - return ret("comment", "comment"); - } - - function tokenString(quote) { - return function(stream, state) { - var escaped = false, ch; - while ((ch = stream.next()) != null) { - if (ch == quote && !escaped) - break; - escaped = !escaped && ch == "\\"; - } - if (!escaped) state.tokenize = tokenBase; - return ret("string", "string"); - }; - } - - return { - startState: function(base) { - return {tokenize: tokenBase, - baseIndent: base || 0, - stack: []}; - }, - - token: function(stream, state) { - if (stream.eatSpace()) return null; - var style = state.tokenize(stream, state); - - var context = state.stack[state.stack.length-1]; - if (type == "hash" && context == "rule") style = "atom"; - else if (style == "variable") { - if (context == "rule") style = null; //"tag" - else if (!context || context == "@media{") { - style = stream.current() == "when" ? "variable" : - /[\s,|\s\)|\s]/.test(stream.peek()) ? "tag" : type; - } - } - - if (context == "rule" && /^[\{\};]$/.test(type)) - state.stack.pop(); - if (type == "{") { - if (context == "@media") state.stack[state.stack.length-1] = "@media{"; - else state.stack.push("{"); - } - else if (type == "}") state.stack.pop(); - else if (type == "@media") state.stack.push("@media"); - else if (stream.current() === "font-family") state.stack[state.stack.length-1] = "font-family"; - else if (stream.current() === "background-position") state.stack[state.stack.length-1] = "background-position"; - else if (stream.current() === "border-color") state.stack[state.stack.length-1] = "border-color"; - else if (context == "{" && type != "comment" && type !== "tag") state.stack.push("rule"); - else if (stream.peek() === ":" && stream.current().match(/@|#/) === null) style = type; - if(type === ";" && (state.stack[state.stack.length-1] == "font-family" || state.stack[state.stack.length-1] == "background-position" || state.stack[state.stack.length-1] == "border-color"))state.stack[state.stack.length-1] = stream.current(); - else if(type === "tag" && stream.peek() === ")" && stream.current().match(/\:/) === null){type = null; style = null;} - // ???? - else if((type === "variable" && stream.peek() === ")") || (type === "variable" && stream.eatSpace() && stream.peek() === ")"))return ret(null,stream.current()); - return style; - }, - - indent: function(state, textAfter) { - var n = state.stack.length; - if (/^\}/.test(textAfter)) - n -= state.stack[state.stack.length-1] === "rule" ? 2 : 1; - else if (state.stack[state.stack.length-2] === "{") - n -= state.stack[state.stack.length-1] === "rule" ? 1 : 0; - return state.baseIndent + n * indentUnit; - }, - - electricChars: "}", - blockCommentStart: "/*", - blockCommentEnd: "*/", - lineComment: "//" - }; -}); - -CodeMirror.defineMIME("text/x-less", "less"); -if (!CodeMirror.mimeModes.hasOwnProperty("text/css")) - CodeMirror.defineMIME("text/css", "less"); diff --git a/Source/WebInspectorUI/UserInterface/External/CodeMirror/livescript.js b/Source/WebInspectorUI/UserInterface/External/CodeMirror/livescript.js index c000324b8..1e363f876 100644 --- a/Source/WebInspectorUI/UserInterface/External/CodeMirror/livescript.js +++ b/Source/WebInspectorUI/UserInterface/External/CodeMirror/livescript.js @@ -1,19 +1,32 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + /** * Link to the project's GitHub page: * https://github.com/duralog/CodeMirror */ -(function() { + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + "use strict"; + CodeMirror.defineMode('livescript', function(){ - var tokenBase, external; - tokenBase = function(stream, state){ - var next_rule, nr, i$, len$, r, m; - if (next_rule = state.next || 'start') { + var tokenBase = function(stream, state) { + var next_rule = state.next || "start"; + if (next_rule) { state.next = state.next; - if (Array.isArray(nr = Rules[next_rule])) { - for (i$ = 0, len$ = nr.length; i$ < len$; ++i$) { - r = nr[i$]; - if (r.regex && (m = stream.match(r.regex))) { - state.next = r.next; + var nr = Rules[next_rule]; + if (nr.splice) { + for (var i$ = 0; i$ < nr.length; ++i$) { + var r = nr[i$]; + if (r.regex && stream.match(r.regex)) { + state.next = r.next || state.next; return r.token; } } @@ -33,16 +46,16 @@ stream.next(); return 'error'; }; - external = { + var external = { startState: function(){ return { next: 'start', - lastToken: null + lastToken: {style: null, indent: 0, content: ""} }; }, token: function(stream, state){ - var style; - style = tokenBase(stream, state); + while (stream.pos == stream.start) + var style = tokenBase(stream, state); state.lastToken = { style: style, indent: stream.indentation(), @@ -51,8 +64,7 @@ return style.replace(/\./g, ' '); }, indent: function(state){ - var indentation; - indentation = state.lastToken.indent; + var indentation = state.lastToken.indent; if (state.lastToken.content.match(indenter)) { indentation += 2; } @@ -192,7 +204,7 @@ next: 'start' }, { token: 'text', - regex: '.', + regex: '', next: 'start' } ], @@ -251,17 +263,18 @@ }; for (var idx in Rules) { var r = Rules[idx]; - if (Array.isArray(r)) { + if (r.splice) { for (var i = 0, len = r.length; i < len; ++i) { var rr = r[i]; - if (rr.regex) { + if (typeof rr.regex === 'string') { Rules[idx][i].regex = new RegExp('^' + rr.regex); } } - } else if (r.regex) { + } else if (typeof rr.regex === 'string') { Rules[idx].regex = new RegExp('^' + r.regex); } } -})(); -CodeMirror.defineMIME('text/x-livescript', 'livescript'); + CodeMirror.defineMIME('text/x-livescript', 'livescript'); + +}); diff --git a/Source/WebInspectorUI/UserInterface/External/CodeMirror/mark-selection.js b/Source/WebInspectorUI/UserInterface/External/CodeMirror/mark-selection.js new file mode 100644 index 000000000..5c42d21eb --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/External/CodeMirror/mark-selection.js @@ -0,0 +1,118 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +// Because sometimes you need to mark the selected *text*. +// +// Adds an option 'styleSelectedText' which, when enabled, gives +// selected text the CSS class given as option value, or +// "CodeMirror-selectedtext" when the value is not a string. + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + "use strict"; + + CodeMirror.defineOption("styleSelectedText", false, function(cm, val, old) { + var prev = old && old != CodeMirror.Init; + if (val && !prev) { + cm.state.markedSelection = []; + cm.state.markedSelectionStyle = typeof val == "string" ? val : "CodeMirror-selectedtext"; + reset(cm); + cm.on("cursorActivity", onCursorActivity); + cm.on("change", onChange); + } else if (!val && prev) { + cm.off("cursorActivity", onCursorActivity); + cm.off("change", onChange); + clear(cm); + cm.state.markedSelection = cm.state.markedSelectionStyle = null; + } + }); + + function onCursorActivity(cm) { + cm.operation(function() { update(cm); }); + } + + function onChange(cm) { + if (cm.state.markedSelection.length) + cm.operation(function() { clear(cm); }); + } + + var CHUNK_SIZE = 8; + var Pos = CodeMirror.Pos; + var cmp = CodeMirror.cmpPos; + + function coverRange(cm, from, to, addAt) { + if (cmp(from, to) == 0) return; + var array = cm.state.markedSelection; + var cls = cm.state.markedSelectionStyle; + for (var line = from.line;;) { + var start = line == from.line ? from : Pos(line, 0); + var endLine = line + CHUNK_SIZE, atEnd = endLine >= to.line; + var end = atEnd ? to : Pos(endLine, 0); + var mark = cm.markText(start, end, {className: cls}); + if (addAt == null) array.push(mark); + else array.splice(addAt++, 0, mark); + if (atEnd) break; + line = endLine; + } + } + + function clear(cm) { + var array = cm.state.markedSelection; + for (var i = 0; i < array.length; ++i) array[i].clear(); + array.length = 0; + } + + function reset(cm) { + clear(cm); + var ranges = cm.listSelections(); + for (var i = 0; i < ranges.length; i++) + coverRange(cm, ranges[i].from(), ranges[i].to()); + } + + function update(cm) { + if (!cm.somethingSelected()) return clear(cm); + if (cm.listSelections().length > 1) return reset(cm); + + var from = cm.getCursor("start"), to = cm.getCursor("end"); + + var array = cm.state.markedSelection; + if (!array.length) return coverRange(cm, from, to); + + var coverStart = array[0].find(), coverEnd = array[array.length - 1].find(); + if (!coverStart || !coverEnd || to.line - from.line < CHUNK_SIZE || + cmp(from, coverEnd.to) >= 0 || cmp(to, coverStart.from) <= 0) + return reset(cm); + + while (cmp(from, coverStart.from) > 0) { + array.shift().clear(); + coverStart = array[0].find(); + } + if (cmp(from, coverStart.from) < 0) { + if (coverStart.to.line - from.line < CHUNK_SIZE) { + array.shift().clear(); + coverRange(cm, from, coverStart.to, 0); + } else { + coverRange(cm, from, coverStart.from, 0); + } + } + + while (cmp(to, coverEnd.to) < 0) { + array.pop().clear(); + coverEnd = array[array.length - 1].find(); + } + if (cmp(to, coverEnd.to) > 0) { + if (to.line - coverEnd.from.line < CHUNK_SIZE) { + array.pop().clear(); + coverRange(cm, coverEnd.from, to); + } else { + coverRange(cm, coverEnd.to, to); + } + } + } +}); diff --git a/Source/WebInspectorUI/UserInterface/External/CodeMirror/matchbrackets.js b/Source/WebInspectorUI/UserInterface/External/CodeMirror/matchbrackets.js index 9d9b3882f..76754ed55 100644 --- a/Source/WebInspectorUI/UserInterface/External/CodeMirror/matchbrackets.js +++ b/Source/WebInspectorUI/UserInterface/External/CodeMirror/matchbrackets.js @@ -1,79 +1,111 @@ -(function() { +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { var ie_lt8 = /MSIE \d/.test(navigator.userAgent) && (document.documentMode == null || document.documentMode < 8); var Pos = CodeMirror.Pos; var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<"}; - function findMatchingBracket(cm, where, strict) { - var state = cm.state.matchBrackets; - var maxScanLen = (state && state.maxScanLineLength) || 10000; - var maxScanLines = (state && state.maxScanLines) || 100; - var cur = where || cm.getCursor(), line = cm.getLineHandle(cur.line), pos = cur.ch - 1; + function findMatchingBracket(cm, where, strict, config) { + var line = cm.getLineHandle(where.line), pos = where.ch - 1; var match = (pos >= 0 && matching[line.text.charAt(pos)]) || matching[line.text.charAt(++pos)]; if (!match) return null; - var forward = match.charAt(1) == ">", d = forward ? 1 : -1; - if (strict && forward != (pos == cur.ch)) return null; - var style = cm.getTokenTypeAt(Pos(cur.line, pos + 1)); + var dir = match.charAt(1) == ">" ? 1 : -1; + if (strict && (dir > 0) != (pos == where.ch)) return null; + var style = cm.getTokenTypeAt(Pos(where.line, pos + 1)); + + var found = scanForBracket(cm, Pos(where.line, pos + (dir > 0 ? 1 : 0)), dir, style || null, config); + if (found == null) return null; + return {from: Pos(where.line, pos), to: found && found.pos, + match: found && found.ch == match.charAt(0), forward: dir > 0}; + } - var stack = [line.text.charAt(pos)], re = /[(){}[\]]/; - function scan(line, lineNo, start) { - if (!line.text) return; - var pos = forward ? 0 : line.text.length - 1, end = forward ? line.text.length : -1; - if (line.text.length > maxScanLen) return null; - if (start != null) pos = start + d; - for (; pos != end; pos += d) { - var ch = line.text.charAt(pos); - if (re.test(ch) && cm.getTokenTypeAt(Pos(lineNo, pos + 1)) == style) { + // bracketRegex is used to specify which type of bracket to scan + // should be a regexp, e.g. /[[\]]/ + // + // Note: If "where" is on an open bracket, then this bracket is ignored. + // + // Returns false when no bracket was found, null when it reached + // maxScanLines and gave up + function scanForBracket(cm, where, dir, style, config) { + var maxScanLen = (config && config.maxScanLineLength) || 10000; + var maxScanLines = (config && config.maxScanLines) || 1000; + + var stack = []; + var re = config && config.bracketRegex ? config.bracketRegex : /[(){}[\]]/; + var lineEnd = dir > 0 ? Math.min(where.line + maxScanLines, cm.lastLine() + 1) + : Math.max(cm.firstLine() - 1, where.line - maxScanLines); + for (var lineNo = where.line; lineNo != lineEnd; lineNo += dir) { + var line = cm.getLine(lineNo); + if (!line) continue; + var pos = dir > 0 ? 0 : line.length - 1, end = dir > 0 ? line.length : -1; + if (line.length > maxScanLen) continue; + if (lineNo == where.line) pos = where.ch - (dir < 0 ? 1 : 0); + for (; pos != end; pos += dir) { + var ch = line.charAt(pos); + if (re.test(ch) && (style === undefined || cm.getTokenTypeAt(Pos(lineNo, pos + 1)) == style)) { var match = matching[ch]; - if (match.charAt(1) == ">" == forward) stack.push(ch); - else if (stack.pop() != match.charAt(0)) return {pos: pos, match: false}; - else if (!stack.length) return {pos: pos, match: true}; + if ((match.charAt(1) == ">") == (dir > 0)) stack.push(ch); + else if (!stack.length) return {pos: Pos(lineNo, pos), ch: ch}; + else stack.pop(); } } } - for (var i = cur.line, found, e = forward ? Math.min(i + maxScanLines, cm.lineCount()) : Math.max(-1, i - maxScanLines); i != e; i+=d) { - if (i == cur.line) found = scan(line, i, pos); - else found = scan(cm.getLineHandle(i), i); - if (found) break; - } - return {from: Pos(cur.line, pos), to: found && Pos(i, found.pos), - match: found && found.match, forward: forward}; + return lineNo - dir == (dir > 0 ? cm.lastLine() : cm.firstLine()) ? false : null; } - function matchBrackets(cm, autoclear) { + function matchBrackets(cm, autoclear, config) { // Disable brace matching in long lines, since it'll cause hugely slow updates var maxHighlightLen = cm.state.matchBrackets.maxHighlightLineLength || 1000; - var found = findMatchingBracket(cm); - if (!found || cm.getLine(found.from.line).length > maxHighlightLen || - found.to && cm.getLine(found.to.line).length > maxHighlightLen) - return; + var marks = [], ranges = cm.listSelections(); + for (var i = 0; i < ranges.length; i++) { + var match = ranges[i].empty() && findMatchingBracket(cm, ranges[i].head, false, config); + if (match && cm.getLine(match.from.line).length <= maxHighlightLen) { + var style = match.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket"; + marks.push(cm.markText(match.from, Pos(match.from.line, match.from.ch + 1), {className: style})); + if (match.to && cm.getLine(match.to.line).length <= maxHighlightLen) + marks.push(cm.markText(match.to, Pos(match.to.line, match.to.ch + 1), {className: style})); + } + } + + if (marks.length) { + // Kludge to work around the IE bug from issue #1193, where text + // input stops going to the textare whever this fires. + if (ie_lt8 && cm.state.focused) cm.focus(); - var style = found.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket"; - var one = cm.markText(found.from, Pos(found.from.line, found.from.ch + 1), {className: style}); - var two = found.to && cm.markText(found.to, Pos(found.to.line, found.to.ch + 1), {className: style}); - // Kludge to work around the IE bug from issue #1193, where text - // input stops going to the textare whever this fires. - if (ie_lt8 && cm.state.focused) cm.display.input.focus(); - var clear = function() { - cm.operation(function() { one.clear(); two && two.clear(); }); - }; - if (autoclear) setTimeout(clear, 800); - else return clear; + var clear = function() { + cm.operation(function() { + for (var i = 0; i < marks.length; i++) marks[i].clear(); + }); + }; + if (autoclear) setTimeout(clear, 800); + else return clear; + } } var currentlyHighlighted = null; function doMatchBrackets(cm) { cm.operation(function() { if (currentlyHighlighted) {currentlyHighlighted(); currentlyHighlighted = null;} - if (!cm.somethingSelected()) currentlyHighlighted = matchBrackets(cm, false); + currentlyHighlighted = matchBrackets(cm, false, cm.state.matchBrackets); }); } CodeMirror.defineOption("matchBrackets", false, function(cm, val, old) { - if (old && old != CodeMirror.Init) + if (old && old != CodeMirror.Init) { cm.off("cursorActivity", doMatchBrackets); + if (currentlyHighlighted) {currentlyHighlighted(); currentlyHighlighted = null;} + } if (val) { cm.state.matchBrackets = typeof val == "object" ? val : {}; cm.on("cursorActivity", doMatchBrackets); @@ -81,7 +113,10 @@ }); CodeMirror.defineExtension("matchBrackets", function() {matchBrackets(this, true);}); - CodeMirror.defineExtension("findMatchingBracket", function(pos, strict){ - return findMatchingBracket(this, pos, strict); + CodeMirror.defineExtension("findMatchingBracket", function(pos, strict, config){ + return findMatchingBracket(this, pos, strict, config); + }); + CodeMirror.defineExtension("scanForBracket", function(pos, dir, style, config){ + return scanForBracket(this, pos, dir, style, config); }); -})(); +}); diff --git a/Source/WebInspectorUI/UserInterface/External/CodeMirror/overlay.js b/Source/WebInspectorUI/UserInterface/External/CodeMirror/overlay.js index b7928a7bb..4a9f99a07 100644 --- a/Source/WebInspectorUI/UserInterface/External/CodeMirror/overlay.js +++ b/Source/WebInspectorUI/UserInterface/External/CodeMirror/overlay.js @@ -1,20 +1,34 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + // Utility function that allows modes to be combined. The mode given // as the base argument takes care of most of the normal mode // functionality, but a second (typically simple) mode is used, which // can override the style of text. Both modes get to parse all of the // text, but when both assign a non-null style to a piece of code, the -// overlay wins, unless the combine argument was true, in which case -// the styles are combined. +// overlay wins, unless the combine argument was true and not overridden, +// or state.overlay.combineTokens was true, in which case the styles are +// combined. + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; -// overlayParser is the old, deprecated name -CodeMirror.overlayMode = CodeMirror.overlayParser = function(base, overlay, combine) { +CodeMirror.overlayMode = function(base, overlay, combine) { return { startState: function() { return { base: CodeMirror.startState(base), overlay: CodeMirror.startState(overlay), basePos: 0, baseCur: null, - overlayPos: 0, overlayCur: null + overlayPos: 0, overlayCur: null, + streamSeen: null }; }, copyState: function(state) { @@ -27,6 +41,12 @@ CodeMirror.overlayMode = CodeMirror.overlayParser = function(base, overlay, comb }, token: function(stream, state) { + if (stream != state.streamSeen || + Math.min(state.basePos, state.overlayPos) < stream.start) { + state.streamSeen = stream; + state.basePos = state.overlayPos = stream.start; + } + if (stream.start == state.basePos) { state.baseCur = base.token(stream, state.base); state.basePos = stream.pos; @@ -37,10 +57,14 @@ CodeMirror.overlayMode = CodeMirror.overlayParser = function(base, overlay, comb state.overlayPos = stream.pos; } stream.pos = Math.min(state.basePos, state.overlayPos); - if (stream.eol()) state.basePos = state.overlayPos = 0; + // state.overlay.combineTokens always takes precedence over combine, + // unless set to null if (state.overlayCur == null) return state.baseCur; - if (state.baseCur != null && combine) return state.baseCur + " " + state.overlayCur; + else if (state.baseCur != null && + state.overlay.combineTokens || + combine && state.overlay.combineTokens == null) + return state.baseCur + " " + state.overlayCur; else return state.overlayCur; }, @@ -52,8 +76,15 @@ CodeMirror.overlayMode = CodeMirror.overlayParser = function(base, overlay, comb innerMode: function(state) { return {state: state.base, mode: base}; }, blankLine: function(state) { - if (base.blankLine) base.blankLine(state.base); - if (overlay.blankLine) overlay.blankLine(state.overlay); + var baseToken, overlayToken; + if (base.blankLine) baseToken = base.blankLine(state.base); + if (overlay.blankLine) overlayToken = overlay.blankLine(state.overlay); + + return overlayToken == null ? + baseToken : + (combine && baseToken != null ? baseToken + " " + overlayToken : overlayToken); } }; }; + +}); diff --git a/Source/WebInspectorUI/UserInterface/External/CodeMirror/placeholder.js b/Source/WebInspectorUI/UserInterface/External/CodeMirror/placeholder.js index 748afe727..2f8b1f84a 100644 --- a/Source/WebInspectorUI/UserInterface/External/CodeMirror/placeholder.js +++ b/Source/WebInspectorUI/UserInterface/External/CodeMirror/placeholder.js @@ -1,13 +1,25 @@ -(function() { +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { CodeMirror.defineOption("placeholder", "", function(cm, val, old) { var prev = old && old != CodeMirror.Init; if (val && !prev) { cm.on("blur", onBlur); cm.on("change", onChange); + cm.on("swapDoc", onChange); onChange(cm); } else if (!val && prev) { cm.off("blur", onBlur); cm.off("change", onChange); + cm.off("swapDoc", onChange); clearPlaceholder(cm); var wrapper = cm.getWrapperElement(); wrapper.className = wrapper.className.replace(" CodeMirror-empty", ""); @@ -27,7 +39,9 @@ var elt = cm.state.placeholder = document.createElement("pre"); elt.style.cssText = "height: 0; overflow: visible"; elt.className = "CodeMirror-placeholder"; - elt.appendChild(document.createTextNode(cm.getOption("placeholder"))); + var placeHolder = cm.getOption("placeholder") + if (typeof placeHolder == "string") placeHolder = document.createTextNode(placeHolder) + elt.appendChild(placeHolder) cm.display.lineSpace.insertBefore(elt, cm.display.lineSpace.firstChild); } @@ -45,4 +59,4 @@ function isEmpty(cm) { return (cm.lineCount() === 1) && (cm.getLine(0) === ""); } -})(); +}); diff --git a/Source/WebInspectorUI/UserInterface/External/CodeMirror/runmode.js b/Source/WebInspectorUI/UserInterface/External/CodeMirror/runmode.js index 7aafa2ad8..a51c6d0d5 100644 --- a/Source/WebInspectorUI/UserInterface/External/CodeMirror/runmode.js +++ b/Source/WebInspectorUI/UserInterface/External/CodeMirror/runmode.js @@ -1,9 +1,22 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + CodeMirror.runMode = function(string, modespec, callback, options) { var mode = CodeMirror.getMode(CodeMirror.defaults, modespec); var ie = /MSIE \d/.test(navigator.userAgent); var ie_lt9 = ie && (document.documentMode == null || document.documentMode < 9); - if (callback.nodeType == 1) { + if (callback.appendChild) { var tabSize = (options && options.tabSize) || CodeMirror.defaults.tabSize; var node = callback, col = 0; node.innerHTML = ""; @@ -43,10 +56,11 @@ CodeMirror.runMode = function(string, modespec, callback, options) { }; } - var lines = CodeMirror.splitLines(string), state = CodeMirror.startState(mode); + var lines = CodeMirror.splitLines(string), state = (options && options.state) || CodeMirror.startState(mode); for (var i = 0, e = lines.length; i < e; ++i) { if (i) callback("\n"); var stream = new CodeMirror.StringStream(lines[i]); + if (!stream.string && mode.blankLine) mode.blankLine(state); while (!stream.eol()) { var style = mode.token(stream, state); callback(stream.current(), style, i, stream.start, state); @@ -54,3 +68,5 @@ CodeMirror.runMode = function(string, modespec, callback, options) { } } }; + +}); diff --git a/Source/WebInspectorUI/UserInterface/External/CodeMirror/sass.js b/Source/WebInspectorUI/UserInterface/External/CodeMirror/sass.js index 9c9a0dae0..6973ece29 100644 --- a/Source/WebInspectorUI/UserInterface/External/CodeMirror/sass.js +++ b/Source/WebInspectorUI/UserInterface/External/CodeMirror/sass.js @@ -1,300 +1,379 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + CodeMirror.defineMode("sass", function(config) { - var tokenRegexp = function(words){ + function tokenRegexp(words) { return new RegExp("^" + words.join("|")); - }; + } var keywords = ["true", "false", "null", "auto"]; var keywordsRegexp = new RegExp("^" + keywords.join("|")); - var operators = ["\\(", "\\)", "=", ">", "<", "==", ">=", "<=", "\\+", "-", "\\!=", "/", "\\*", "%", "and", "or", "not"]; + var operators = ["\\(", "\\)", "=", ">", "<", "==", ">=", "<=", "\\+", "-", + "\\!=", "/", "\\*", "%", "and", "or", "not", ";","\\{","\\}",":"]; var opRegexp = tokenRegexp(operators); - var pseudoElementsRegexp = /^::?[\w\-]+/; + var pseudoElementsRegexp = /^::?[a-zA-Z_][\w\-]*/; - var urlTokens = function(stream, state){ + function urlTokens(stream, state) { var ch = stream.peek(); - if (ch === ")"){ + if (ch === ")") { stream.next(); state.tokenizer = tokenBase; return "operator"; - }else if (ch === "("){ + } else if (ch === "(") { stream.next(); stream.eatSpace(); return "operator"; - }else if (ch === "'" || ch === '"'){ + } else if (ch === "'" || ch === '"') { state.tokenizer = buildStringTokenizer(stream.next()); return "string"; - }else{ + } else { state.tokenizer = buildStringTokenizer(")", false); return "string"; } - }; - var multilineComment = function(stream, state) { - if (stream.skipTo("*/")){ - stream.next(); - stream.next(); - state.tokenizer = tokenBase; - }else { - stream.next(); - } + } + function comment(indentation, multiLine) { + return function(stream, state) { + if (stream.sol() && stream.indentation() <= indentation) { + state.tokenizer = tokenBase; + return tokenBase(stream, state); + } - return "comment"; - }; + if (multiLine && stream.skipTo("*/")) { + stream.next(); + stream.next(); + state.tokenizer = tokenBase; + } else { + stream.skipToEnd(); + } - var buildStringTokenizer = function(quote, greedy){ - if(greedy == null){ greedy = true; } + return "comment"; + }; + } - function stringTokenizer(stream, state){ + function buildStringTokenizer(quote, greedy) { + if (greedy == null) { greedy = true; } + + function stringTokenizer(stream, state) { var nextChar = stream.next(); var peekChar = stream.peek(); var previousChar = stream.string.charAt(stream.pos-2); var endingString = ((nextChar !== "\\" && peekChar === quote) || (nextChar === quote && previousChar !== "\\")); - /* - console.log("previousChar: " + previousChar); - console.log("nextChar: " + nextChar); - console.log("peekChar: " + peekChar); - console.log("ending: " + endingString); - */ - - if (endingString){ + if (endingString) { if (nextChar !== quote && greedy) { stream.next(); } state.tokenizer = tokenBase; return "string"; - }else if (nextChar === "#" && peekChar === "{"){ + } else if (nextChar === "#" && peekChar === "{") { state.tokenizer = buildInterpolationTokenizer(stringTokenizer); stream.next(); return "operator"; - }else { + } else { return "string"; } } return stringTokenizer; - }; + } - var buildInterpolationTokenizer = function(currentTokenizer){ - return function(stream, state){ - if (stream.peek() === "}"){ + function buildInterpolationTokenizer(currentTokenizer) { + return function(stream, state) { + if (stream.peek() === "}") { stream.next(); state.tokenizer = currentTokenizer; return "operator"; - }else{ + } else { return tokenBase(stream, state); } }; - }; + } - var indent = function(state){ - if (state.indentCount == 0){ + function indent(state) { + if (state.indentCount == 0) { state.indentCount++; var lastScopeOffset = state.scopes[0].offset; var currentOffset = lastScopeOffset + config.indentUnit; state.scopes.unshift({ offset:currentOffset }); } - }; + } - var dedent = function(state){ - if (state.scopes.length == 1) { return; } + function dedent(state) { + if (state.scopes.length == 1) return; state.scopes.shift(); - }; + } - var tokenBase = function(stream, state) { + function tokenBase(stream, state) { var ch = stream.peek(); - // Single line Comment - if (stream.match('//')) { - stream.skipToEnd(); - return "comment"; + // Comment + if (stream.match("/*")) { + state.tokenizer = comment(stream.indentation(), true); + return state.tokenizer(stream, state); } - - // Multiline Comment - if (stream.match('/*')){ - state.tokenizer = multilineComment; + if (stream.match("//")) { + state.tokenizer = comment(stream.indentation(), false); return state.tokenizer(stream, state); } // Interpolation - if (stream.match('#{')){ - state.tokenizer = buildInterpolationTokenizer(tokenBase); + if (stream.match("#{")) { + state.tokenizer = buildInterpolationTokenizer(tokenBase); return "operator"; } - if (ch === "."){ + // Strings + if (ch === '"' || ch === "'") { stream.next(); + state.tokenizer = buildStringTokenizer(ch); + return "string"; + } - // Match class selectors - if (stream.match(/^[\w-]+/)){ - indent(state); - return "atom"; - }else if (stream.peek() === "#"){ - indent(state); - return "atom"; - }else{ - return "operator"; + if(!state.cursorHalf){// state.cursorHalf === 0 + // first half i.e. before : for key-value pairs + // including selectors + + if (ch === ".") { + stream.next(); + if (stream.match(/^[\w-]+/)) { + indent(state); + return "atom"; + } else if (stream.peek() === "#") { + indent(state); + return "atom"; + } } - } - if (ch === "#"){ - stream.next(); + if (ch === "#") { + stream.next(); + // ID selectors + if (stream.match(/^[\w-]+/)) { + indent(state); + return "atom"; + } + if (stream.peek() === "#") { + indent(state); + return "atom"; + } + } - // Hex numbers - if (stream.match(/[0-9a-fA-F]{6}|[0-9a-fA-F]{3}/)){ - return "number"; + // Variables + if (ch === "$") { + stream.next(); + stream.eatWhile(/[\w-]/); + return "variable-2"; } - // ID selectors - if (stream.match(/^[\w-]+/)){ - indent(state); + // Numbers + if (stream.match(/^-?[0-9\.]+/)) + return "number"; + + // Units + if (stream.match(/^(px|em|in)\b/)) + return "unit"; + + if (stream.match(keywordsRegexp)) + return "keyword"; + + if (stream.match(/^url/) && stream.peek() === "(") { + state.tokenizer = urlTokens; return "atom"; } - if (stream.peek() === "#"){ - indent(state); - return "atom"; + if (ch === "=") { + // Match shortcut mixin definition + if (stream.match(/^=[\w-]+/)) { + indent(state); + return "meta"; + } } - } - // Numbers - if (stream.match(/^-?[0-9\.]+/)){ - return "number"; - } + if (ch === "+") { + // Match shortcut mixin definition + if (stream.match(/^\+[\w-]+/)){ + return "variable-3"; + } + } - // Units - if (stream.match(/^(px|em|in)\b/)){ - return "unit"; - } + if(ch === "@"){ + if(stream.match(/@extend/)){ + if(!stream.match(/\s*[\w]/)) + dedent(state); + } + } - if (stream.match(keywordsRegexp)){ - return "keyword"; - } - if (stream.match(/^url/) && stream.peek() === "("){ - state.tokenizer = urlTokens; - return "atom"; - } + // Indent Directives + if (stream.match(/^@(else if|if|media|else|for|each|while|mixin|function)/)) { + indent(state); + return "meta"; + } - // Variables - if (ch === "$"){ - stream.next(); - stream.eatWhile(/[\w-]/); + // Other Directives + if (ch === "@") { + stream.next(); + stream.eatWhile(/[\w-]/); + return "meta"; + } + + if (stream.eatWhile(/[\w-]/)){ + if(stream.match(/ *: *[\w-\+\$#!\("']/,false)){ + return "property"; + } + else if(stream.match(/ *:/,false)){ + indent(state); + state.cursorHalf = 1; + return "atom"; + } + else if(stream.match(/ *,/,false)){ + return "atom"; + } + else{ + indent(state); + return "atom"; + } + } - if (stream.peek() === ":"){ + if(ch === ":"){ + if (stream.match(pseudoElementsRegexp)){ // could be a pseudo-element + return "keyword"; + } stream.next(); - return "variable-2"; - }else{ - return "variable-3"; + state.cursorHalf=1; + return "operator"; } - } - if (ch === "!"){ - stream.next(); + } // cursorHalf===0 ends here + else{ - if (stream.match(/^[\w]+/)){ - return "keyword"; + if (ch === "#") { + stream.next(); + // Hex numbers + if (stream.match(/[0-9a-fA-F]{6}|[0-9a-fA-F]{3}/)){ + if(!stream.peek()){ + state.cursorHalf = 0; + } + return "number"; + } } - return "operator"; - } + // Numbers + if (stream.match(/^-?[0-9\.]+/)){ + if(!stream.peek()){ + state.cursorHalf = 0; + } + return "number"; + } - if (ch === "="){ - stream.next(); + // Units + if (stream.match(/^(px|em|in)\b/)){ + if(!stream.peek()){ + state.cursorHalf = 0; + } + return "unit"; + } - // Match shortcut mixin definition - if (stream.match(/^[\w-]+/)){ - indent(state); - return "meta"; - }else { - return "operator"; + if (stream.match(keywordsRegexp)){ + if(!stream.peek()){ + state.cursorHalf = 0; + } + return "keyword"; } - } - if (ch === "+"){ - stream.next(); + if (stream.match(/^url/) && stream.peek() === "(") { + state.tokenizer = urlTokens; + if(!stream.peek()){ + state.cursorHalf = 0; + } + return "atom"; + } - // Match shortcut mixin definition - if (stream.match(/^[\w-]+/)){ + // Variables + if (ch === "$") { + stream.next(); + stream.eatWhile(/[\w-]/); + if(!stream.peek()){ + state.cursorHalf = 0; + } return "variable-3"; - }else { - return "operator"; } - } - // Indent Directives - if (stream.match(/^@(else if|if|media|else|for|each|while|mixin|function)/)){ - indent(state); - return "meta"; - } + // bang character for !important, !default, etc. + if (ch === "!") { + stream.next(); + if(!stream.peek()){ + state.cursorHalf = 0; + } + return stream.match(/^[\w]+/) ? "keyword": "operator"; + } - // Other Directives - if (ch === "@"){ - stream.next(); - stream.eatWhile(/[\w-]/); - return "meta"; - } + if (stream.match(opRegexp)){ + if(!stream.peek()){ + state.cursorHalf = 0; + } + return "operator"; + } - // Strings - if (ch === '"' || ch === "'"){ - stream.next(); - state.tokenizer = buildStringTokenizer(ch); - return "string"; - } + // attributes + if (stream.eatWhile(/[\w-]/)) { + if(!stream.peek()){ + state.cursorHalf = 0; + } + return "attribute"; + } - // Pseudo element selectors - if (ch == ':' && stream.match(pseudoElementsRegexp)){ - return "keyword"; - } + //stream.eatSpace(); + if(!stream.peek()){ + state.cursorHalf = 0; + return null; + } - // atoms - if (stream.eatWhile(/[\w-&]/)){ - // matches a property definition - if (stream.peek() === ":" && !stream.match(pseudoElementsRegexp, false)) - return "property"; - else - return "atom"; - } + } // else ends here - if (stream.match(opRegexp)){ + if (stream.match(opRegexp)) return "operator"; - } // If we haven't returned by now, we move 1 character // and return an error stream.next(); return null; - }; + } - var tokenLexer = function(stream, state) { - if (stream.sol()){ - state.indentCount = 0; - } + function tokenLexer(stream, state) { + if (stream.sol()) state.indentCount = 0; var style = state.tokenizer(stream, state); var current = stream.current(); - if (current === "@return"){ + if (current === "@return" || current === "}"){ dedent(state); } - if (style === "atom"){ - indent(state); - } - - if (style !== null){ + if (style !== null) { var startOfToken = stream.pos - current.length; + var withCurrentIndent = startOfToken + (config.indentUnit * state.indentCount); var newScopes = []; - for (var i = 0; i < state.scopes.length; i++){ + for (var i = 0; i < state.scopes.length; i++) { var scope = state.scopes[i]; - if (scope.offset <= withCurrentIndent){ + if (scope.offset <= withCurrentIndent) newScopes.push(scope); - } } state.scopes = newScopes; @@ -302,13 +381,16 @@ CodeMirror.defineMode("sass", function(config) { return style; - }; + } return { startState: function() { return { tokenizer: tokenBase, - scopes: [{offset: 0, type: 'sass'}], + scopes: [{offset: 0, type: "sass"}], + indentCount: 0, + cursorHalf: 0, // cursor half tells us if cursor lies after (1) + // or before (0) colon (well... more or less) definedVars: [], definedMixins: [] }; @@ -328,3 +410,5 @@ CodeMirror.defineMode("sass", function(config) { }); CodeMirror.defineMIME("text/x-sass", "sass"); + +}); diff --git a/Source/WebInspectorUI/UserInterface/External/CodeMirror/searchcursor.js b/Source/WebInspectorUI/UserInterface/External/CodeMirror/searchcursor.js index c034d5865..b70242ee4 100644 --- a/Source/WebInspectorUI/UserInterface/External/CodeMirror/searchcursor.js +++ b/Source/WebInspectorUI/UserInterface/External/CodeMirror/searchcursor.js @@ -1,4 +1,15 @@ -(function(){ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + "use strict"; var Pos = CodeMirror.Pos; function SearchCursor(doc, query, pos, caseFold) { @@ -47,6 +58,7 @@ match: match}; }; } else { // String query + var origQuery = query; if (caseFold) query = query.toLowerCase(); var fold = caseFold ? function(str){return str.toLowerCase();} : function(str){return str;}; var target = query.split("\n"); @@ -58,33 +70,45 @@ this.matches = function() {}; } else { this.matches = function(reverse, pos) { - var line = fold(doc.getLine(pos.line)), len = query.length, match; - if (reverse ? (pos.ch >= len && (match = line.lastIndexOf(query, pos.ch - len)) != -1) - : (match = line.indexOf(query, pos.ch)) != -1) - return {from: Pos(pos.line, match), - to: Pos(pos.line, match + len)}; + if (reverse) { + var orig = doc.getLine(pos.line).slice(0, pos.ch), line = fold(orig); + var match = line.lastIndexOf(query); + if (match > -1) { + match = adjustPos(orig, line, match); + return {from: Pos(pos.line, match), to: Pos(pos.line, match + origQuery.length)}; + } + } else { + var orig = doc.getLine(pos.line).slice(pos.ch), line = fold(orig); + var match = line.indexOf(query); + if (match > -1) { + match = adjustPos(orig, line, match) + pos.ch; + return {from: Pos(pos.line, match), to: Pos(pos.line, match + origQuery.length)}; + } + } }; } } else { + var origTarget = origQuery.split("\n"); this.matches = function(reverse, pos) { - var ln = pos.line, idx = (reverse ? target.length - 1 : 0), match = target[idx], line = fold(doc.getLine(ln)); - var offsetA = (reverse ? line.indexOf(match) + match.length : line.lastIndexOf(match)); - if (reverse ? offsetA > pos.ch || offsetA != match.length - : offsetA < pos.ch || offsetA != line.length - match.length) - return; - for (;;) { - if (reverse ? !ln : ln == doc.lineCount() - 1) return; - line = fold(doc.getLine(ln += reverse ? -1 : 1)); - match = target[reverse ? --idx : ++idx]; - if (idx > 0 && idx < target.length - 1) { - if (line != match) return; - else continue; - } - var offsetB = (reverse ? line.lastIndexOf(match) : line.indexOf(match) + match.length); - if (reverse ? offsetB != line.length - match.length : offsetB != match.length) - return; - var start = Pos(pos.line, offsetA), end = Pos(ln, offsetB); - return {from: reverse ? end : start, to: reverse ? start : end}; + var last = target.length - 1; + if (reverse) { + if (pos.line - (target.length - 1) < doc.firstLine()) return; + if (fold(doc.getLine(pos.line).slice(0, origTarget[last].length)) != target[target.length - 1]) return; + var to = Pos(pos.line, origTarget[last].length); + for (var ln = pos.line - 1, i = last - 1; i >= 1; --i, --ln) + if (target[i] != fold(doc.getLine(ln))) return; + var line = doc.getLine(ln), cut = line.length - origTarget[0].length; + if (fold(line.slice(cut)) != target[0]) return; + return {from: Pos(ln, cut), to: to}; + } else { + if (pos.line + (target.length - 1) > doc.lastLine()) return; + var line = doc.getLine(pos.line), cut = line.length - origTarget[0].length; + if (fold(line.slice(cut)) != target[0]) return; + var from = Pos(pos.line, cut); + for (var ln = pos.line + 1, i = 1; i < last; ++i, ++ln) + if (target[i] != fold(doc.getLine(ln))) return; + if (fold(doc.getLine(ln).slice(0, origTarget[last].length)) != target[last]) return; + return {from: from, to: Pos(ln, origTarget[last].length)}; } }; } @@ -106,7 +130,6 @@ for (;;) { if (this.pos = this.matches(reverse, pos)) { - if (!this.pos.from || !this.pos.to) { console.log(this.matches, this.pos); } this.atOccurrence = true; return this.pos.match || true; } @@ -125,19 +148,42 @@ from: function() {if (this.atOccurrence) return this.pos.from;}, to: function() {if (this.atOccurrence) return this.pos.to;}, - replace: function(newText) { + replace: function(newText, origin) { if (!this.atOccurrence) return; var lines = CodeMirror.splitLines(newText); - this.doc.replaceRange(lines, this.pos.from, this.pos.to); + this.doc.replaceRange(lines, this.pos.from, this.pos.to, origin); this.pos.to = Pos(this.pos.from.line + lines.length - 1, lines[lines.length - 1].length + (lines.length == 1 ? this.pos.from.ch : 0)); } }; + // Maps a position in a case-folded line back to a position in the original line + // (compensating for codepoints increasing in number during folding) + function adjustPos(orig, folded, pos) { + if (orig.length == folded.length) return pos; + for (var pos1 = Math.min(pos, orig.length);;) { + var len1 = orig.slice(0, pos1).toLowerCase().length; + if (len1 < pos) ++pos1; + else if (len1 > pos) --pos1; + else return pos1; + } + } + CodeMirror.defineExtension("getSearchCursor", function(query, pos, caseFold) { return new SearchCursor(this.doc, query, pos, caseFold); }); CodeMirror.defineDocExtension("getSearchCursor", function(query, pos, caseFold) { return new SearchCursor(this, query, pos, caseFold); }); -})(); + + CodeMirror.defineExtension("selectMatches", function(query, caseFold) { + var ranges = []; + var cur = this.getSearchCursor(query, this.getCursor("from"), caseFold); + while (cur.findNext()) { + if (CodeMirror.cmpPos(cur.to(), this.getCursor("to")) > 0) break; + ranges.push({anchor: cur.from(), head: cur.to()}); + } + if (ranges.length) + this.setSelections(ranges, 0); + }); +}); diff --git a/Source/WebInspectorUI/UserInterface/External/CodeMirror/sql.js b/Source/WebInspectorUI/UserInterface/External/CodeMirror/sql.js index 3be68caa1..32ced3e9d 100644 --- a/Source/WebInspectorUI/UserInterface/External/CodeMirror/sql.js +++ b/Source/WebInspectorUI/UserInterface/External/CodeMirror/sql.js @@ -1,3 +1,16 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + CodeMirror.defineMode("sql", function(config, parserConfig) { "use strict"; @@ -19,13 +32,13 @@ CodeMirror.defineMode("sql", function(config, parserConfig) { if (result !== false) return result; } - if (support.hexNumber == true && + if (support.hexNumber && ((ch == "0" && stream.match(/^[xX][0-9a-fA-F]+/)) || (ch == "x" || ch == "X") && stream.match(/^'[0-9a-fA-F]+'/))) { // hex // ref: http://dev.mysql.com/doc/refman/5.5/en/hexadecimal-literals.html return "number"; - } else if (support.binaryNumber == true && + } else if (support.binaryNumber && (((ch == "b" || ch == "B") && stream.match(/^'[01]+'/)) || (ch == "0" && stream.match(/^b[01]+/)))) { // bitstring @@ -35,7 +48,7 @@ CodeMirror.defineMode("sql", function(config, parserConfig) { // numbers // ref: http://dev.mysql.com/doc/refman/5.5/en/number-literals.html stream.match(/^[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?/); - support.decimallessFloat == true && stream.eat('.'); + support.decimallessFloat && stream.eat('.'); return "number"; } else if (ch == "?" && (stream.eatSpace() || stream.eol() || stream.eat(";"))) { // placeholders @@ -45,14 +58,14 @@ CodeMirror.defineMode("sql", function(config, parserConfig) { // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html state.tokenize = tokenLiteral(ch); return state.tokenize(stream, state); - } else if ((((support.nCharCast == true && (ch == "n" || ch == "N")) - || (support.charsetCast == true && ch == "_" && stream.match(/[a-z][a-z0-9]*/i))) + } else if ((((support.nCharCast && (ch == "n" || ch == "N")) + || (support.charsetCast && ch == "_" && stream.match(/[a-z][a-z0-9]*/i))) && (stream.peek() == "'" || stream.peek() == '"'))) { // charset casting: _utf8'str', N'str', n'str' // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html return "keyword"; } else if (/^[\(\),\;\[\]]/.test(ch)) { - // no highlightning + // no highlighting return null; } else if (support.commentSlashSlash && ch == "/" && stream.eat("/")) { // 1-line comment @@ -71,12 +84,12 @@ CodeMirror.defineMode("sql", function(config, parserConfig) { return state.tokenize(stream, state); } else if (ch == ".") { // .1 for 0.1 - if (support.zerolessFloat == true && stream.match(/^(?:\d+(?:e[+-]?\d+)?)/i)) { + if (support.zerolessFloat && stream.match(/^(?:\d+(?:e[+-]?\d+)?)/i)) { return "number"; } // .table_name (ODBC) // // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html - if (support.ODBCdotTable == true && stream.match(/^[a-zA-Z_]+/)) { + if (support.ODBCdotTable && stream.match(/^[a-zA-Z_]+/)) { return "variable-2"; } } else if (operatorChars.test(ch)) { @@ -178,8 +191,9 @@ CodeMirror.defineMode("sql", function(config, parserConfig) { indent: function(state, textAfter) { var cx = state.context; if (!cx) return CodeMirror.Pass; - if (cx.align) return cx.col + (textAfter.charAt(0) == cx.type ? 0 : 1); - else return cx.indent + config.indentUnit; + var closing = textAfter.charAt(0) == cx.type; + if (cx.align) return cx.col + (closing ? 0 : 1); + else return cx.indent + (closing ? 0 : config.indentUnit); }, blockCommentStart: "/*", @@ -199,7 +213,8 @@ CodeMirror.defineMode("sql", function(config, parserConfig) { while ((ch = stream.next()) != null) { if (ch == "`" && !stream.eat("`")) return "variable-2"; } - return null; + stream.backUp(stream.current().length - 1); + return stream.eatWhile(/\w/) ? "variable-2" : null; } // variable token @@ -242,7 +257,7 @@ CodeMirror.defineMode("sql", function(config, parserConfig) { } // these keywords are used by all SQL dialects (however, a mode can still overwrite it) - var sqlKeywords = "alter and as asc between by count create delete desc distinct drop from having in insert into is join like not on or order select set table union update values where "; + var sqlKeywords = "alter and as asc between by count create delete desc distinct drop from group having in insert into is join like not on or order select set table union update values where limit "; // turn a space-separated list into an array function set(str) { @@ -265,7 +280,7 @@ CodeMirror.defineMode("sql", function(config, parserConfig) { CodeMirror.defineMIME("text/x-mssql", { name: "sql", client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"), - keywords: set(sqlKeywords + "begin trigger proc view index for add constraint key primary foreign collate clustered nonclustered"), + keywords: set(sqlKeywords + "begin trigger proc view index for add constraint key primary foreign collate clustered nonclustered declare exec"), builtin: set("bigint numeric bit smallint decimal smallmoney int tinyint money float real char varchar text nchar nvarchar ntext binary varbinary image cursor timestamp hierarchyid uniqueidentifier sql_variant xml table "), atoms: set("false true null unknown"), operatorChars: /^[*+\-%<>!=]/, @@ -278,7 +293,7 @@ CodeMirror.defineMode("sql", function(config, parserConfig) { CodeMirror.defineMIME("text/x-mysql", { name: "sql", client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"), - keywords: set(sqlKeywords + "accessible action add after algorithm all analyze asensitive at authors auto_increment autocommit avg avg_row_length before binary binlog both btree cache call cascade cascaded case catalog_name chain change changed character check checkpoint checksum class_origin client_statistics close coalesce code collate collation collations column columns comment commit committed completion concurrent condition connection consistent constraint contains continue contributors convert cross current current_date current_time current_timestamp current_user cursor data database databases day_hour day_microsecond day_minute day_second deallocate dec declare default delay_key_write delayed delimiter des_key_file describe deterministic dev_pop dev_samp deviance diagnostics directory disable discard distinctrow div dual dumpfile each elseif enable enclosed end ends engine engines enum errors escape escaped even event events every execute exists exit explain extended fast fetch field fields first flush for force foreign found_rows full fulltext function general get global grant grants group groupby_concat handler hash help high_priority hosts hour_microsecond hour_minute hour_second if ignore ignore_server_ids import index index_statistics infile inner innodb inout insensitive insert_method install interval invoker isolation iterate key keys kill language last leading leave left level limit linear lines list load local localtime localtimestamp lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters match max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modifies modify mutex mysql_errno natural next no no_write_to_binlog offline offset one online open optimize option optionally out outer outfile pack_keys parser partition partitions password phase plugin plugins prepare preserve prev primary privileges procedure processlist profile profiles purge query quick range read read_write reads real rebuild recover references regexp relaylog release remove rename reorganize repair repeatable replace require resignal restrict resume return returns revoke right rlike rollback rollup row row_format rtree savepoint schedule schema schema_name schemas second_microsecond security sensitive separator serializable server session share show signal slave slow smallint snapshot soname spatial specific sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result sqlexception sqlstate sqlwarning ssl start starting starts status std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace temporary terminated to trailing transaction trigger triggers truncate uncommitted undo uninstall unique unlock upgrade usage use use_frm user user_resources user_statistics using utc_date utc_time utc_timestamp value variables varying view views warnings when while with work write xa xor year_month zerofill begin do then else loop repeat"), + keywords: set(sqlKeywords + "accessible action add after algorithm all analyze asensitive at authors auto_increment autocommit avg avg_row_length before binary binlog both btree cache call cascade cascaded case catalog_name chain change changed character check checkpoint checksum class_origin client_statistics close coalesce code collate collation collations column columns comment commit committed completion concurrent condition connection consistent constraint contains continue contributors convert cross current current_date current_time current_timestamp current_user cursor data database databases day_hour day_microsecond day_minute day_second deallocate dec declare default delay_key_write delayed delimiter des_key_file describe deterministic dev_pop dev_samp deviance diagnostics directory disable discard distinctrow div dual dumpfile each elseif enable enclosed end ends engine engines enum errors escape escaped even event events every execute exists exit explain extended fast fetch field fields first flush for force foreign found_rows full fulltext function general get global grant grants group group_concat handler hash help high_priority hosts hour_microsecond hour_minute hour_second if ignore ignore_server_ids import index index_statistics infile inner innodb inout insensitive insert_method install interval invoker isolation iterate key keys kill language last leading leave left level limit linear lines list load local localtime localtimestamp lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters match max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modifies modify mutex mysql_errno natural next no no_write_to_binlog offline offset one online open optimize option optionally out outer outfile pack_keys parser partition partitions password phase plugin plugins prepare preserve prev primary privileges procedure processlist profile profiles purge query quick range read read_write reads real rebuild recover references regexp relaylog release remove rename reorganize repair repeatable replace require resignal restrict resume return returns revoke right rlike rollback rollup row row_format rtree savepoint schedule schema schema_name schemas second_microsecond security sensitive separator serializable server session share show signal slave slow smallint snapshot soname spatial specific sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result sqlexception sqlstate sqlwarning ssl start starting starts status std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace temporary terminated to trailing transaction trigger triggers truncate uncommitted undo uninstall unique unlock upgrade usage use use_frm user user_resources user_statistics using utc_date utc_time utc_timestamp value variables varying view views warnings when while with work write xa xor year_month zerofill begin do then else loop repeat"), builtin: set("bool boolean bit blob decimal double float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision date datetime year unsigned signed numeric"), atoms: set("false true null unknown"), operatorChars: /^[*+\-%<>!=&|^]/, @@ -312,9 +327,9 @@ CodeMirror.defineMode("sql", function(config, parserConfig) { CodeMirror.defineMIME("text/x-cassandra", { name: "sql", client: { }, - keywords: set("use select from using consistency where limit first reversed first and in insert into values using consistency ttl update set delete truncate begin batch apply create keyspace with columnfamily primary key index on drop alter type add any one quorum all local_quorum each_quorum"), - builtin: set("ascii bigint blob boolean counter decimal double float int text timestamp uuid varchar varint"), - atoms: set("false true"), + keywords: set("add all allow alter and any apply as asc authorize batch begin by clustering columnfamily compact consistency count create custom delete desc distinct drop each_quorum exists filtering from grant if in index insert into key keyspace keyspaces level limit local_one local_quorum modify nan norecursive nosuperuser not of on one order password permission permissions primary quorum rename revoke schema select set storage superuser table three to token truncate ttl two type unlogged update use user users using values where with writetime"), + builtin: set("ascii bigint blob boolean counter decimal double float frozen inet int list map static text timestamp timeuuid tuple uuid varchar varint"), + atoms: set("false true infinity NaN"), operatorChars: /^[<>=]/, dateSQL: { }, support: set("commentSlashSlash decimallessFloat"), @@ -325,22 +340,55 @@ CodeMirror.defineMode("sql", function(config, parserConfig) { CodeMirror.defineMIME("text/x-plsql", { name: "sql", client: set("appinfo arraysize autocommit autoprint autorecovery autotrace blockterminator break btitle cmdsep colsep compatibility compute concat copycommit copytypecheck define describe echo editfile embedded escape exec execute feedback flagger flush heading headsep instance linesize lno loboffset logsource long longchunksize markup native newpage numformat numwidth pagesize pause pno recsep recsepchar release repfooter repheader serveroutput shiftinout show showmode size spool sqlblanklines sqlcase sqlcode sqlcontinue sqlnumber sqlpluscompatibility sqlprefix sqlprompt sqlterminator suffix tab term termout time timing trimout trimspool ttitle underline verify version wrap"), - keywords: set("abort accept access add all alter and any array arraylen as asc assert assign at attributes audit authorization avg base_table begin between binary_integer body boolean by case cast char char_base check close cluster clusters colauth column comment commit compress connect connected constant constraint crash create current currval cursor data_base database date dba deallocate debugoff debugon decimal declare default definition delay delete desc digits dispose distinct do drop else elsif enable end entry escape exception exception_init exchange exclusive exists exit external fast fetch file for force form from function generic goto grant group having identified if immediate in increment index indexes indicator initial initrans insert interface intersect into is key level library like limited local lock log logging long loop master maxextents maxtrans member minextents minus mislabel mode modify multiset new next no noaudit nocompress nologging noparallel not nowait number_base object of off offline on online only open option or order out package parallel partition pctfree pctincrease pctused pls_integer positive positiven pragma primary prior private privileges procedure public raise range raw read rebuild record ref references refresh release rename replace resource restrict return returning reverse revoke rollback row rowid rowlabel rownum rows run savepoint schema segment select separate session set share snapshot some space split sql start statement storage subtype successful synonym tabauth table tables tablespace task terminate then to trigger truncate type union unique unlimited unrecoverable unusable update use using validate value values variable view views when whenever where while with work"), - builtin: set("bfile blob character clob dec float int integer mlslabel natural naturaln nchar nclob number numeric nvarchar2 real rowtype signtype smallint string varchar varchar2 abs acos add_months ascii asin atan atan2 average bfilename ceil chartorowid chr concat convert cos cosh count decode deref dual dump dup_val_on_index empty error exp false floor found glb greatest hextoraw initcap instr instrb isopen last_day least lenght lenghtb ln lower lpad ltrim lub make_ref max min mod months_between new_time next_day nextval nls_charset_decl_len nls_charset_id nls_charset_name nls_initcap nls_lower nls_sort nls_upper nlssort no_data_found notfound null nvl others power rawtohex reftohex round rowcount rowidtochar rpad rtrim sign sin sinh soundex sqlcode sqlerrm sqrt stddev substr substrb sum sysdate tan tanh to_char to_date to_label to_multi_byte to_number to_single_byte translate true trunc uid upper user userenv variance vsize"), + keywords: set("abort accept access add all alter and any array arraylen as asc assert assign at attributes audit authorization avg base_table begin between binary_integer body boolean by case cast char char_base check close cluster clusters colauth column comment commit compress connect connected constant constraint crash create current currval cursor data_base database date dba deallocate debugoff debugon decimal declare default definition delay delete desc digits dispose distinct do drop else elseif elsif enable end entry escape exception exception_init exchange exclusive exists exit external fast fetch file for force form from function generic goto grant group having identified if immediate in increment index indexes indicator initial initrans insert interface intersect into is key level library like limited local lock log logging long loop master maxextents maxtrans member minextents minus mislabel mode modify multiset new next no noaudit nocompress nologging noparallel not nowait number_base object of off offline on online only open option or order out package parallel partition pctfree pctincrease pctused pls_integer positive positiven pragma primary prior private privileges procedure public raise range raw read rebuild record ref references refresh release rename replace resource restrict return returning returns reverse revoke rollback row rowid rowlabel rownum rows run savepoint schema segment select separate session set share snapshot some space split sql start statement storage subtype successful synonym tabauth table tables tablespace task terminate then to trigger truncate type union unique unlimited unrecoverable unusable update use using validate value values variable view views when whenever where while with work"), + builtin: set("abs acos add_months ascii asin atan atan2 average bfile bfilename bigserial bit blob ceil character chartorowid chr clob concat convert cos cosh count dec decode deref dual dump dup_val_on_index empty error exp false float floor found glb greatest hextoraw initcap instr instrb int integer isopen last_day least length lengthb ln lower lpad ltrim lub make_ref max min mlslabel mod months_between natural naturaln nchar nclob new_time next_day nextval nls_charset_decl_len nls_charset_id nls_charset_name nls_initcap nls_lower nls_sort nls_upper nlssort no_data_found notfound null number numeric nvarchar2 nvl others power rawtohex real reftohex round rowcount rowidtochar rowtype rpad rtrim serial sign signtype sin sinh smallint soundex sqlcode sqlerrm sqrt stddev string substr substrb sum sysdate tan tanh to_char text to_date to_label to_multi_byte to_number to_single_byte translate true trunc uid unlogged upper user userenv varchar varchar2 variance varying vsize xml"), operatorChars: /^[*+\-%<>!=~]/, dateSQL: set("date time timestamp"), support: set("doubleQuote nCharCast zerolessFloat binaryNumber hexNumber") }); + + // Created to support specific hive keywords + CodeMirror.defineMIME("text/x-hive", { + name: "sql", + keywords: set("select alter $elem$ $key$ $value$ add after all analyze and archive as asc before between binary both bucket buckets by cascade case cast change cluster clustered clusterstatus collection column columns comment compute concatenate continue create cross cursor data database databases dbproperties deferred delete delimited desc describe directory disable distinct distribute drop else enable end escaped exclusive exists explain export extended external false fetch fields fileformat first format formatted from full function functions grant group having hold_ddltime idxproperties if import in index indexes inpath inputdriver inputformat insert intersect into is items join keys lateral left like limit lines load local location lock locks mapjoin materialized minus msck no_drop nocompress not of offline on option or order out outer outputdriver outputformat overwrite partition partitioned partitions percent plus preserve procedure purge range rcfile read readonly reads rebuild recordreader recordwriter recover reduce regexp rename repair replace restrict revoke right rlike row schema schemas semi sequencefile serde serdeproperties set shared show show_database sort sorted ssl statistics stored streamtable table tables tablesample tblproperties temporary terminated textfile then tmp to touch transform trigger true unarchive undo union uniquejoin unlock update use using utc utc_tmestamp view when where while with"), + builtin: set("bool boolean long timestamp tinyint smallint bigint int float double date datetime unsigned string array struct map uniontype"), + atoms: set("false true null unknown"), + operatorChars: /^[*+\-%<>!=]/, + dateSQL: set("date timestamp"), + support: set("ODBCdotTable doubleQuote binaryNumber hexNumber") + }); + + CodeMirror.defineMIME("text/x-pgsql", { + name: "sql", + client: set("source"), + // http://www.postgresql.org/docs/9.5/static/sql-keywords-appendix.html + keywords: set(sqlKeywords + "a abort abs absent absolute access according action ada add admin after aggregate all allocate also always analyse analyze any are array array_agg array_max_cardinality asensitive assertion assignment asymmetric at atomic attribute attributes authorization avg backward base64 before begin begin_frame begin_partition bernoulli binary bit_length blob blocked bom both breadth c cache call called cardinality cascade cascaded case cast catalog catalog_name ceil ceiling chain characteristics characters character_length character_set_catalog character_set_name character_set_schema char_length check checkpoint class class_origin clob close cluster coalesce cobol collate collation collation_catalog collation_name collation_schema collect column columns column_name command_function command_function_code comment comments commit committed concurrently condition condition_number configuration conflict connect connection connection_name constraint constraints constraint_catalog constraint_name constraint_schema constructor contains content continue control conversion convert copy corr corresponding cost covar_pop covar_samp cross csv cube cume_dist current current_catalog current_date current_default_transform_group current_path current_role current_row current_schema current_time current_timestamp current_transform_group_for_type current_user cursor cursor_name cycle data database datalink datetime_interval_code datetime_interval_precision day db deallocate dec declare default defaults deferrable deferred defined definer degree delimiter delimiters dense_rank depth deref derived describe descriptor deterministic diagnostics dictionary disable discard disconnect dispatch dlnewcopy dlpreviouscopy dlurlcomplete dlurlcompleteonly dlurlcompletewrite dlurlpath dlurlpathonly dlurlpathwrite dlurlscheme dlurlserver dlvalue do document domain dynamic dynamic_function dynamic_function_code each element else empty enable encoding encrypted end end-exec end_frame end_partition enforced enum equals escape event every except exception exclude excluding exclusive exec execute exists exp explain expression extension external extract false family fetch file filter final first first_value flag float floor following for force foreign fortran forward found frame_row free freeze fs full function functions fusion g general generated get global go goto grant granted greatest grouping groups handler header hex hierarchy hold hour id identity if ignore ilike immediate immediately immutable implementation implicit import including increment indent index indexes indicator inherit inherits initially inline inner inout input insensitive instance instantiable instead integrity intersect intersection invoker isnull isolation k key key_member key_type label lag language large last last_value lateral lead leading leakproof least left length level library like_regex link listen ln load local localtime localtimestamp location locator lock locked logged lower m map mapping match matched materialized max maxvalue max_cardinality member merge message_length message_octet_length message_text method min minute minvalue mod mode modifies module month more move multiset mumps name names namespace national natural nchar nclob nesting new next nfc nfd nfkc nfkd nil no none normalize normalized nothing notify notnull nowait nth_value ntile null nullable nullif nulls number object occurrences_regex octets octet_length of off offset oids old only open operator option options ordering ordinality others out outer output over overlaps overlay overriding owned owner p pad parameter parameter_mode parameter_name parameter_ordinal_position parameter_specific_catalog parameter_specific_name parameter_specific_schema parser partial partition pascal passing passthrough password percent percentile_cont percentile_disc percent_rank period permission placing plans pli policy portion position position_regex power precedes preceding prepare prepared preserve primary prior privileges procedural procedure program public quote range rank read reads reassign recheck recovery recursive ref references referencing refresh regr_avgx regr_avgy regr_count regr_intercept regr_r2 regr_slope regr_sxx regr_sxy regr_syy reindex relative release rename repeatable replace replica requiring reset respect restart restore restrict result return returned_cardinality returned_length returned_octet_length returned_sqlstate returning returns revoke right role rollback rollup routine routine_catalog routine_name routine_schema row rows row_count row_number rule savepoint scale schema schema_name scope scope_catalog scope_name scope_schema scroll search second section security selective self sensitive sequence sequences serializable server server_name session session_user setof sets share show similar simple size skip snapshot some source space specific specifictype specific_name sql sqlcode sqlerror sqlexception sqlstate sqlwarning sqrt stable standalone start state statement static statistics stddev_pop stddev_samp stdin stdout storage strict strip structure style subclass_origin submultiset substring substring_regex succeeds sum symmetric sysid system system_time system_user t tables tablesample tablespace table_name temp template temporary then ties timezone_hour timezone_minute to token top_level_count trailing transaction transactions_committed transactions_rolled_back transaction_active transform transforms translate translate_regex translation treat trigger trigger_catalog trigger_name trigger_schema trim trim_array true truncate trusted type types uescape unbounded uncommitted under unencrypted unique unknown unlink unlisten unlogged unnamed unnest until untyped upper uri usage user user_defined_type_catalog user_defined_type_code user_defined_type_name user_defined_type_schema using vacuum valid validate validator value value_of varbinary variadic var_pop var_samp verbose version versioning view views volatile when whenever whitespace width_bucket window within work wrapper write xmlagg xmlattributes xmlbinary xmlcast xmlcomment xmlconcat xmldeclaration xmldocument xmlelement xmlexists xmlforest xmliterate xmlnamespaces xmlparse xmlpi xmlquery xmlroot xmlschema xmlserialize xmltable xmltext xmlvalidate year yes loop repeat"), + // http://www.postgresql.org/docs/9.5/static/datatype.html + builtin: set("bigint int8 bigserial serial8 bit varying varbit boolean bool box bytea character char varchar cidr circle date double precision float8 inet integer int int4 interval json jsonb line lseg macaddr money numeric decimal path pg_lsn point polygon real float4 smallint int2 smallserial serial2 serial serial4 text time without zone with timetz timestamp timestamptz tsquery tsvector txid_snapshot uuid xml"), + atoms: set("false true null unknown"), + operatorChars: /^[*+\-%<>!=&|^\/#@?~]/, + dateSQL: set("date time timestamp"), + support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber nCharCast charsetCast") + }); + + // Google's SQL-like query language, GQL + CodeMirror.defineMIME("text/x-gql", { + name: "sql", + keywords: set("ancestor and asc by contains desc descendant distinct from group has in is limit offset on order select superset where"), + atoms: set("false true"), + builtin: set("blob datetime first key __key__ string integer double boolean null"), + operatorChars: /^[*+\-%<>!=]/ + }); }()); +}); + /* How Properties of Mime Types are used by SQL Mode ================================================= keywords: A list of keywords you want to be highlighted. - functions: - A list of function names you want to be highlighted. builtin: A list of builtin types you want to be highlighted (if you want types to be of class "builtin" instead of "keyword"). operatorChars: diff --git a/Source/WebInspectorUI/UserInterface/External/CodeMirror/sublime.js b/Source/WebInspectorUI/UserInterface/External/CodeMirror/sublime.js new file mode 100644 index 000000000..c5d2906bc --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/External/CodeMirror/sublime.js @@ -0,0 +1,588 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +// A rough approximation of Sublime Text's keybindings +// Depends on addon/search/searchcursor.js and optionally addon/dialog/dialogs.js + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../lib/codemirror"), require("../addon/search/searchcursor"), require("../addon/edit/matchbrackets")); + else if (typeof define == "function" && define.amd) // AMD + define(["../lib/codemirror", "../addon/search/searchcursor", "../addon/edit/matchbrackets"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + "use strict"; + + var map = CodeMirror.keyMap.sublime = {fallthrough: "default"}; + var cmds = CodeMirror.commands; + var Pos = CodeMirror.Pos; + var mac = CodeMirror.keyMap["default"] == CodeMirror.keyMap.macDefault; + var ctrl = mac ? "Cmd-" : "Ctrl-"; + + // This is not exactly Sublime's algorithm. I couldn't make heads or tails of that. + function findPosSubword(doc, start, dir) { + if (dir < 0 && start.ch == 0) return doc.clipPos(Pos(start.line - 1)); + var line = doc.getLine(start.line); + if (dir > 0 && start.ch >= line.length) return doc.clipPos(Pos(start.line + 1, 0)); + var state = "start", type; + for (var pos = start.ch, e = dir < 0 ? 0 : line.length, i = 0; pos != e; pos += dir, i++) { + var next = line.charAt(dir < 0 ? pos - 1 : pos); + var cat = next != "_" && CodeMirror.isWordChar(next) ? "w" : "o"; + if (cat == "w" && next.toUpperCase() == next) cat = "W"; + if (state == "start") { + if (cat != "o") { state = "in"; type = cat; } + } else if (state == "in") { + if (type != cat) { + if (type == "w" && cat == "W" && dir < 0) pos--; + if (type == "W" && cat == "w" && dir > 0) { type = "w"; continue; } + break; + } + } + } + return Pos(start.line, pos); + } + + function moveSubword(cm, dir) { + cm.extendSelectionsBy(function(range) { + if (cm.display.shift || cm.doc.extend || range.empty()) + return findPosSubword(cm.doc, range.head, dir); + else + return dir < 0 ? range.from() : range.to(); + }); + } + + var goSubwordCombo = mac ? "Ctrl-" : "Alt-"; + + cmds[map[goSubwordCombo + "Left"] = "goSubwordLeft"] = function(cm) { moveSubword(cm, -1); }; + cmds[map[goSubwordCombo + "Right"] = "goSubwordRight"] = function(cm) { moveSubword(cm, 1); }; + + if (mac) map["Cmd-Left"] = "goLineStartSmart"; + + var scrollLineCombo = mac ? "Ctrl-Alt-" : "Ctrl-"; + + cmds[map[scrollLineCombo + "Up"] = "scrollLineUp"] = function(cm) { + var info = cm.getScrollInfo(); + if (!cm.somethingSelected()) { + var visibleBottomLine = cm.lineAtHeight(info.top + info.clientHeight, "local"); + if (cm.getCursor().line >= visibleBottomLine) + cm.execCommand("goLineUp"); + } + cm.scrollTo(null, info.top - cm.defaultTextHeight()); + }; + cmds[map[scrollLineCombo + "Down"] = "scrollLineDown"] = function(cm) { + var info = cm.getScrollInfo(); + if (!cm.somethingSelected()) { + var visibleTopLine = cm.lineAtHeight(info.top, "local")+1; + if (cm.getCursor().line <= visibleTopLine) + cm.execCommand("goLineDown"); + } + cm.scrollTo(null, info.top + cm.defaultTextHeight()); + }; + + cmds[map["Shift-" + ctrl + "L"] = "splitSelectionByLine"] = function(cm) { + var ranges = cm.listSelections(), lineRanges = []; + for (var i = 0; i < ranges.length; i++) { + var from = ranges[i].from(), to = ranges[i].to(); + for (var line = from.line; line <= to.line; ++line) + if (!(to.line > from.line && line == to.line && to.ch == 0)) + lineRanges.push({anchor: line == from.line ? from : Pos(line, 0), + head: line == to.line ? to : Pos(line)}); + } + cm.setSelections(lineRanges, 0); + }; + + map["Shift-Tab"] = "indentLess"; + + cmds[map["Esc"] = "singleSelectionTop"] = function(cm) { + var range = cm.listSelections()[0]; + cm.setSelection(range.anchor, range.head, {scroll: false}); + }; + + cmds[map[ctrl + "L"] = "selectLine"] = function(cm) { + var ranges = cm.listSelections(), extended = []; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + extended.push({anchor: Pos(range.from().line, 0), + head: Pos(range.to().line + 1, 0)}); + } + cm.setSelections(extended); + }; + + map["Shift-Ctrl-K"] = "deleteLine"; + + function insertLine(cm, above) { + if (cm.isReadOnly()) return CodeMirror.Pass + cm.operation(function() { + var len = cm.listSelections().length, newSelection = [], last = -1; + for (var i = 0; i < len; i++) { + var head = cm.listSelections()[i].head; + if (head.line <= last) continue; + var at = Pos(head.line + (above ? 0 : 1), 0); + cm.replaceRange("\n", at, null, "+insertLine"); + cm.indentLine(at.line, null, true); + newSelection.push({head: at, anchor: at}); + last = head.line + 1; + } + cm.setSelections(newSelection); + }); + cm.execCommand("indentAuto"); + } + + cmds[map[ctrl + "Enter"] = "insertLineAfter"] = function(cm) { return insertLine(cm, false); }; + + cmds[map["Shift-" + ctrl + "Enter"] = "insertLineBefore"] = function(cm) { return insertLine(cm, true); }; + + function wordAt(cm, pos) { + var start = pos.ch, end = start, line = cm.getLine(pos.line); + while (start && CodeMirror.isWordChar(line.charAt(start - 1))) --start; + while (end < line.length && CodeMirror.isWordChar(line.charAt(end))) ++end; + return {from: Pos(pos.line, start), to: Pos(pos.line, end), word: line.slice(start, end)}; + } + + cmds[map[ctrl + "D"] = "selectNextOccurrence"] = function(cm) { + var from = cm.getCursor("from"), to = cm.getCursor("to"); + var fullWord = cm.state.sublimeFindFullWord == cm.doc.sel; + if (CodeMirror.cmpPos(from, to) == 0) { + var word = wordAt(cm, from); + if (!word.word) return; + cm.setSelection(word.from, word.to); + fullWord = true; + } else { + var text = cm.getRange(from, to); + var query = fullWord ? new RegExp("\\b" + text + "\\b") : text; + var cur = cm.getSearchCursor(query, to); + if (cur.findNext()) { + cm.addSelection(cur.from(), cur.to()); + } else { + cur = cm.getSearchCursor(query, Pos(cm.firstLine(), 0)); + if (cur.findNext()) + cm.addSelection(cur.from(), cur.to()); + } + } + if (fullWord) + cm.state.sublimeFindFullWord = cm.doc.sel; + }; + + var mirror = "(){}[]"; + function selectBetweenBrackets(cm) { + var ranges = cm.listSelections(), newRanges = [] + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i], pos = range.head, opening = cm.scanForBracket(pos, -1); + if (!opening) return false; + for (;;) { + var closing = cm.scanForBracket(pos, 1); + if (!closing) return false; + if (closing.ch == mirror.charAt(mirror.indexOf(opening.ch) + 1)) { + newRanges.push({anchor: Pos(opening.pos.line, opening.pos.ch + 1), + head: closing.pos}); + break; + } + pos = Pos(closing.pos.line, closing.pos.ch + 1); + } + } + cm.setSelections(newRanges); + return true; + } + + cmds[map["Shift-" + ctrl + "Space"] = "selectScope"] = function(cm) { + selectBetweenBrackets(cm) || cm.execCommand("selectAll"); + }; + cmds[map["Shift-" + ctrl + "M"] = "selectBetweenBrackets"] = function(cm) { + if (!selectBetweenBrackets(cm)) return CodeMirror.Pass; + }; + + cmds[map[ctrl + "M"] = "goToBracket"] = function(cm) { + cm.extendSelectionsBy(function(range) { + var next = cm.scanForBracket(range.head, 1); + if (next && CodeMirror.cmpPos(next.pos, range.head) != 0) return next.pos; + var prev = cm.scanForBracket(range.head, -1); + return prev && Pos(prev.pos.line, prev.pos.ch + 1) || range.head; + }); + }; + + var swapLineCombo = mac ? "Cmd-Ctrl-" : "Shift-Ctrl-"; + + cmds[map[swapLineCombo + "Up"] = "swapLineUp"] = function(cm) { + if (cm.isReadOnly()) return CodeMirror.Pass + var ranges = cm.listSelections(), linesToMove = [], at = cm.firstLine() - 1, newSels = []; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i], from = range.from().line - 1, to = range.to().line; + newSels.push({anchor: Pos(range.anchor.line - 1, range.anchor.ch), + head: Pos(range.head.line - 1, range.head.ch)}); + if (range.to().ch == 0 && !range.empty()) --to; + if (from > at) linesToMove.push(from, to); + else if (linesToMove.length) linesToMove[linesToMove.length - 1] = to; + at = to; + } + cm.operation(function() { + for (var i = 0; i < linesToMove.length; i += 2) { + var from = linesToMove[i], to = linesToMove[i + 1]; + var line = cm.getLine(from); + cm.replaceRange("", Pos(from, 0), Pos(from + 1, 0), "+swapLine"); + if (to > cm.lastLine()) + cm.replaceRange("\n" + line, Pos(cm.lastLine()), null, "+swapLine"); + else + cm.replaceRange(line + "\n", Pos(to, 0), null, "+swapLine"); + } + cm.setSelections(newSels); + cm.scrollIntoView(); + }); + }; + + cmds[map[swapLineCombo + "Down"] = "swapLineDown"] = function(cm) { + if (cm.isReadOnly()) return CodeMirror.Pass + var ranges = cm.listSelections(), linesToMove = [], at = cm.lastLine() + 1; + for (var i = ranges.length - 1; i >= 0; i--) { + var range = ranges[i], from = range.to().line + 1, to = range.from().line; + if (range.to().ch == 0 && !range.empty()) from--; + if (from < at) linesToMove.push(from, to); + else if (linesToMove.length) linesToMove[linesToMove.length - 1] = to; + at = to; + } + cm.operation(function() { + for (var i = linesToMove.length - 2; i >= 0; i -= 2) { + var from = linesToMove[i], to = linesToMove[i + 1]; + var line = cm.getLine(from); + if (from == cm.lastLine()) + cm.replaceRange("", Pos(from - 1), Pos(from), "+swapLine"); + else + cm.replaceRange("", Pos(from, 0), Pos(from + 1, 0), "+swapLine"); + cm.replaceRange(line + "\n", Pos(to, 0), null, "+swapLine"); + } + cm.scrollIntoView(); + }); + }; + + cmds[map[ctrl + "/"] = "toggleCommentIndented"] = function(cm) { + cm.toggleComment({ indent: true }); + } + + cmds[map[ctrl + "J"] = "joinLines"] = function(cm) { + var ranges = cm.listSelections(), joined = []; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i], from = range.from(); + var start = from.line, end = range.to().line; + while (i < ranges.length - 1 && ranges[i + 1].from().line == end) + end = ranges[++i].to().line; + joined.push({start: start, end: end, anchor: !range.empty() && from}); + } + cm.operation(function() { + var offset = 0, ranges = []; + for (var i = 0; i < joined.length; i++) { + var obj = joined[i]; + var anchor = obj.anchor && Pos(obj.anchor.line - offset, obj.anchor.ch), head; + for (var line = obj.start; line <= obj.end; line++) { + var actual = line - offset; + if (line == obj.end) head = Pos(actual, cm.getLine(actual).length + 1); + if (actual < cm.lastLine()) { + cm.replaceRange(" ", Pos(actual), Pos(actual + 1, /^\s*/.exec(cm.getLine(actual + 1))[0].length)); + ++offset; + } + } + ranges.push({anchor: anchor || head, head: head}); + } + cm.setSelections(ranges, 0); + }); + }; + + cmds[map["Shift-" + ctrl + "D"] = "duplicateLine"] = function(cm) { + cm.operation(function() { + var rangeCount = cm.listSelections().length; + for (var i = 0; i < rangeCount; i++) { + var range = cm.listSelections()[i]; + if (range.empty()) + cm.replaceRange(cm.getLine(range.head.line) + "\n", Pos(range.head.line, 0)); + else + cm.replaceRange(cm.getRange(range.from(), range.to()), range.from()); + } + cm.scrollIntoView(); + }); + }; + + if (!mac) map[ctrl + "T"] = "transposeChars"; + + function sortLines(cm, caseSensitive) { + if (cm.isReadOnly()) return CodeMirror.Pass + var ranges = cm.listSelections(), toSort = [], selected; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + if (range.empty()) continue; + var from = range.from().line, to = range.to().line; + while (i < ranges.length - 1 && ranges[i + 1].from().line == to) + to = range[++i].to().line; + toSort.push(from, to); + } + if (toSort.length) selected = true; + else toSort.push(cm.firstLine(), cm.lastLine()); + + cm.operation(function() { + var ranges = []; + for (var i = 0; i < toSort.length; i += 2) { + var from = toSort[i], to = toSort[i + 1]; + var start = Pos(from, 0), end = Pos(to); + var lines = cm.getRange(start, end, false); + if (caseSensitive) + lines.sort(); + else + lines.sort(function(a, b) { + var au = a.toUpperCase(), bu = b.toUpperCase(); + if (au != bu) { a = au; b = bu; } + return a < b ? -1 : a == b ? 0 : 1; + }); + cm.replaceRange(lines, start, end); + if (selected) ranges.push({anchor: start, head: end}); + } + if (selected) cm.setSelections(ranges, 0); + }); + } + + cmds[map["F9"] = "sortLines"] = function(cm) { sortLines(cm, true); }; + cmds[map[ctrl + "F9"] = "sortLinesInsensitive"] = function(cm) { sortLines(cm, false); }; + + cmds[map["F2"] = "nextBookmark"] = function(cm) { + var marks = cm.state.sublimeBookmarks; + if (marks) while (marks.length) { + var current = marks.shift(); + var found = current.find(); + if (found) { + marks.push(current); + return cm.setSelection(found.from, found.to); + } + } + }; + + cmds[map["Shift-F2"] = "prevBookmark"] = function(cm) { + var marks = cm.state.sublimeBookmarks; + if (marks) while (marks.length) { + marks.unshift(marks.pop()); + var found = marks[marks.length - 1].find(); + if (!found) + marks.pop(); + else + return cm.setSelection(found.from, found.to); + } + }; + + cmds[map[ctrl + "F2"] = "toggleBookmark"] = function(cm) { + var ranges = cm.listSelections(); + var marks = cm.state.sublimeBookmarks || (cm.state.sublimeBookmarks = []); + for (var i = 0; i < ranges.length; i++) { + var from = ranges[i].from(), to = ranges[i].to(); + var found = cm.findMarks(from, to); + for (var j = 0; j < found.length; j++) { + if (found[j].sublimeBookmark) { + found[j].clear(); + for (var k = 0; k < marks.length; k++) + if (marks[k] == found[j]) + marks.splice(k--, 1); + break; + } + } + if (j == found.length) + marks.push(cm.markText(from, to, {sublimeBookmark: true, clearWhenEmpty: false})); + } + }; + + cmds[map["Shift-" + ctrl + "F2"] = "clearBookmarks"] = function(cm) { + var marks = cm.state.sublimeBookmarks; + if (marks) for (var i = 0; i < marks.length; i++) marks[i].clear(); + marks.length = 0; + }; + + cmds[map["Alt-F2"] = "selectBookmarks"] = function(cm) { + var marks = cm.state.sublimeBookmarks, ranges = []; + if (marks) for (var i = 0; i < marks.length; i++) { + var found = marks[i].find(); + if (!found) + marks.splice(i--, 0); + else + ranges.push({anchor: found.from, head: found.to}); + } + if (ranges.length) + cm.setSelections(ranges, 0); + }; + + map["Alt-Q"] = "wrapLines"; + + var cK = ctrl + "K "; + + function modifyWordOrSelection(cm, mod) { + cm.operation(function() { + var ranges = cm.listSelections(), indices = [], replacements = []; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + if (range.empty()) { indices.push(i); replacements.push(""); } + else replacements.push(mod(cm.getRange(range.from(), range.to()))); + } + cm.replaceSelections(replacements, "around", "case"); + for (var i = indices.length - 1, at; i >= 0; i--) { + var range = ranges[indices[i]]; + if (at && CodeMirror.cmpPos(range.head, at) > 0) continue; + var word = wordAt(cm, range.head); + at = word.from; + cm.replaceRange(mod(word.word), word.from, word.to); + } + }); + } + + map[cK + ctrl + "Backspace"] = "delLineLeft"; + + cmds[map["Backspace"] = "smartBackspace"] = function(cm) { + if (cm.somethingSelected()) return CodeMirror.Pass; + + cm.operation(function() { + var cursors = cm.listSelections(); + var indentUnit = cm.getOption("indentUnit"); + + for (var i = cursors.length - 1; i >= 0; i--) { + var cursor = cursors[i].head; + var toStartOfLine = cm.getRange({line: cursor.line, ch: 0}, cursor); + var column = CodeMirror.countColumn(toStartOfLine, null, cm.getOption("tabSize")); + + // Delete by one character by default + var deletePos = cm.findPosH(cursor, -1, "char", false); + + if (toStartOfLine && !/\S/.test(toStartOfLine) && column % indentUnit == 0) { + var prevIndent = new Pos(cursor.line, + CodeMirror.findColumn(toStartOfLine, column - indentUnit, indentUnit)); + + // Smart delete only if we found a valid prevIndent location + if (prevIndent.ch != cursor.ch) deletePos = prevIndent; + } + + cm.replaceRange("", deletePos, cursor, "+delete"); + } + }); + }; + + cmds[map[cK + ctrl + "K"] = "delLineRight"] = function(cm) { + cm.operation(function() { + var ranges = cm.listSelections(); + for (var i = ranges.length - 1; i >= 0; i--) + cm.replaceRange("", ranges[i].anchor, Pos(ranges[i].to().line), "+delete"); + cm.scrollIntoView(); + }); + }; + + cmds[map[cK + ctrl + "U"] = "upcaseAtCursor"] = function(cm) { + modifyWordOrSelection(cm, function(str) { return str.toUpperCase(); }); + }; + cmds[map[cK + ctrl + "L"] = "downcaseAtCursor"] = function(cm) { + modifyWordOrSelection(cm, function(str) { return str.toLowerCase(); }); + }; + + cmds[map[cK + ctrl + "Space"] = "setSublimeMark"] = function(cm) { + if (cm.state.sublimeMark) cm.state.sublimeMark.clear(); + cm.state.sublimeMark = cm.setBookmark(cm.getCursor()); + }; + cmds[map[cK + ctrl + "A"] = "selectToSublimeMark"] = function(cm) { + var found = cm.state.sublimeMark && cm.state.sublimeMark.find(); + if (found) cm.setSelection(cm.getCursor(), found); + }; + cmds[map[cK + ctrl + "W"] = "deleteToSublimeMark"] = function(cm) { + var found = cm.state.sublimeMark && cm.state.sublimeMark.find(); + if (found) { + var from = cm.getCursor(), to = found; + if (CodeMirror.cmpPos(from, to) > 0) { var tmp = to; to = from; from = tmp; } + cm.state.sublimeKilled = cm.getRange(from, to); + cm.replaceRange("", from, to); + } + }; + cmds[map[cK + ctrl + "X"] = "swapWithSublimeMark"] = function(cm) { + var found = cm.state.sublimeMark && cm.state.sublimeMark.find(); + if (found) { + cm.state.sublimeMark.clear(); + cm.state.sublimeMark = cm.setBookmark(cm.getCursor()); + cm.setCursor(found); + } + }; + cmds[map[cK + ctrl + "Y"] = "sublimeYank"] = function(cm) { + if (cm.state.sublimeKilled != null) + cm.replaceSelection(cm.state.sublimeKilled, null, "paste"); + }; + + map[cK + ctrl + "G"] = "clearBookmarks"; + cmds[map[cK + ctrl + "C"] = "showInCenter"] = function(cm) { + var pos = cm.cursorCoords(null, "local"); + cm.scrollTo(null, (pos.top + pos.bottom) / 2 - cm.getScrollInfo().clientHeight / 2); + }; + + var selectLinesCombo = mac ? "Ctrl-Shift-" : "Ctrl-Alt-"; + cmds[map[selectLinesCombo + "Up"] = "selectLinesUpward"] = function(cm) { + cm.operation(function() { + var ranges = cm.listSelections(); + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + if (range.head.line > cm.firstLine()) + cm.addSelection(Pos(range.head.line - 1, range.head.ch)); + } + }); + }; + cmds[map[selectLinesCombo + "Down"] = "selectLinesDownward"] = function(cm) { + cm.operation(function() { + var ranges = cm.listSelections(); + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + if (range.head.line < cm.lastLine()) + cm.addSelection(Pos(range.head.line + 1, range.head.ch)); + } + }); + }; + + function getTarget(cm) { + var from = cm.getCursor("from"), to = cm.getCursor("to"); + if (CodeMirror.cmpPos(from, to) == 0) { + var word = wordAt(cm, from); + if (!word.word) return; + from = word.from; + to = word.to; + } + return {from: from, to: to, query: cm.getRange(from, to), word: word}; + } + + function findAndGoTo(cm, forward) { + var target = getTarget(cm); + if (!target) return; + var query = target.query; + var cur = cm.getSearchCursor(query, forward ? target.to : target.from); + + if (forward ? cur.findNext() : cur.findPrevious()) { + cm.setSelection(cur.from(), cur.to()); + } else { + cur = cm.getSearchCursor(query, forward ? Pos(cm.firstLine(), 0) + : cm.clipPos(Pos(cm.lastLine()))); + if (forward ? cur.findNext() : cur.findPrevious()) + cm.setSelection(cur.from(), cur.to()); + else if (target.word) + cm.setSelection(target.from, target.to); + } + }; + cmds[map[ctrl + "F3"] = "findUnder"] = function(cm) { findAndGoTo(cm, true); }; + cmds[map["Shift-" + ctrl + "F3"] = "findUnderPrevious"] = function(cm) { findAndGoTo(cm,false); }; + cmds[map["Alt-F3"] = "findAllUnder"] = function(cm) { + var target = getTarget(cm); + if (!target) return; + var cur = cm.getSearchCursor(target.query); + var matches = []; + var primaryIndex = -1; + while (cur.findNext()) { + matches.push({anchor: cur.from(), head: cur.to()}); + if (cur.from().line <= target.from.line && cur.from().ch <= target.from.ch) + primaryIndex++; + } + cm.setSelections(matches, primaryIndex); + }; + + map["Shift-" + ctrl + "["] = "fold"; + map["Shift-" + ctrl + "]"] = "unfold"; + map[cK + ctrl + "0"] = map[cK + ctrl + "J"] = "unfoldAll"; + + map[ctrl + "I"] = "findIncremental"; + map["Shift-" + ctrl + "I"] = "findIncrementalReverse"; + map[ctrl + "H"] = "replace"; + map["F3"] = "findNext"; + map["Shift-F3"] = "findPrev"; + + CodeMirror.normalizeKeyMap(map); +}); diff --git a/Source/WebInspectorUI/UserInterface/External/CodeMirror/xml.js b/Source/WebInspectorUI/UserInterface/External/CodeMirror/xml.js index 4f49e07fa..f987a3a3c 100644 --- a/Source/WebInspectorUI/UserInterface/External/CodeMirror/xml.js +++ b/Source/WebInspectorUI/UserInterface/External/CodeMirror/xml.js @@ -1,51 +1,69 @@ -CodeMirror.defineMode("xml", function(config, parserConfig) { - var indentUnit = config.indentUnit; - var multilineTagIndentFactor = parserConfig.multilineTagIndentFactor || 1; - var multilineTagIndentPastTag = parserConfig.multilineTagIndentPastTag || true; +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE - var Kludges = parserConfig.htmlMode ? { - autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true, - 'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true, - 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true, - 'track': true, 'wbr': true}, - implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true, - 'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true, - 'th': true, 'tr': true}, - contextGrabbers: { - 'dd': {'dd': true, 'dt': true}, - 'dt': {'dd': true, 'dt': true}, - 'li': {'li': true}, - 'option': {'option': true, 'optgroup': true}, - 'optgroup': {'optgroup': true}, - 'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true, - 'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true, - 'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true, - 'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true, - 'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true}, - 'rp': {'rp': true, 'rt': true}, - 'rt': {'rp': true, 'rt': true}, - 'tbody': {'tbody': true, 'tfoot': true}, - 'td': {'td': true, 'th': true}, - 'tfoot': {'tbody': true}, - 'th': {'td': true, 'th': true}, - 'thead': {'tbody': true, 'tfoot': true}, - 'tr': {'tr': true} - }, - doNotIndent: {"pre": true}, - allowUnquoted: true, - allowMissing: true - } : { - autoSelfClosers: {}, - implicitlyClosed: {}, - contextGrabbers: {}, - doNotIndent: {}, - allowUnquoted: false, - allowMissing: false - }; - var alignCDATA = parserConfig.alignCDATA; +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +var htmlConfig = { + autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true, + 'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true, + 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true, + 'track': true, 'wbr': true, 'menuitem': true}, + implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true, + 'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true, + 'th': true, 'tr': true}, + contextGrabbers: { + 'dd': {'dd': true, 'dt': true}, + 'dt': {'dd': true, 'dt': true}, + 'li': {'li': true}, + 'option': {'option': true, 'optgroup': true}, + 'optgroup': {'optgroup': true}, + 'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true, + 'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true, + 'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true, + 'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true, + 'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true}, + 'rp': {'rp': true, 'rt': true}, + 'rt': {'rp': true, 'rt': true}, + 'tbody': {'tbody': true, 'tfoot': true}, + 'td': {'td': true, 'th': true}, + 'tfoot': {'tbody': true}, + 'th': {'td': true, 'th': true}, + 'thead': {'tbody': true, 'tfoot': true}, + 'tr': {'tr': true} + }, + doNotIndent: {"pre": true}, + allowUnquoted: true, + allowMissing: true, + caseFold: true +} + +var xmlConfig = { + autoSelfClosers: {}, + implicitlyClosed: {}, + contextGrabbers: {}, + doNotIndent: {}, + allowUnquoted: false, + allowMissing: false, + caseFold: false +} + +CodeMirror.defineMode("xml", function(editorConf, config_) { + var indentUnit = editorConf.indentUnit + var config = {} + var defaults = config_.htmlMode ? htmlConfig : xmlConfig + for (var prop in defaults) config[prop] = defaults[prop] + for (var prop in config_) config[prop] = config_[prop] // Return variables for tokenizers - var tagName, type; + var type, setStyle; function inText(stream, state) { function chain(parser) { @@ -72,14 +90,9 @@ CodeMirror.defineMode("xml", function(config, parserConfig) { state.tokenize = inBlock("meta", "?>"); return "meta"; } else { - var isClose = stream.eat("/"); - tagName = ""; - var c; - while ((c = stream.eat(/[^\s\u00a0=<>\"\'\/?]/))) tagName += c; - if (!tagName) return "tag error"; - type = isClose ? "closeTag" : "openTag"; + type = stream.eat("/") ? "closeTag" : "openTag"; state.tokenize = inTag; - return "tag"; + return "tag bracket"; } } else if (ch == "&") { var ok; @@ -98,26 +111,29 @@ CodeMirror.defineMode("xml", function(config, parserConfig) { return null; } } + inText.isInText = true; function inTag(stream, state) { var ch = stream.next(); if (ch == ">" || (ch == "/" && stream.eat(">"))) { state.tokenize = inText; type = ch == ">" ? "endTag" : "selfcloseTag"; - return "tag"; + return "tag bracket"; } else if (ch == "=") { type = "equals"; return null; } else if (ch == "<") { state.tokenize = inText; + state.state = baseState; + state.tagName = state.tagStart = null; var next = state.tokenize(stream, state); - return next ? next + " error" : "error"; + return next ? next + " tag error" : "tag error"; } else if (/[\'\"]/.test(ch)) { state.tokenize = inAttribute(ch); state.stringStartCol = stream.column(); return state.tokenize(stream, state); } else { - stream.eatWhile(/[^\s\u00a0=<>\"\']/); + stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/); return "word"; } } @@ -169,139 +185,143 @@ CodeMirror.defineMode("xml", function(config, parserConfig) { }; } - var curState, curStream, setStyle; - function pass() { - for (var i = arguments.length - 1; i >= 0; i--) curState.cc.push(arguments[i]); - } - function cont() { - pass.apply(null, arguments); - return true; + function Context(state, tagName, startOfLine) { + this.prev = state.context; + this.tagName = tagName; + this.indent = state.indented; + this.startOfLine = startOfLine; + if (config.doNotIndent.hasOwnProperty(tagName) || (state.context && state.context.noIndent)) + this.noIndent = true; } - - function pushContext(tagName, startOfLine) { - var noIndent = Kludges.doNotIndent.hasOwnProperty(tagName) || (curState.context && curState.context.noIndent); - curState.context = { - prev: curState.context, - tagName: tagName, - indent: curState.indented, - startOfLine: startOfLine, - noIndent: noIndent - }; + function popContext(state) { + if (state.context) state.context = state.context.prev; } - function popContext() { - if (curState.context) curState.context = curState.context.prev; + function maybePopContext(state, nextTagName) { + var parentTagName; + while (true) { + if (!state.context) { + return; + } + parentTagName = state.context.tagName; + if (!config.contextGrabbers.hasOwnProperty(parentTagName) || + !config.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) { + return; + } + popContext(state); + } } - function element(type) { + function baseState(type, stream, state) { if (type == "openTag") { - curState.tagName = tagName; - curState.tagStart = curStream.column(); - return cont(attributes, endtag(curState.startOfLine)); + state.tagStart = stream.column(); + return tagNameState; } else if (type == "closeTag") { - var err = false; - if (curState.context) { - if (curState.context.tagName != tagName) { - if (Kludges.implicitlyClosed.hasOwnProperty(curState.context.tagName.toLowerCase())) { - popContext(); - } - err = !curState.context || curState.context.tagName != tagName; - } - } else { - err = true; - } - if (err) setStyle = "error"; - return cont(endclosetag(err)); + return closeTagNameState; + } else { + return baseState; } - return cont(); - } - function endtag(startOfLine) { - return function(type) { - var tagName = curState.tagName; - curState.tagName = curState.tagStart = null; - if (type == "selfcloseTag" || - (type == "endTag" && Kludges.autoSelfClosers.hasOwnProperty(tagName.toLowerCase()))) { - maybePopContext(tagName.toLowerCase()); - return cont(); - } - if (type == "endTag") { - maybePopContext(tagName.toLowerCase()); - pushContext(tagName, startOfLine); - return cont(); - } - return cont(); - }; } - function endclosetag(err) { - return function(type) { - if (err) setStyle = "error"; - if (type == "endTag") { popContext(); return cont(); } + function tagNameState(type, stream, state) { + if (type == "word") { + state.tagName = stream.current(); + setStyle = "tag"; + return attrState; + } else { setStyle = "error"; - return cont(arguments.callee); - }; + return tagNameState; + } } - function maybePopContext(nextTagName) { - var parentTagName; - while (true) { - if (!curState.context) { - return; - } - parentTagName = curState.context.tagName.toLowerCase(); - if (!Kludges.contextGrabbers.hasOwnProperty(parentTagName) || - !Kludges.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) { - return; + function closeTagNameState(type, stream, state) { + if (type == "word") { + var tagName = stream.current(); + if (state.context && state.context.tagName != tagName && + config.implicitlyClosed.hasOwnProperty(state.context.tagName)) + popContext(state); + if ((state.context && state.context.tagName == tagName) || config.matchClosing === false) { + setStyle = "tag"; + return closeState; + } else { + setStyle = "tag error"; + return closeStateErr; } - popContext(); + } else { + setStyle = "error"; + return closeStateErr; + } + } + + function closeState(type, _stream, state) { + if (type != "endTag") { + setStyle = "error"; + return closeState; } + popContext(state); + return baseState; + } + function closeStateErr(type, stream, state) { + setStyle = "error"; + return closeState(type, stream, state); } - function attributes(type) { - if (type == "word") {setStyle = "attribute"; return cont(attribute, attributes);} - if (type == "endTag" || type == "selfcloseTag") return pass(); + function attrState(type, _stream, state) { + if (type == "word") { + setStyle = "attribute"; + return attrEqState; + } else if (type == "endTag" || type == "selfcloseTag") { + var tagName = state.tagName, tagStart = state.tagStart; + state.tagName = state.tagStart = null; + if (type == "selfcloseTag" || + config.autoSelfClosers.hasOwnProperty(tagName)) { + maybePopContext(state, tagName); + } else { + maybePopContext(state, tagName); + state.context = new Context(state, tagName, tagStart == state.indented); + } + return baseState; + } setStyle = "error"; - return cont(attributes); + return attrState; } - function attribute(type) { - if (type == "equals") return cont(attvalue, attributes); - if (!Kludges.allowMissing) setStyle = "error"; - else if (type == "word") {setStyle = "attribute"; return cont(attribute, attributes);} - return (type == "endTag" || type == "selfcloseTag") ? pass() : cont(); + function attrEqState(type, stream, state) { + if (type == "equals") return attrValueState; + if (!config.allowMissing) setStyle = "error"; + return attrState(type, stream, state); } - function attvalue(type) { - if (type == "string") return cont(attvaluemaybe); - if (type == "word" && Kludges.allowUnquoted) {setStyle = "string"; return cont();} + function attrValueState(type, stream, state) { + if (type == "string") return attrContinuedState; + if (type == "word" && config.allowUnquoted) {setStyle = "string"; return attrState;} setStyle = "error"; - return (type == "endTag" || type == "selfCloseTag") ? pass() : cont(); + return attrState(type, stream, state); } - function attvaluemaybe(type) { - if (type == "string") return cont(attvaluemaybe); - else return pass(); + function attrContinuedState(type, stream, state) { + if (type == "string") return attrContinuedState; + return attrState(type, stream, state); } return { - startState: function() { - return {tokenize: inText, cc: [], indented: 0, startOfLine: true, tagName: null, tagStart: null, context: null}; + startState: function(baseIndent) { + var state = {tokenize: inText, + state: baseState, + indented: baseIndent || 0, + tagName: null, tagStart: null, + context: null} + if (baseIndent != null) state.baseIndent = baseIndent + return state }, token: function(stream, state) { - if (!state.tagName && stream.sol()) { - state.startOfLine = true; + if (!state.tagName && stream.sol()) state.indented = stream.indentation(); - } - if (stream.eatSpace()) return null; - setStyle = type = tagName = null; + if (stream.eatSpace()) return null; + type = null; var style = state.tokenize(stream, state); - state.type = type; if ((style || type) && style != "comment") { - curState = state; curStream = stream; - while (true) { - var comb = state.cc.pop() || element; - if (comb(type || style)) break; - } + setStyle = null; + state.state = state.state(type || style, stream, state); + if (setStyle) + style = setStyle == "error" ? style + " error" : setStyle; } - state.startOfLine = false; - if (setStyle) - style = setStyle == "error" ? style + " error" : setStyle; return style; }, @@ -309,33 +329,60 @@ CodeMirror.defineMode("xml", function(config, parserConfig) { var context = state.context; // Indent multi-line strings (e.g. css). if (state.tokenize.isInAttribute) { - return state.stringStartCol + 1; + if (state.tagStart == state.indented) + return state.stringStartCol + 1; + else + return state.indented + indentUnit; } - if ((state.tokenize != inTag && state.tokenize != inText) || - context && context.noIndent) + if (context && context.noIndent) return CodeMirror.Pass; + if (state.tokenize != inTag && state.tokenize != inText) return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0; // Indent the starts of attribute names. if (state.tagName) { - if (multilineTagIndentPastTag) + if (config.multilineTagIndentPastTag !== false) return state.tagStart + state.tagName.length + 2; else - return state.tagStart + indentUnit * multilineTagIndentFactor; + return state.tagStart + indentUnit * (config.multilineTagIndentFactor || 1); } - if (alignCDATA && /$/, blockCommentStart: "", - configuration: parserConfig.htmlMode ? "html" : "xml", - helperType: parserConfig.htmlMode ? "html" : "xml" + configuration: config.htmlMode ? "html" : "xml", + helperType: config.htmlMode ? "html" : "xml", + + skipAttribute: function(state) { + if (state.state == attrValueState) + state.state = attrState + } }; }); @@ -343,3 +390,5 @@ CodeMirror.defineMIME("text/xml", "xml"); CodeMirror.defineMIME("application/xml", "xml"); if (!CodeMirror.mimeModes.hasOwnProperty("text/html")) CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true}); + +}); diff --git a/Source/WebInspectorUI/UserInterface/External/ESLint/LICENSE b/Source/WebInspectorUI/UserInterface/External/ESLint/LICENSE new file mode 100644 index 000000000..d5f046fdc --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/External/ESLint/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2014 TJ Holowaychuk + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the 'Software'), to deal +in the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/Source/WebInspectorUI/UserInterface/External/ESLint/eslint.js b/Source/WebInspectorUI/UserInterface/External/ESLint/eslint.js new file mode 100644 index 000000000..3b123a2f4 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/External/ESLint/eslint.js @@ -0,0 +1,18223 @@ +!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.eslint=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 0 && this._events[type].length > m) { + this._events[type].warned = true; + console.error('(node) warning: possible EventEmitter memory ' + + 'leak detected. %d listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit.', + this._events[type].length); + if (typeof console.trace === 'function') { + // not supported in IE 10 + console.trace(); + } + } + } + + return this; +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.once = function(type, listener) { + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + var fired = false; + + function g() { + this.removeListener(type, g); + + if (!fired) { + fired = true; + listener.apply(this, arguments); + } + } + + g.listener = listener; + this.on(type, g); + + return this; +}; + +// emits a 'removeListener' event iff the listener was removed +EventEmitter.prototype.removeListener = function(type, listener) { + var list, position, length, i; + + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + if (!this._events || !this._events[type]) + return this; + + list = this._events[type]; + length = list.length; + position = -1; + + if (list === listener || + (isFunction(list.listener) && list.listener === listener)) { + delete this._events[type]; + if (this._events.removeListener) + this.emit('removeListener', type, listener); + + } else if (isObject(list)) { + for (i = length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list.length = 0; + delete this._events[type]; + } else { + list.splice(position, 1); + } + + if (this._events.removeListener) + this.emit('removeListener', type, listener); + } + + return this; +}; + +EventEmitter.prototype.removeAllListeners = function(type) { + var key, listeners; + + if (!this._events) + return this; + + // not listening for removeListener, no need to emit + if (!this._events.removeListener) { + if (arguments.length === 0) + this._events = {}; + else if (this._events[type]) + delete this._events[type]; + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + for (key in this._events) { + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = {}; + return this; + } + + listeners = this._events[type]; + + if (isFunction(listeners)) { + this.removeListener(type, listeners); + } else { + // LIFO order + while (listeners.length) + this.removeListener(type, listeners[listeners.length - 1]); + } + delete this._events[type]; + + return this; +}; + +EventEmitter.prototype.listeners = function(type) { + var ret; + if (!this._events || !this._events[type]) + ret = []; + else if (isFunction(this._events[type])) + ret = [this._events[type]]; + else + ret = this._events[type].slice(); + return ret; +}; + +EventEmitter.listenerCount = function(emitter, type) { + var ret; + if (!emitter._events || !emitter._events[type]) + ret = 0; + else if (isFunction(emitter._events[type])) + ret = 1; + else + ret = emitter._events[type].length; + return ret; +}; + +function isFunction(arg) { + return typeof arg === 'function'; +} + +function isNumber(arg) { + return typeof arg === 'number'; +} + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} + +function isUndefined(arg) { + return arg === void 0; +} + +},{}],4:[function(require,module,exports){ +/* + Copyright (C) 2012-2014 Yusuke Suzuki + Copyright (C) 2014 Dan Tao + Copyright (C) 2013 Andrew Eisenberg + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/*jslint bitwise:true plusplus:true eqeq:true nomen:true*/ +/*global doctrine:true, exports:true, parseTypeExpression:true, parseTop:true*/ + +(function (exports) { + 'use strict'; + + var VERSION, + Regex, + CanAccessStringByIndex, + typed, + jsdoc, + isArray, + hasOwnProperty; + + // Sync with package.json. + VERSION = '0.5.2-dev'; + + // See also tools/generate-unicode-regex.py. + Regex = { + NonAsciiIdentifierStart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]'), + NonAsciiIdentifierPart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0300-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u0483-\u0487\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u05d0-\u05ea\u05f0-\u05f2\u0610-\u061a\u0620-\u0669\u066e-\u06d3\u06d5-\u06dc\u06df-\u06e8\u06ea-\u06fc\u06ff\u0710-\u074a\u074d-\u07b1\u07c0-\u07f5\u07fa\u0800-\u082d\u0840-\u085b\u08a0\u08a2-\u08ac\u08e4-\u08fe\u0900-\u0963\u0966-\u096f\u0971-\u0977\u0979-\u097f\u0981-\u0983\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bc-\u09c4\u09c7\u09c8\u09cb-\u09ce\u09d7\u09dc\u09dd\u09df-\u09e3\u09e6-\u09f1\u0a01-\u0a03\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a59-\u0a5c\u0a5e\u0a66-\u0a75\u0a81-\u0a83\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abc-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ad0\u0ae0-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3c-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5c\u0b5d\u0b5f-\u0b63\u0b66-\u0b6f\u0b71\u0b82\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd0\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c58\u0c59\u0c60-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbc-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0cde\u0ce0-\u0ce3\u0ce6-\u0cef\u0cf1\u0cf2\u0d02\u0d03\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d-\u0d44\u0d46-\u0d48\u0d4a-\u0d4e\u0d57\u0d60-\u0d63\u0d66-\u0d6f\u0d7a-\u0d7f\u0d82\u0d83\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e01-\u0e3a\u0e40-\u0e4e\u0e50-\u0e59\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb9\u0ebb-\u0ebd\u0ec0-\u0ec4\u0ec6\u0ec8-\u0ecd\u0ed0-\u0ed9\u0edc-\u0edf\u0f00\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e-\u0f47\u0f49-\u0f6c\u0f71-\u0f84\u0f86-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1049\u1050-\u109d\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u135d-\u135f\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176c\u176e-\u1770\u1772\u1773\u1780-\u17d3\u17d7\u17dc\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1820-\u1877\u1880-\u18aa\u18b0-\u18f5\u1900-\u191c\u1920-\u192b\u1930-\u193b\u1946-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u19d0-\u19d9\u1a00-\u1a1b\u1a20-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1aa7\u1b00-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1bf3\u1c00-\u1c37\u1c40-\u1c49\u1c4d-\u1c7d\u1cd0-\u1cd2\u1cd4-\u1cf6\u1d00-\u1de6\u1dfc-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u200c\u200d\u203f\u2040\u2054\u2071\u207f\u2090-\u209c\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d7f-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2de0-\u2dff\u2e2f\u3005-\u3007\u3021-\u302f\u3031-\u3035\u3038-\u303c\u3041-\u3096\u3099\u309a\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua62b\ua640-\ua66f\ua674-\ua67d\ua67f-\ua697\ua69f-\ua6f1\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua827\ua840-\ua873\ua880-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f7\ua8fb\ua900-\ua92d\ua930-\ua953\ua960-\ua97c\ua980-\ua9c0\ua9cf-\ua9d9\uaa00-\uaa36\uaa40-\uaa4d\uaa50-\uaa59\uaa60-\uaa76\uaa7a\uaa7b\uaa80-\uaac2\uaadb-\uaadd\uaae0-\uaaef\uaaf2-\uaaf6\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabea\uabec\uabed\uabf0-\uabf9\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\ufe70-\ufe74\ufe76-\ufefc\uff10-\uff19\uff21-\uff3a\uff3f\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]') + }; + + CanAccessStringByIndex = typeof 'doctrine'[0] !== undefined; + + function sliceSource(source, index, last) { + var output; + if (!CanAccessStringByIndex) { + output = source.slice(index, last).join(''); + } else { + output = source.slice(index, last); + } + return output; + } + + isArray = Array.isArray; + if (!isArray) { + isArray = function isArray(ary) { + return Object.prototype.toString.call(ary) === '[object Array]'; + }; + } + + hasOwnProperty = (function () { + var func = Object.prototype.hasOwnProperty; + return function hasOwnProperty(obj, name) { + return func.call(obj, name); + }; + }()); + + function shallowCopy(obj) { + var ret = {}, key; + for (key in obj) { + if (obj.hasOwnProperty(key)) { + ret[key] = obj[key]; + } + } + return ret; + } + + function isLineTerminator(ch) { + return ch === '\n' || ch === '\r' || ch === '\u2028' || ch === '\u2029'; + } + + function isWhiteSpace(ch) { + return (ch === ' ') || (ch === '\u0009') || (ch === '\u000B') || + (ch === '\u000C') || (ch === '\u00A0') || + (ch.charCodeAt(0) >= 0x1680 && + '\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\uFEFF'.indexOf(ch) >= 0); + } + + function isDecimalDigit(ch) { + return '0123456789'.indexOf(ch) >= 0; + } + + function isHexDigit(ch) { + return '0123456789abcdefABCDEF'.indexOf(ch) >= 0; + } + + function isOctalDigit(ch) { + return '01234567'.indexOf(ch) >= 0; + } + + function isASCIIAlphanumeric(ch) { + return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9'); + } + + function isIdentifierStart(ch) { + return (ch === '$') || (ch === '_') || (ch === '\\') || + (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || + ((ch.charCodeAt(0) >= 0x80) && Regex.NonAsciiIdentifierStart.test(ch)); + } + + function isIdentifierPart(ch) { + return (ch === '$') || (ch === '_') || (ch === '\\') || + (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || + ((ch >= '0') && (ch <= '9')) || + ((ch.charCodeAt(0) >= 0x80) && Regex.NonAsciiIdentifierPart.test(ch)); + } + + function isTypeName(ch) { + return '><(){}[],:*|?!='.indexOf(ch) === -1 && !isWhiteSpace(ch) && !isLineTerminator(ch); + } + + function isParamTitle(title) { + return title === 'param' || title === 'argument' || title === 'arg'; + } + + function isProperty(title) { + return title === 'property' || title === 'prop'; + } + + function isNameParameterRequired(title) { + return isParamTitle(title) || isProperty(title) || + title === 'alias' || title === 'this' || title === 'mixes' || title === 'requires'; + } + + function isAllowedName(title) { + return isNameParameterRequired(title) || title === 'const' || title === 'constant'; + } + + function isAllowedNested(title) { + return isProperty(title) || isParamTitle(title); + } + + function isTypeParameterRequired(title) { + return isParamTitle(title) || title === 'define' || title === 'enum' || + title === 'implements' || title === 'return' || + title === 'this' || title === 'type' || title === 'typedef' || + title === 'returns' || isProperty(title); + } + + // Consider deprecation instead using 'isTypeParameterRequired' and 'Rules' declaration to pick when a type is optional/required + // This would require changes to 'parseType' + function isAllowedType(title) { + return isTypeParameterRequired(title) || title === 'throws' || title === 'const' || title === 'constant' || + title === 'namespace' || title === 'member' || title === 'var' || title === 'module' || + title === 'constructor' || title === 'class' || title === 'extends' || title === 'augments' || + title === 'public' || title === 'private' || title === 'protected'; + } + + function DoctrineError(message) { + this.name = 'DoctrineError'; + this.message = message; + } + DoctrineError.prototype = new Error(); + DoctrineError.prototype.constructor = DoctrineError; + + function throwError(message) { + throw new DoctrineError(message); + } + + function assert(cond, text) { + if (VERSION.slice(-3) === 'dev') { + if (!cond) { + throwError(text); + } + } + } + + function trim(str) { + return str.replace(/^\s+/, '').replace(/\s+$/, ''); + } + + function unwrapComment(doc) { + // JSDoc comment is following form + // /** + // * ....... + // */ + // remove /**, */ and * + var BEFORE_STAR = 0, + STAR = 1, + AFTER_STAR = 2, + index, + len, + mode, + result, + ch; + + doc = doc.replace(/^\/\*\*?/, '').replace(/\*\/$/, ''); + index = 0; + len = doc.length; + mode = BEFORE_STAR; + result = ''; + + while (index < len) { + ch = doc[index]; + switch (mode) { + case BEFORE_STAR: + if (isLineTerminator(ch)) { + result += ch; + } else if (ch === '*') { + mode = STAR; + } else if (!isWhiteSpace(ch)) { + result += ch; + mode = AFTER_STAR; + } + break; + + case STAR: + if (!isWhiteSpace(ch)) { + result += ch; + } + mode = isLineTerminator(ch) ? BEFORE_STAR : AFTER_STAR; + break; + + case AFTER_STAR: + result += ch; + if (isLineTerminator(ch)) { + mode = BEFORE_STAR; + } + break; + } + index += 1; + } + + return result; + } + + // Type Expression Parser + + (function (exports) { + var Syntax, + Token, + source, + length, + index, + previous, + token, + value; + + Syntax = { + NullableLiteral: 'NullableLiteral', + AllLiteral: 'AllLiteral', + NullLiteral: 'NullLiteral', + UndefinedLiteral: 'UndefinedLiteral', + VoidLiteral: 'VoidLiteral', + UnionType: 'UnionType', + ArrayType: 'ArrayType', + RecordType: 'RecordType', + FieldType: 'FieldType', + FunctionType: 'FunctionType', + ParameterType: 'ParameterType', + RestType: 'RestType', + NonNullableType: 'NonNullableType', + OptionalType: 'OptionalType', + NullableType: 'NullableType', + NameExpression: 'NameExpression', + TypeApplication: 'TypeApplication' + }; + + Token = { + ILLEGAL: 0, // ILLEGAL + DOT: 1, // . + DOT_LT: 2, // .< + REST: 3, // ... + LT: 4, // < + GT: 5, // > + LPAREN: 6, // ( + RPAREN: 7, // ) + LBRACE: 8, // { + RBRACE: 9, // } + LBRACK: 10, // [ + RBRACK: 11, // ] + COMMA: 12, // , + COLON: 13, // : + STAR: 14, // * + PIPE: 15, // | + QUESTION: 16, // ? + BANG: 17, // ! + EQUAL: 18, // = + NAME: 19, // name token + STRING: 20, // string + NUMBER: 21, // number + EOF: 22 + }; + + function Context(previous, index, token, value) { + this._previous = previous; + this._index = index; + this._token = token; + this._value = value; + } + + Context.prototype.restore = function () { + previous = this._previous; + index = this._index; + token = this._token; + value = this._value; + }; + + Context.save = function () { + return new Context(previous, index, token, value); + }; + + function advance() { + var ch = source[index]; + index += 1; + return ch; + } + + function scanHexEscape(prefix) { + var i, len, ch, code = 0; + + len = (prefix === 'u') ? 4 : 2; + for (i = 0; i < len; ++i) { + if (index < length && isHexDigit(source[index])) { + ch = advance(); + code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); + } else { + return ''; + } + } + return String.fromCharCode(code); + } + + function scanString() { + var str = '', quote, ch, code, unescaped, restore; //TODO review removal octal = false + quote = source[index]; + ++index; + + while (index < length) { + ch = advance(); + + if (ch === quote) { + quote = ''; + break; + } else if (ch === '\\') { + ch = advance(); + if (!isLineTerminator(ch)) { + switch (ch) { + case 'n': + str += '\n'; + break; + case 'r': + str += '\r'; + break; + case 't': + str += '\t'; + break; + case 'u': + case 'x': + restore = index; + unescaped = scanHexEscape(ch); + if (unescaped) { + str += unescaped; + } else { + index = restore; + str += ch; + } + break; + case 'b': + str += '\b'; + break; + case 'f': + str += '\f'; + break; + case 'v': + str += '\v'; + break; + + default: + if (isOctalDigit(ch)) { + code = '01234567'.indexOf(ch); + + // \0 is not octal escape sequence + // Deprecating unused code. TODO review removal + //if (code !== 0) { + // octal = true; + //} + + if (index < length && isOctalDigit(source[index])) { + //TODO Review Removal octal = true; + code = code * 8 + '01234567'.indexOf(advance()); + + // 3 digits are only allowed when string starts + // with 0, 1, 2, 3 + if ('0123'.indexOf(ch) >= 0 && + index < length && + isOctalDigit(source[index])) { + code = code * 8 + '01234567'.indexOf(advance()); + } + } + str += String.fromCharCode(code); + } else { + str += ch; + } + break; + } + } else { + if (ch === '\r' && source[index] === '\n') { + ++index; + } + } + } else if (isLineTerminator(ch)) { + break; + } else { + str += ch; + } + } + + if (quote !== '') { + throwError('unexpected quote'); + } + + value = str; + return Token.STRING; + } + + function scanNumber() { + var number, ch; + + number = ''; + if (ch !== '.') { + number = advance(); + ch = source[index]; + + if (number === '0') { + if (ch === 'x' || ch === 'X') { + number += advance(); + while (index < length) { + ch = source[index]; + if (!isHexDigit(ch)) { + break; + } + number += advance(); + } + + if (number.length <= 2) { + // only 0x + throwError('unexpected token'); + } + + if (index < length) { + ch = source[index]; + if (isIdentifierStart(ch)) { + throwError('unexpected token'); + } + } + value = parseInt(number, 16); + return Token.NUMBER; + } + + if (isOctalDigit(ch)) { + number += advance(); + while (index < length) { + ch = source[index]; + if (!isOctalDigit(ch)) { + break; + } + number += advance(); + } + + if (index < length) { + ch = source[index]; + if (isIdentifierStart(ch) || isDecimalDigit(ch)) { + throwError('unexpected token'); + } + } + value = parseInt(number, 8); + return Token.NUMBER; + } + + if (isDecimalDigit(ch)) { + throwError('unexpected token'); + } + } + + while (index < length) { + ch = source[index]; + if (!isDecimalDigit(ch)) { + break; + } + number += advance(); + } + } + + if (ch === '.') { + number += advance(); + while (index < length) { + ch = source[index]; + if (!isDecimalDigit(ch)) { + break; + } + number += advance(); + } + } + + if (ch === 'e' || ch === 'E') { + number += advance(); + + ch = source[index]; + if (ch === '+' || ch === '-') { + number += advance(); + } + + ch = source[index]; + if (isDecimalDigit(ch)) { + number += advance(); + while (index < length) { + ch = source[index]; + if (!isDecimalDigit(ch)) { + break; + } + number += advance(); + } + } else { + throwError('unexpected token'); + } + } + + if (index < length) { + ch = source[index]; + if (isIdentifierStart(ch)) { + throwError('unexpected token'); + } + } + + value = parseFloat(number); + return Token.NUMBER; + } + + + function scanTypeName() { + var ch, ch2; + + value = advance(); + while (index < length && isTypeName(source[index])) { + ch = source[index]; + if (ch === '.') { + if ((index + 1) < length) { + ch2 = source[index + 1]; + if (ch2 === '<') { + break; + } + } + } + value += advance(); + } + return Token.NAME; + } + + function next() { + var ch; + + previous = index; + + while (index < length && isWhiteSpace(source[index])) { + advance(); + } + if (index >= length) { + token = Token.EOF; + return token; + } + + ch = source[index]; + switch (ch) { + case '"': + token = scanString(); + return token; + + case ':': + advance(); + token = Token.COLON; + return token; + + case ',': + advance(); + token = Token.COMMA; + return token; + + case '(': + advance(); + token = Token.LPAREN; + return token; + + case ')': + advance(); + token = Token.RPAREN; + return token; + + case '[': + advance(); + token = Token.LBRACK; + return token; + + case ']': + advance(); + token = Token.RBRACK; + return token; + + case '{': + advance(); + token = Token.LBRACE; + return token; + + case '}': + advance(); + token = Token.RBRACE; + return token; + + case '.': + advance(); + if (index < length) { + ch = source[index]; + if (ch === '<') { + advance(); + token = Token.DOT_LT; + return token; + } + + if (ch === '.' && index + 1 < length && source[index + 1] === '.') { + advance(); + advance(); + token = Token.REST; + return token; + } + + if (isDecimalDigit(ch)) { + token = scanNumber(); + return token; + } + } + token = Token.DOT; + return token; + + case '<': + advance(); + token = Token.LT; + return token; + + case '>': + advance(); + token = Token.GT; + return token; + + case '*': + advance(); + token = Token.STAR; + return token; + + case '|': + advance(); + token = Token.PIPE; + return token; + + case '?': + advance(); + token = Token.QUESTION; + return token; + + case '!': + advance(); + token = Token.BANG; + return token; + + case '=': + advance(); + token = Token.EQUAL; + return token; + + default: + if (isDecimalDigit(ch)) { + token = scanNumber(); + return token; + } + + // type string permits following case, + // + // namespace.module.MyClass + // + // this reduced 1 token TK_NAME + if (isTypeName(ch)) { + token = scanTypeName(); + return token; + } + + token = Token.ILLEGAL; + return token; + } + } + + function consume(target, text) { + assert(token === target, text || 'consumed token not matched'); + next(); + } + + function expect(target) { + if (token !== target) { + throwError('unexpected token'); + } + next(); + } + + // UnionType := '(' TypeUnionList ')' + // + // TypeUnionList := + // <> + // | NonemptyTypeUnionList + // + // NonemptyTypeUnionList := + // TypeExpression + // | TypeExpression '|' NonemptyTypeUnionList + function parseUnionType() { + var elements; + consume(Token.LPAREN, 'UnionType should start with ('); + elements = []; + if (token !== Token.RPAREN) { + while (true) { + elements.push(parseTypeExpression()); + if (token === Token.RPAREN) { + break; + } + expect(Token.PIPE); + } + } + consume(Token.RPAREN, 'UnionType should end with )'); + return { + type: Syntax.UnionType, + elements: elements + }; + } + + // ArrayType := '[' ElementTypeList ']' + // + // ElementTypeList := + // <> + // | TypeExpression + // | '...' TypeExpression + // | TypeExpression ',' ElementTypeList + function parseArrayType() { + var elements; + consume(Token.LBRACK, 'ArrayType should start with ['); + elements = []; + while (token !== Token.RBRACK) { + if (token === Token.REST) { + consume(Token.REST); + elements.push({ + type: Syntax.RestType, + expression: parseTypeExpression() + }); + break; + } else { + elements.push(parseTypeExpression()); + } + if (token !== Token.RBRACK) { + expect(Token.COMMA); + } + } + expect(Token.RBRACK); + return { + type: Syntax.ArrayType, + elements: elements + }; + } + + function parseFieldName() { + var v = value; + if (token === Token.NAME || token === Token.STRING) { + next(); + return v; + } + + if (token === Token.NUMBER) { + consume(Token.NUMBER); + return String(v); + } + + throwError('unexpected token'); + } + + // FieldType := + // FieldName + // | FieldName ':' TypeExpression + // + // FieldName := + // NameExpression + // | StringLiteral + // | NumberLiteral + // | ReservedIdentifier + function parseFieldType() { + var key; + + key = parseFieldName(); + if (token === Token.COLON) { + consume(Token.COLON); + return { + type: Syntax.FieldType, + key: key, + value: parseTypeExpression() + }; + } + return { + type: Syntax.FieldType, + key: key, + value: null + }; + } + + // RecordType := '{' FieldTypeList '}' + // + // FieldTypeList := + // <> + // | FieldType + // | FieldType ',' FieldTypeList + function parseRecordType() { + var fields; + + consume(Token.LBRACE, 'RecordType should start with {'); + fields = []; + if (token === Token.COMMA) { + consume(Token.COMMA); + } else { + while (token !== Token.RBRACE) { + fields.push(parseFieldType()); + if (token !== Token.RBRACE) { + expect(Token.COMMA); + } + } + } + expect(Token.RBRACE); + return { + type: Syntax.RecordType, + fields: fields + }; + } + + function parseNameExpression() { + var name = value; + expect(Token.NAME); + return { + type: Syntax.NameExpression, + name: name + }; + } + + // TypeExpressionList := + // TopLevelTypeExpression + // | TopLevelTypeExpression ',' TypeExpressionList + function parseTypeExpressionList() { + var elements = []; + + elements.push(parseTop()); + while (token === Token.COMMA) { + consume(Token.COMMA); + elements.push(parseTop()); + } + return elements; + } + + // TypeName := + // NameExpression + // | NameExpression TypeApplication + // + // TypeApplication := + // '.<' TypeExpressionList '>' + // | '<' TypeExpressionList '>' // this is extension of doctrine + function parseTypeName() { + var expr, applications; + + expr = parseNameExpression(); + if (token === Token.DOT_LT || token === Token.LT) { + next(); + applications = parseTypeExpressionList(); + expect(Token.GT); + return { + type: Syntax.TypeApplication, + expression: expr, + applications: applications + }; + } + return expr; + } + + // ResultType := + // <> + // | ':' void + // | ':' TypeExpression + // + // BNF is above + // but, we remove <> pattern, so token is always TypeToken::COLON + function parseResultType() { + consume(Token.COLON, 'ResultType should start with :'); + if (token === Token.NAME && value === 'void') { + consume(Token.NAME); + return { + type: Syntax.VoidLiteral + }; + } + return parseTypeExpression(); + } + + // ParametersType := + // RestParameterType + // | NonRestParametersType + // | NonRestParametersType ',' RestParameterType + // + // RestParameterType := + // '...' + // '...' Identifier + // + // NonRestParametersType := + // ParameterType ',' NonRestParametersType + // | ParameterType + // | OptionalParametersType + // + // OptionalParametersType := + // OptionalParameterType + // | OptionalParameterType, OptionalParametersType + // + // OptionalParameterType := ParameterType= + // + // ParameterType := TypeExpression | Identifier ':' TypeExpression + // + // Identifier is "new" or "this" + function parseParametersType() { + var params = [], normal = true, expr, rest = false; + + while (token !== Token.RPAREN) { + if (token === Token.REST) { + // RestParameterType + consume(Token.REST); + rest = true; + } + + expr = parseTypeExpression(); + if (expr.type === Syntax.NameExpression && token === Token.COLON) { + // Identifier ':' TypeExpression + consume(Token.COLON); + expr = { + type: Syntax.ParameterType, + name: expr.name, + expression: parseTypeExpression() + }; + } + if (token === Token.EQUAL) { + consume(Token.EQUAL); + expr = { + type: Syntax.OptionalType, + expression: expr + }; + normal = false; + } else { + if (!normal) { + throwError('unexpected token'); + } + } + if (rest) { + expr = { + type: Syntax.RestType, + expression: expr + }; + } + params.push(expr); + if (token !== Token.RPAREN) { + expect(Token.COMMA); + } + } + return params; + } + + // FunctionType := 'function' FunctionSignatureType + // + // FunctionSignatureType := + // | TypeParameters '(' ')' ResultType + // | TypeParameters '(' ParametersType ')' ResultType + // | TypeParameters '(' 'this' ':' TypeName ')' ResultType + // | TypeParameters '(' 'this' ':' TypeName ',' ParametersType ')' ResultType + function parseFunctionType() { + var isNew, thisBinding, params, result, fnType; + assert(token === Token.NAME && value === 'function', 'FunctionType should start with \'function\''); + consume(Token.NAME); + + // Google Closure Compiler is not implementing TypeParameters. + // So we do not. if we don't get '(', we see it as error. + expect(Token.LPAREN); + + isNew = false; + params = []; + thisBinding = null; + if (token !== Token.RPAREN) { + // ParametersType or 'this' + if (token === Token.NAME && + (value === 'this' || value === 'new')) { + // 'this' or 'new' + // 'new' is Closure Compiler extension + isNew = value === 'new'; + consume(Token.NAME); + expect(Token.COLON); + thisBinding = parseTypeName(); + if (token === Token.COMMA) { + consume(Token.COMMA); + params = parseParametersType(); + } + } else { + params = parseParametersType(); + } + } + + expect(Token.RPAREN); + + result = null; + if (token === Token.COLON) { + result = parseResultType(); + } + + fnType = { + type: Syntax.FunctionType, + params: params, + result: result + }; + if (thisBinding) { + // avoid adding null 'new' and 'this' properties + fnType['this'] = thisBinding; + if (isNew) { + fnType['new'] = true; + } + } + return fnType; + } + + // BasicTypeExpression := + // '*' + // | 'null' + // | 'undefined' + // | TypeName + // | FunctionType + // | UnionType + // | RecordType + // | ArrayType + function parseBasicTypeExpression() { + var context; + switch (token) { + case Token.STAR: + consume(Token.STAR); + return { + type: Syntax.AllLiteral + }; + + case Token.LPAREN: + return parseUnionType(); + + case Token.LBRACK: + return parseArrayType(); + + case Token.LBRACE: + return parseRecordType(); + + case Token.NAME: + if (value === 'null') { + consume(Token.NAME); + return { + type: Syntax.NullLiteral + }; + } + + if (value === 'undefined') { + consume(Token.NAME); + return { + type: Syntax.UndefinedLiteral + }; + } + + context = Context.save(); + if (value === 'function') { + try { + return parseFunctionType(); + } catch (e) { + context.restore(); + } + } + + return parseTypeName(); + + default: + throwError('unexpected token'); + } + } + + // TypeExpression := + // BasicTypeExpression + // | '?' BasicTypeExpression + // | '!' BasicTypeExpression + // | BasicTypeExpression '?' + // | BasicTypeExpression '!' + // | '?' + // | BasicTypeExpression '[]' + function parseTypeExpression() { + var expr; + + if (token === Token.QUESTION) { + consume(Token.QUESTION); + if (token === Token.COMMA || token === Token.EQUAL || token === Token.RBRACE || + token === Token.RPAREN || token === Token.PIPE || token === Token.EOF || + token === Token.RBRACK) { + return { + type: Syntax.NullableLiteral + }; + } + return { + type: Syntax.NullableType, + expression: parseBasicTypeExpression(), + prefix: true + }; + } + + if (token === Token.BANG) { + consume(Token.BANG); + return { + type: Syntax.NonNullableType, + expression: parseBasicTypeExpression(), + prefix: true + }; + } + + expr = parseBasicTypeExpression(); + if (token === Token.BANG) { + consume(Token.BANG); + return { + type: Syntax.NonNullableType, + expression: expr, + prefix: false + }; + } + + if (token === Token.QUESTION) { + consume(Token.QUESTION); + return { + type: Syntax.NullableType, + expression: expr, + prefix: false + }; + } + + if (token === Token.LBRACK) { + consume(Token.LBRACK); + consume(Token.RBRACK, 'expected an array-style type declaration (' + value + '[])'); + return { + type: Syntax.TypeApplication, + expression: { + type: Syntax.NameExpression, + name: 'Array' + }, + applications: [expr] + }; + } + + return expr; + } + + // TopLevelTypeExpression := + // TypeExpression + // | TypeUnionList + // + // This rule is Google Closure Compiler extension, not ES4 + // like, + // { number | string } + // If strict to ES4, we should write it as + // { (number|string) } + function parseTop() { + var expr, elements; + + expr = parseTypeExpression(); + if (token !== Token.PIPE) { + return expr; + } + + elements = [ expr ]; + consume(Token.PIPE); + while (true) { + elements.push(parseTypeExpression()); + if (token !== Token.PIPE) { + break; + } + consume(Token.PIPE); + } + + return { + type: Syntax.UnionType, + elements: elements + }; + } + + function parseTopParamType() { + var expr; + + if (token === Token.REST) { + consume(Token.REST); + return { + type: Syntax.RestType, + expression: parseTop() + }; + } + + expr = parseTop(); + if (token === Token.EQUAL) { + consume(Token.EQUAL); + return { + type: Syntax.OptionalType, + expression: expr + }; + } + + return expr; + } + + function parseType(src, opt) { + var expr; + + source = src; + length = source.length; + index = 0; + previous = 0; + + if (!CanAccessStringByIndex) { + source = source.split(''); + } + + next(); + expr = parseTop(); + + if (opt && opt.midstream) { + return { + expression: expr, + index: previous + }; + } + + if (token !== Token.EOF) { + throwError('not reach to EOF'); + } + + return expr; + } + + function parseParamType(src, opt) { + var expr; + + source = src; + length = source.length; + index = 0; + previous = 0; + + if (!CanAccessStringByIndex) { + source = source.split(''); + } + + next(); + expr = parseTopParamType(); + + if (opt && opt.midstream) { + return { + expression: expr, + index: previous + }; + } + + if (token !== Token.EOF) { + throwError('not reach to EOF'); + } + + return expr; + } + + function stringifyImpl(node, compact, topLevel) { + var result, i, iz; + + switch (node.type) { + case Syntax.NullableLiteral: + result = '?'; + break; + + case Syntax.AllLiteral: + result = '*'; + break; + + case Syntax.NullLiteral: + result = 'null'; + break; + + case Syntax.UndefinedLiteral: + result = 'undefined'; + break; + + case Syntax.VoidLiteral: + result = 'void'; + break; + + case Syntax.UnionType: + if (!topLevel) { + result = '('; + } else { + result = ''; + } + + for (i = 0, iz = node.elements.length; i < iz; ++i) { + result += stringifyImpl(node.elements[i], compact); + if ((i + 1) !== iz) { + result += '|'; + } + } + + if (!topLevel) { + result += ')'; + } + break; + + case Syntax.ArrayType: + result = '['; + for (i = 0, iz = node.elements.length; i < iz; ++i) { + result += stringifyImpl(node.elements[i], compact); + if ((i + 1) !== iz) { + result += compact ? ',' : ', '; + } + } + result += ']'; + break; + + case Syntax.RecordType: + result = '{'; + for (i = 0, iz = node.fields.length; i < iz; ++i) { + result += stringifyImpl(node.fields[i], compact); + if ((i + 1) !== iz) { + result += compact ? ',' : ', '; + } + } + result += '}'; + break; + + case Syntax.FieldType: + if (node.value) { + result = node.key + (compact ? ':' : ': ') + stringifyImpl(node.value, compact); + } else { + result = node.key; + } + break; + + case Syntax.FunctionType: + result = compact ? 'function(' : 'function ('; + + if (node['this']) { + if (node['new']) { + result += (compact ? 'new:' : 'new: '); + } else { + result += (compact ? 'this:' : 'this: '); + } + + result += stringifyImpl(node['this'], compact); + + if (node.params.length !== 0) { + result += compact ? ',' : ', '; + } + } + + for (i = 0, iz = node.params.length; i < iz; ++i) { + result += stringifyImpl(node.params[i], compact); + if ((i + 1) !== iz) { + result += compact ? ',' : ', '; + } + } + + result += ')'; + + if (node.result) { + result += (compact ? ':' : ': ') + stringifyImpl(node.result, compact); + } + break; + + case Syntax.ParameterType: + result = node.name + (compact ? ':' : ': ') + stringifyImpl(node.expression, compact); + break; + + case Syntax.RestType: + result = '...'; + if (node.expression) { + result += stringifyImpl(node.expression, compact); + } + break; + + case Syntax.NonNullableType: + if (node.prefix) { + result = '!' + stringifyImpl(node.expression, compact); + } else { + result = stringifyImpl(node.expression, compact) + '!'; + } + break; + + case Syntax.OptionalType: + result = stringifyImpl(node.expression, compact) + '='; + break; + + case Syntax.NullableType: + if (node.prefix) { + result = '?' + stringifyImpl(node.expression, compact); + } else { + result = stringifyImpl(node.expression, compact) + '?'; + } + break; + + case Syntax.NameExpression: + result = node.name; + break; + + case Syntax.TypeApplication: + result = stringifyImpl(node.expression, compact) + '.<'; + for (i = 0, iz = node.applications.length; i < iz; ++i) { + result += stringifyImpl(node.applications[i], compact); + if ((i + 1) !== iz) { + result += compact ? ',' : ', '; + } + } + result += '>'; + break; + + default: + throwError('Unknown type ' + node.type); + } + + return result; + } + + function stringify(node, options) { + if (options == null) { + options = {}; + } + return stringifyImpl(node, options.compact, options.topLevel); + } + + exports.parseType = parseType; + exports.parseParamType = parseParamType; + exports.stringify = stringify; + exports.Syntax = Syntax; + }(typed = {})); + + // JSDoc Tag Parser + + (function (exports) { + var Rules, + index, + lineNumber, + length, + source, + recoverable, + sloppy, + strict; + + function advance() { + var ch = source[index]; + index += 1; + if (isLineTerminator(ch)) { + lineNumber += 1; + } + return ch; + } + + function scanTitle() { + var title = ''; + // waste '@' + advance(); + + while (index < length && isASCIIAlphanumeric(source[index])) { + title += advance(); + } + + return title; + } + + function seekContent() { + var ch, waiting, last = index; + + waiting = false; + while (last < length) { + ch = source[last]; + if (isLineTerminator(ch)) { + lineNumber += 1; + waiting = true; + } else if (waiting) { + if (ch === '@') { + break; + } + if (!isWhiteSpace(ch)) { + waiting = false; + } + } + last += 1; + } + return last; + } + + // type expression may have nest brace, such as, + // { { ok: string } } + // + // therefore, scanning type expression with balancing braces. + function parseType(title, last) { + var ch, brace, type, direct = false; + + // search '{' + while (index < last) { + ch = source[index]; + if (isWhiteSpace(ch)) { + advance(); + } else if (ch === '{') { + advance(); + break; + } else { + // this is direct pattern + direct = true; + break; + } + } + + if (!direct) { + // type expression { is found + brace = 1; + type = ''; + while (index < last) { + ch = source[index]; + if (isLineTerminator(ch)) { + advance(); + } else { + if (ch === '}') { + brace -= 1; + if (brace === 0) { + advance(); + break; + } + } else if (ch === '{') { + brace += 1; + } + type += advance(); + } + } + + if (brace !== 0) { + // braces is not balanced + return throwError('Braces are not balanced'); + } + + try { + if (isParamTitle(title)) { + return typed.parseParamType(type); + } + return typed.parseType(type); + } catch (e1) { + // parse failed + return null; + } + } else { + return null; + } + } + + function scanIdentifier(last) { + var identifier; + if (!isIdentifierStart(source[index])) { + return null; + } + identifier = advance(); + while (index < last && isIdentifierPart(source[index])) { + identifier += advance(); + } + return identifier; + } + + function skipWhiteSpace(last) { + while (index < last && (isWhiteSpace(source[index]) || isLineTerminator(source[index]))) { + advance(); + } + } + + function parseName(last, allowBrackets, allowNestedParams) { + var name = '', useBrackets; + + skipWhiteSpace(last); + + if (index >= last) { + return null; + } + + if (allowBrackets && source[index] === '[') { + useBrackets = true; + name = advance(); + } + + if (!isIdentifierStart(source[index])) { + return null; + } + + name += scanIdentifier(last); + + if (allowNestedParams) { + while (source[index] === '.') { + name += '.'; + index += 1; + name += scanIdentifier(last); + } + } + + if (useBrackets) { + // do we have a default value for this? + if (source[index] === '=') { + + // consume the '='' symbol + name += advance(); + // scan in the default value + while (index < last && source[index] !== ']') { + name += advance(); + } + } + + if (index >= last || source[index] !== ']') { + // we never found a closing ']' + return null; + } + + // collect the last ']' + name += advance(); + } + + return name; + } + + function skipToTag() { + while (index < length && source[index] !== '@') { + advance(); + } + if (index >= length) { + return false; + } + assert(source[index] === '@'); + return true; + } + + function TagParser(options, title) { + this._options = options; + this._title = title; + this._tag = { + title: title, + description: null + }; + if (this._options.lineNumbers) { + this._tag.lineNumber = lineNumber; + } + this._last = 0; + // space to save special information for title parsers. + this._extra = { }; + } + + // addError(err, ...) + TagParser.prototype.addError = function addError(errorText) { + var args = Array.prototype.slice.call(arguments, 1), + msg = errorText.replace( + /%(\d)/g, + function (whole, index) { + assert(index < args.length, 'Message reference must be in range'); + return args[index]; + } + ); + + if (!this._tag.errors) { + this._tag.errors = []; + } + if (strict) { + throwError(msg); + } + this._tag.errors.push(msg); + return recoverable; + }; + + TagParser.prototype.parseType = function () { + // type required titles + if (isTypeParameterRequired(this._title)) { + try { + this._tag.type = parseType(this._title, this._last); + if (!this._tag.type) { + if (!isParamTitle(this._title)) { + if (!this.addError('Missing or invalid tag type')) { + return false; + } + } + } + } catch (error) { + this._tag.type = null; + if (!this.addError(error.message)) { + return false; + } + } + } else if (isAllowedType(this._title)) { + // optional types + try { + this._tag.type = parseType(this._title, this._last); + } catch (e) { + //For optional types, lets drop the thrown error when we hit the end of the file + } + } + return true; + }; + + TagParser.prototype._parseNamePath = function (optional) { + var name; + name = parseName(this._last, sloppy && isParamTitle(this._title), true); + if (!name) { + if (!optional) { + if (!this.addError('Missing or invalid tag name')) { + return false; + } + } + } + this._tag.name = name; + return true; + }; + + TagParser.prototype.parseNamePath = function () { + return this._parseNamePath(false); + }; + + TagParser.prototype.parseNamePathOptional = function () { + return this._parseNamePath(true); + }; + + + TagParser.prototype.parseName = function () { + var assign, name; + + // param, property requires name + if (isAllowedName(this._title)) { + this._tag.name = parseName(this._last, sloppy && isParamTitle(this._title), isAllowedNested(this._title)); + if (!this._tag.name) { + if (!isNameParameterRequired(this._title)) { + return true; + } + + // it's possible the name has already been parsed but interpreted as a type + // it's also possible this is a sloppy declaration, in which case it will be + // fixed at the end + if (isParamTitle(this._title) && this._tag.type.name) { + this._extra.name = this._tag.type; + this._tag.name = this._tag.type.name; + this._tag.type = null; + } else { + if (!this.addError('Missing or invalid tag name')) { + return false; + } + } + } else { + name = this._tag.name; + if (name.charAt(0) === '[' && name.charAt(name.length - 1) === ']') { + // extract the default value if there is one + // example: @param {string} [somebody=John Doe] description + assign = name.substring(1, name.length - 1).split('='); + if (assign[1]) { + this._tag['default'] = assign[1]; + } + this._tag.name = assign[0]; + + // convert to an optional type + if (this._tag.type.type !== 'OptionalType') { + this._tag.type = { + type: 'OptionalType', + expression: this._tag.type + }; + } + } + } + } + + return true; + }; + + TagParser.prototype.parseDescription = function parseDescription() { + var description = trim(sliceSource(source, index, this._last)); + if (description) { + if ((/^-\s+/).test(description)) { + description = description.substring(2); + } + this._tag.description = description; + } + return true; + }; + + TagParser.prototype.parseKind = function parseKind() { + var kind, kinds; + kinds = { + 'class': true, + 'constant': true, + 'event': true, + 'external': true, + 'file': true, + 'function': true, + 'member': true, + 'mixin': true, + 'module': true, + 'namespace': true, + 'typedef': true + }; + kind = trim(sliceSource(source, index, this._last)); + this._tag.kind = kind; + if (!hasOwnProperty(kinds, kind)) { + if (!this.addError('Invalid kind name \'%0\'', kind)) { + return false; + } + } + return true; + }; + + TagParser.prototype.parseAccess = function parseAccess() { + var access; + access = trim(sliceSource(source, index, this._last)); + this._tag.access = access; + if (access !== 'private' && access !== 'protected' && access !== 'public') { + if (!this.addError('Invalid access name \'%0\'', access)) { + return false; + } + } + return true; + }; + + TagParser.prototype.parseVariation = function parseVariation() { + var variation, text; + text = trim(sliceSource(source, index, this._last)); + variation = parseFloat(text, 10); + this._tag.variation = variation; + if (isNaN(variation)) { + if (!this.addError('Invalid variation \'%0\'', text)) { + return false; + } + } + return true; + }; + + TagParser.prototype.ensureEnd = function () { + var shouldBeEmpty = trim(sliceSource(source, index, this._last)); + if (shouldBeEmpty) { + if (!this.addError('Unknown content \'%0\'', shouldBeEmpty)) { + return false; + } + } + return true; + }; + + TagParser.prototype.epilogue = function epilogue() { + var description; + + description = this._tag.description; + // un-fix potentially sloppy declaration + if (isParamTitle(this._title) && !this._tag.type && description && description.charAt(0) === '[') { + this._tag.type = this._extra.name; + this._tag.name = undefined; + + if (!sloppy) { + if (!this.addError('Missing or invalid tag name')) { + return false; + } + } + } + + return true; + }; + + Rules = { + // http://usejsdoc.org/tags-access.html + 'access': ['parseAccess'], + // http://usejsdoc.org/tags-alias.html + 'alias': ['parseNamePath', 'ensureEnd'], + // http://usejsdoc.org/tags-augments.html + 'augments': ['parseType', 'parseNamePathOptional', 'ensureEnd'], + // http://usejsdoc.org/tags-constructor.html + 'constructor': ['parseType', 'parseNamePathOptional', 'ensureEnd'], + // Synonym: http://usejsdoc.org/tags-constructor.html + 'class': ['parseType', 'parseNamePathOptional', 'ensureEnd'], + // Synonym: http://usejsdoc.org/tags-extends.html + 'extends': ['parseType', 'parseNamePathOptional', 'ensureEnd'], + // http://usejsdoc.org/tags-deprecated.html + 'deprecated': ['parseDescription'], + // http://usejsdoc.org/tags-global.html + 'global': ['ensureEnd'], + // http://usejsdoc.org/tags-inner.html + 'inner': ['ensureEnd'], + // http://usejsdoc.org/tags-instance.html + 'instance': ['ensureEnd'], + // http://usejsdoc.org/tags-kind.html + 'kind': ['parseKind'], + // http://usejsdoc.org/tags-mixes.html + 'mixes': ['parseNamePath', 'ensureEnd'], + // http://usejsdoc.org/tags-mixin.html + 'mixin': ['parseNamePathOptional', 'ensureEnd'], + // http://usejsdoc.org/tags-member.html + 'member': ['parseType', 'parseNamePathOptional', 'ensureEnd'], + // http://usejsdoc.org/tags-method.html + 'method': ['parseNamePathOptional', 'ensureEnd'], + // http://usejsdoc.org/tags-module.html + 'module': ['parseType', 'parseNamePathOptional', 'ensureEnd'], + // Synonym: http://usejsdoc.org/tags-method.html + 'func': ['parseNamePathOptional', 'ensureEnd'], + // Synonym: http://usejsdoc.org/tags-method.html + 'function': ['parseNamePathOptional', 'ensureEnd'], + // Synonym: http://usejsdoc.org/tags-member.html + 'var': ['parseType', 'parseNamePathOptional', 'ensureEnd'], + // http://usejsdoc.org/tags-name.html + 'name': ['parseNamePath', 'ensureEnd'], + // http://usejsdoc.org/tags-namespace.html + 'namespace': ['parseType', 'parseNamePathOptional', 'ensureEnd'], + // http://usejsdoc.org/tags-private.html + 'private': ['parseType', 'parseDescription'], + // http://usejsdoc.org/tags-protected.html + 'protected': ['parseType', 'parseDescription'], + // http://usejsdoc.org/tags-public.html + 'public': ['parseType', 'parseDescription'], + // http://usejsdoc.org/tags-readonly.html + 'readonly': ['ensureEnd'], + // http://usejsdoc.org/tags-requires.html + 'requires': ['parseNamePath', 'ensureEnd'], + // http://usejsdoc.org/tags-since.html + 'since': ['parseDescription'], + // http://usejsdoc.org/tags-static.html + 'static': ['ensureEnd'], + // http://usejsdoc.org/tags-summary.html + 'summary': ['parseDescription'], + // http://usejsdoc.org/tags-this.html + 'this': ['parseNamePath', 'ensureEnd'], + // http://usejsdoc.org/tags-todo.html + 'todo': ['parseDescription'], + // http://usejsdoc.org/tags-variation.html + 'variation': ['parseVariation'], + // http://usejsdoc.org/tags-version.html + 'version': ['parseDescription'] + }; + + TagParser.prototype.parse = function parse() { + var i, iz, sequences, method; + + // empty title + if (!this._title) { + if (!this.addError('Missing or invalid title')) { + return null; + } + } + + // Seek to content last index. + this._last = seekContent(this._title); + + if (hasOwnProperty(Rules, this._title)) { + sequences = Rules[this._title]; + } else { + // default sequences + sequences = ['parseType', 'parseName', 'parseDescription', 'epilogue']; + } + + for (i = 0, iz = sequences.length; i < iz; ++i) { + method = sequences[i]; + if (!this[method]()) { + return null; + } + } + + // Seek global index to end of this tag. + index = this._last; + return this._tag; + }; + + function parseTag(options) { + var title, parser; + + // skip to tag + if (!skipToTag()) { + return null; + } + + // scan title + title = scanTitle(); + + // construct tag parser + parser = new TagParser(options, title); + return parser.parse(); + } + + // + // Parse JSDoc + // + + function scanJSDocDescription() { + var description = '', ch, atAllowed; + + atAllowed = true; + while (index < length) { + ch = source[index]; + + if (atAllowed && ch === '@') { + break; + } + + if (isLineTerminator(ch)) { + atAllowed = true; + } else if (atAllowed && !isWhiteSpace(ch)) { + atAllowed = false; + } + + description += advance(); + } + return trim(description); + } + + function parse(comment, options) { + var tags = [], tag, description, interestingTags, i, iz; + + if (options === undefined) { + options = {}; + } + + if (typeof options.unwrap === 'boolean' && options.unwrap) { + source = unwrapComment(comment); + } else { + source = comment; + } + + // array of relevant tags + if (options.tags) { + if (isArray(options.tags)) { + interestingTags = { }; + for (i = 0, iz = options.tags.length; i < iz; i++) { + if (typeof options.tags[i] === 'string') { + interestingTags[options.tags[i]] = true; + } else { + throwError('Invalid "tags" parameter: ' + options.tags); + } + } + } else { + throwError('Invalid "tags" parameter: ' + options.tags); + } + } + + if (!CanAccessStringByIndex) { + source = source.split(''); + } + + length = source.length; + index = 0; + lineNumber = 0; + recoverable = options.recoverable; + sloppy = options.sloppy; + strict = options.strict; + + description = scanJSDocDescription(); + + while (true) { + tag = parseTag(options); + if (!tag) { + break; + } + if (!interestingTags || interestingTags.hasOwnProperty(tag.title)) { + tags.push(tag); + } + } + + return { + description: description, + tags: tags + }; + } + exports.parse = parse; + }(jsdoc = {})); + + exports.version = VERSION; + exports.parse = jsdoc.parse; + exports.parseType = typed.parseType; + exports.parseParamType = typed.parseParamType; + exports.unwrapComment = unwrapComment; + exports.Syntax = shallowCopy(typed.Syntax); + exports.Error = DoctrineError; + exports.type = { + Syntax: exports.Syntax, + parseType: typed.parseType, + parseParamType: typed.parseParamType, + stringify: typed.stringify + }; +}(typeof exports === 'undefined' ? (doctrine = {}) : exports)); +/* vim: set sw=4 ts=4 et tw=80 : */ + +},{}],5:[function(require,module,exports){ +/* + Copyright (C) 2012-2013 Yusuke Suzuki + Copyright (C) 2013 Alex Seville + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/** + * Escope (escope) is an ECMAScript + * scope analyzer extracted from the esmangle project. + *

      + * escope finds lexical scopes in a source program, i.e. areas of that + * program where different occurrences of the same identifier refer to the same + * variable. With each scope the contained variables are collected, and each + * identifier reference in code is linked to its corresponding variable (if + * possible). + *

      + * escope works on a syntax tree of the parsed source code which has + * to adhere to the + * Mozilla Parser API. E.g. esprima is a parser + * that produces such syntax trees. + *

      + * The main interface is the {@link analyze} function. + * @module + */ + +/*jslint bitwise:true */ +/*global exports:true, define:true, require:true*/ +(function (factory, global) { + 'use strict'; + + function namespace(str, obj) { + var i, iz, names, name; + names = str.split('.'); + for (i = 0, iz = names.length; i < iz; ++i) { + name = names[i]; + if (obj.hasOwnProperty(name)) { + obj = obj[name]; + } else { + obj = (obj[name] = {}); + } + } + return obj; + } + + // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, + // and plain browser loading, + if (typeof define === 'function' && define.amd) { + define('escope', ['exports', 'estraverse'], function (exports, estraverse) { + factory(exports, global, estraverse); + }); + } else if (typeof exports !== 'undefined') { + factory(exports, global, require('estraverse')); + } else { + factory(namespace('escope', global), global, global.estraverse); + } +}(function (exports, global, estraverse) { + 'use strict'; + + var Syntax, + Map, + currentScope, + globalScope, + scopes, + options; + + Syntax = estraverse.Syntax; + + if (typeof global.Map !== 'undefined') { + // ES6 Map + Map = global.Map; + } else { + Map = function Map() { + this.__data = {}; + }; + + Map.prototype.get = function MapGet(key) { + key = '$' + key; + if (this.__data.hasOwnProperty(key)) { + return this.__data[key]; + } + return undefined; + }; + + Map.prototype.has = function MapHas(key) { + key = '$' + key; + return this.__data.hasOwnProperty(key); + }; + + Map.prototype.set = function MapSet(key, val) { + key = '$' + key; + this.__data[key] = val; + }; + + Map.prototype['delete'] = function MapDelete(key) { + key = '$' + key; + return delete this.__data[key]; + }; + } + + function assert(cond, text) { + if (!cond) { + throw new Error(text); + } + } + + function defaultOptions() { + return { + optimistic: false, + directive: false + }; + } + + function updateDeeply(target, override) { + var key, val; + + function isHashObject(target) { + return typeof target === 'object' && target instanceof Object && !(target instanceof RegExp); + } + + for (key in override) { + if (override.hasOwnProperty(key)) { + val = override[key]; + if (isHashObject(val)) { + if (isHashObject(target[key])) { + updateDeeply(target[key], val); + } else { + target[key] = updateDeeply({}, val); + } + } else { + target[key] = val; + } + } + } + return target; + } + + /** + * A Reference represents a single occurrence of an identifier in code. + * @class Reference + */ + function Reference(ident, scope, flag, writeExpr, maybeImplicitGlobal) { + /** + * Identifier syntax node. + * @member {esprima#Identifier} Reference#identifier + */ + this.identifier = ident; + /** + * Reference to the enclosing Scope. + * @member {Scope} Reference#from + */ + this.from = scope; + /** + * Whether the reference comes from a dynamic scope (such as 'eval', + * 'with', etc.), and may be trapped by dynamic scopes. + * @member {boolean} Reference#tainted + */ + this.tainted = false; + /** + * The variable this reference is resolved with. + * @member {Variable} Reference#resolved + */ + this.resolved = null; + /** + * The read-write mode of the reference. (Value is one of {@link + * Reference.READ}, {@link Reference.RW}, {@link Reference.WRITE}). + * @member {number} Reference#flag + * @private + */ + this.flag = flag; + if (this.isWrite()) { + /** + * If reference is writeable, this is the tree being written to it. + * @member {esprima#Node} Reference#writeExpr + */ + this.writeExpr = writeExpr; + } + /** + * Whether the Reference might refer to a global variable. + * @member {boolean} Reference#__maybeImplicitGlobal + * @private + */ + this.__maybeImplicitGlobal = maybeImplicitGlobal; + } + + /** + * @constant Reference.READ + * @private + */ + Reference.READ = 0x1; + /** + * @constant Reference.WRITE + * @private + */ + Reference.WRITE = 0x2; + /** + * @constant Reference.RW + * @private + */ + Reference.RW = 0x3; + + /** + * Whether the reference is static. + * @method Reference#isStatic + * @return {boolean} + */ + Reference.prototype.isStatic = function isStatic() { + return !this.tainted && this.resolved && this.resolved.scope.isStatic(); + }; + + /** + * Whether the reference is writeable. + * @method Reference#isWrite + * @return {boolean} + */ + Reference.prototype.isWrite = function isWrite() { + return this.flag & Reference.WRITE; + }; + + /** + * Whether the reference is readable. + * @method Reference#isRead + * @return {boolean} + */ + Reference.prototype.isRead = function isRead() { + return this.flag & Reference.READ; + }; + + /** + * Whether the reference is read-only. + * @method Reference#isReadOnly + * @return {boolean} + */ + Reference.prototype.isReadOnly = function isReadOnly() { + return this.flag === Reference.READ; + }; + + /** + * Whether the reference is write-only. + * @method Reference#isWriteOnly + * @return {boolean} + */ + Reference.prototype.isWriteOnly = function isWriteOnly() { + return this.flag === Reference.WRITE; + }; + + /** + * Whether the reference is read-write. + * @method Reference#isReadWrite + * @return {boolean} + */ + Reference.prototype.isReadWrite = function isReadWrite() { + return this.flag === Reference.RW; + }; + + /** + * A Variable represents a locally scoped identifier. These include arguments to + * functions. + * @class Variable + */ + function Variable(name, scope) { + /** + * The variable name, as given in the source code. + * @member {String} Variable#name + */ + this.name = name; + /** + * List of defining occurrences of this variable (like in 'var ...' + * statements or as parameter), as AST nodes. + * @member {esprima.Identifier[]} Variable#identifiers + */ + this.identifiers = []; + /** + * List of {@link Reference|references} of this variable (excluding parameter entries) + * in its defining scope and all nested scopes. For defining + * occurrences only see {@link Variable#defs}. + * @member {Reference[]} Variable#references + */ + this.references = []; + + /** + * List of defining occurrences of this variable (like in 'var ...' + * statements or as parameter), as custom objects. + * @typedef {Object} DefEntry + * @property {String} DefEntry.type - the type of the occurrence (e.g. + * "Parameter", "Variable", ...) + * @property {esprima.Identifier} DefEntry.name - the identifier AST node of the occurrence + * @property {esprima.Node} DefEntry.node - the enclosing node of the + * identifier + * @property {esprima.Node} [DefEntry.parent] - the enclosing statement + * node of the identifier + * @member {DefEntry[]} Variable#defs + */ + this.defs = []; + + this.tainted = false; + /** + * Whether this is a stack variable. + * @member {boolean} Variable#stack + */ + this.stack = true; + /** + * Reference to the enclosing Scope. + * @member {Scope} Variable#scope + */ + this.scope = scope; + } + + Variable.CatchClause = 'CatchClause'; + Variable.Parameter = 'Parameter'; + Variable.FunctionName = 'FunctionName'; + Variable.Variable = 'Variable'; + Variable.ImplicitGlobalVariable = 'ImplicitGlobalVariable'; + + function isStrictScope(scope, block) { + var body, i, iz, stmt, expr; + + // When upper scope is exists and strict, inner scope is also strict. + if (scope.upper && scope.upper.isStrict) { + return true; + } + + if (scope.type === 'function') { + body = block.body; + } else if (scope.type === 'global') { + body = block; + } else { + return false; + } + + if (options.directive) { + for (i = 0, iz = body.body.length; i < iz; ++i) { + stmt = body.body[i]; + if (stmt.type !== 'DirectiveStatement') { + break; + } + if (stmt.raw === '"use strict"' || stmt.raw === '\'use strict\'') { + return true; + } + } + } else { + for (i = 0, iz = body.body.length; i < iz; ++i) { + stmt = body.body[i]; + if (stmt.type !== Syntax.ExpressionStatement) { + break; + } + expr = stmt.expression; + if (expr.type !== Syntax.Literal || typeof expr.value !== 'string') { + break; + } + if (expr.raw != null) { + if (expr.raw === '"use strict"' || expr.raw === '\'use strict\'') { + return true; + } + } else { + if (expr.value === 'use strict') { + return true; + } + } + } + } + return false; + } + + /** + * @class Scope + */ + function Scope(block, opt) { + var variable, body; + + /** + * One of 'catch', 'with', 'function' or 'global'. + * @member {String} Scope#type + */ + this.type = + (block.type === Syntax.CatchClause) ? 'catch' : + (block.type === Syntax.WithStatement) ? 'with' : + (block.type === Syntax.Program) ? 'global' : 'function'; + /** + * The scoped {@link Variable}s of this scope, as { Variable.name + * : Variable }. + * @member {Map} Scope#set + */ + this.set = new Map(); + /** + * The tainted variables of this scope, as { Variable.name : + * boolean }. + * @member {Map} Scope#taints */ + this.taints = new Map(); + /** + * Generally, through the lexical scoping of JS you can always know + * which variable an identifier in the source code refers to. There are + * a few exceptions to this rule. With 'global' and 'with' scopes you + * can only decide at runtime which variable a reference refers to. + * Moreover, if 'eval()' is used in a scope, it might introduce new + * bindings in this or its prarent scopes. + * All those scopes are considered 'dynamic'. + * @member {boolean} Scope#dynamic + */ + this.dynamic = this.type === 'global' || this.type === 'with'; + /** + * A reference to the scope-defining syntax node. + * @member {esprima.Node} Scope#block + */ + this.block = block; + /** + * The {@link Reference|references} that are not resolved with this scope. + * @member {Reference[]} Scope#through + */ + this.through = []; + /** + * The scoped {@link Variable}s of this scope. In the case of a + * 'function' scope this includes the automatic argument arguments as + * its first element, as well as all further formal arguments. + * @member {Variable[]} Scope#variables + */ + this.variables = []; + /** + * Any variable {@link Reference|reference} found in this scope. This + * includes occurrences of local variables as well as variables from + * parent scopes (including the global scope). For local variables + * this also includes defining occurrences (like in a 'var' statement). + * In a 'function' scope this does not include the occurrences of the + * formal parameter in the parameter list. + * @member {Reference[]} Scope#references + */ + this.references = []; + /** + * List of {@link Reference}s that are left to be resolved (i.e. which + * need to be linked to the variable they refer to). Used internally to + * resolve bindings during scope analysis. On a finalized scope + * analysis, all sopes have left value null. + * @member {Reference[]} Scope#left + */ + this.left = []; + /** + * For 'global' and 'function' scopes, this is a self-reference. For + * other scope types this is the variableScope value of the + * parent scope. + * @member {Scope} Scope#variableScope + */ + this.variableScope = + (this.type === 'global' || this.type === 'function') ? this : currentScope.variableScope; + /** + * Whether this scope is created by a FunctionExpression. + * @member {boolean} Scope#functionExpressionScope + */ + this.functionExpressionScope = false; + /** + * Whether this is a scope that contains an 'eval()' invocation. + * @member {boolean} Scope#directCallToEvalScope + */ + this.directCallToEvalScope = false; + /** + * @member {boolean} Scope#thisFound + */ + this.thisFound = false; + body = this.type === 'function' ? block.body : block; + if (opt.naming) { + this.__define(block.id, { + type: Variable.FunctionName, + name: block.id, + node: block + }); + this.functionExpressionScope = true; + } else { + if (this.type === 'function') { + variable = new Variable('arguments', this); + this.taints.set('arguments', true); + this.set.set('arguments', variable); + this.variables.push(variable); + } + + if (block.type === Syntax.FunctionExpression && block.id) { + new Scope(block, { naming: true }); + } + } + + /** + * Reference to the parent {@link Scope|scope}. + * @member {Scope} Scope#upper + */ + this.upper = currentScope; + /** + * Whether 'use strict' is in effect in this scope. + * @member {boolean} Scope#isStrict + */ + this.isStrict = isStrictScope(this, block); + + /** + * List of nested {@link Scope}s. + * @member {Scope[]} Scope#childScopes + */ + this.childScopes = []; + if (currentScope) { + currentScope.childScopes.push(this); + } + + + // RAII + currentScope = this; + if (this.type === 'global') { + globalScope = this; + globalScope.implicit = { + set: new Map(), + variables: [] + }; + } + scopes.push(this); + } + + Scope.prototype.__close = function __close() { + var i, iz, ref, current, node, implicit; + + // Because if this is global environment, upper is null + if (!this.dynamic || options.optimistic) { + // static resolve + for (i = 0, iz = this.left.length; i < iz; ++i) { + ref = this.left[i]; + if (!this.__resolve(ref)) { + this.__delegateToUpperScope(ref); + } + } + } else { + // this is "global" / "with" / "function with eval" environment + if (this.type === 'with') { + for (i = 0, iz = this.left.length; i < iz; ++i) { + ref = this.left[i]; + ref.tainted = true; + this.__delegateToUpperScope(ref); + } + } else { + for (i = 0, iz = this.left.length; i < iz; ++i) { + // notify all names are through to global + ref = this.left[i]; + current = this; + do { + current.through.push(ref); + current = current.upper; + } while (current); + } + } + } + + if (this.type === 'global') { + implicit = []; + for (i = 0, iz = this.left.length; i < iz; ++i) { + ref = this.left[i]; + if (ref.__maybeImplicitGlobal && !this.set.has(ref.identifier.name)) { + implicit.push(ref.__maybeImplicitGlobal); + } + } + + // create an implicit global variable from assignment expression + for (i = 0, iz = implicit.length; i < iz; ++i) { + node = implicit[i]; + this.__defineImplicit(node.left, { + type: Variable.ImplicitGlobalVariable, + name: node.left, + node: node + }); + } + } + + this.left = null; + currentScope = this.upper; + }; + + Scope.prototype.__resolve = function __resolve(ref) { + var variable, name; + name = ref.identifier.name; + if (this.set.has(name)) { + variable = this.set.get(name); + variable.references.push(ref); + variable.stack = variable.stack && ref.from.variableScope === this.variableScope; + if (ref.tainted) { + variable.tainted = true; + this.taints.set(variable.name, true); + } + ref.resolved = variable; + return true; + } + return false; + }; + + Scope.prototype.__delegateToUpperScope = function __delegateToUpperScope(ref) { + if (this.upper) { + this.upper.left.push(ref); + } + this.through.push(ref); + }; + + Scope.prototype.__defineImplicit = function __defineImplicit(node, info) { + var name, variable; + if (node && node.type === Syntax.Identifier) { + name = node.name; + if (!this.implicit.set.has(name)) { + variable = new Variable(name, this); + variable.identifiers.push(node); + variable.defs.push(info); + this.implicit.set.set(name, variable); + this.implicit.variables.push(variable); + } else { + variable = this.implicit.set.get(name); + variable.identifiers.push(node); + variable.defs.push(info); + } + } + }; + + Scope.prototype.__define = function __define(node, info) { + var name, variable; + if (node && node.type === Syntax.Identifier) { + name = node.name; + if (!this.set.has(name)) { + variable = new Variable(name, this); + variable.identifiers.push(node); + variable.defs.push(info); + this.set.set(name, variable); + this.variables.push(variable); + } else { + variable = this.set.get(name); + variable.identifiers.push(node); + variable.defs.push(info); + } + } + }; + + Scope.prototype.__referencing = function __referencing(node, assign, writeExpr, maybeImplicitGlobal) { + var ref; + // because Array element may be null + if (node && node.type === Syntax.Identifier) { + ref = new Reference(node, this, assign || Reference.READ, writeExpr, maybeImplicitGlobal); + this.references.push(ref); + this.left.push(ref); + } + }; + + Scope.prototype.__detectEval = function __detectEval() { + var current; + current = this; + this.directCallToEvalScope = true; + do { + current.dynamic = true; + current = current.upper; + } while (current); + }; + + Scope.prototype.__detectThis = function __detectThis() { + this.thisFound = true; + }; + + Scope.prototype.__isClosed = function isClosed() { + return this.left === null; + }; + + // API Scope#resolve(name) + // returns resolved reference + Scope.prototype.resolve = function resolve(ident) { + var ref, i, iz; + assert(this.__isClosed(), 'scope should be closed'); + assert(ident.type === Syntax.Identifier, 'target should be identifier'); + for (i = 0, iz = this.references.length; i < iz; ++i) { + ref = this.references[i]; + if (ref.identifier === ident) { + return ref; + } + } + return null; + }; + + // API Scope#isStatic + // returns this scope is static + Scope.prototype.isStatic = function isStatic() { + return !this.dynamic; + }; + + // API Scope#isArgumentsMaterialized + // return this scope has materialized arguments + Scope.prototype.isArgumentsMaterialized = function isArgumentsMaterialized() { + // TODO(Constellation) + // We can more aggressive on this condition like this. + // + // function t() { + // // arguments of t is always hidden. + // function arguments() { + // } + // } + var variable; + + // This is not function scope + if (this.type !== 'function') { + return true; + } + + if (!this.isStatic()) { + return true; + } + + variable = this.set.get('arguments'); + assert(variable, 'always have arguments variable'); + return variable.tainted || variable.references.length !== 0; + }; + + // API Scope#isThisMaterialized + // return this scope has materialized `this` reference + Scope.prototype.isThisMaterialized = function isThisMaterialized() { + // This is not function scope + if (this.type !== 'function') { + return true; + } + if (!this.isStatic()) { + return true; + } + return this.thisFound; + }; + + Scope.mangledName = '__$escope$__'; + + Scope.prototype.attach = function attach() { + if (!this.functionExpressionScope) { + this.block[Scope.mangledName] = this; + } + }; + + Scope.prototype.detach = function detach() { + if (!this.functionExpressionScope) { + delete this.block[Scope.mangledName]; + } + }; + + Scope.prototype.isUsedName = function (name) { + if (this.set.has(name)) { + return true; + } + for (var i = 0, iz = this.through.length; i < iz; ++i) { + if (this.through[i].identifier.name === name) { + return true; + } + } + return false; + }; + + /** + * @class ScopeManager + */ + function ScopeManager(scopes) { + this.scopes = scopes; + this.attached = false; + } + + // Returns appropliate scope for this node + ScopeManager.prototype.__get = function __get(node) { + var i, iz, scope; + if (this.attached) { + return node[Scope.mangledName] || null; + } + if (Scope.isScopeRequired(node)) { + for (i = 0, iz = this.scopes.length; i < iz; ++i) { + scope = this.scopes[i]; + if (!scope.functionExpressionScope) { + if (scope.block === node) { + return scope; + } + } + } + } + return null; + }; + + ScopeManager.prototype.acquire = function acquire(node) { + return this.__get(node); + }; + + ScopeManager.prototype.release = function release(node) { + var scope = this.__get(node); + if (scope) { + scope = scope.upper; + while (scope) { + if (!scope.functionExpressionScope) { + return scope; + } + scope = scope.upper; + } + } + return null; + }; + + ScopeManager.prototype.attach = function attach() { + var i, iz; + for (i = 0, iz = this.scopes.length; i < iz; ++i) { + this.scopes[i].attach(); + } + this.attached = true; + }; + + ScopeManager.prototype.detach = function detach() { + var i, iz; + for (i = 0, iz = this.scopes.length; i < iz; ++i) { + this.scopes[i].detach(); + } + this.attached = false; + }; + + Scope.isScopeRequired = function isScopeRequired(node) { + return Scope.isVariableScopeRequired(node) || node.type === Syntax.WithStatement || node.type === Syntax.CatchClause; + }; + + Scope.isVariableScopeRequired = function isVariableScopeRequired(node) { + return node.type === Syntax.Program || node.type === Syntax.FunctionExpression || node.type === Syntax.FunctionDeclaration; + }; + + /** + * Main interface function. Takes an Esprima syntax tree and returns the + * analyzed scopes. + * @function analyze + * @param {esprima.Tree} tree + * @param {Object} providedOptions - Options that tailor the scope analysis + * @param {boolean} [providedOptions.optimistic=false] - the optimistic flag + * @param {boolean} [providedOptions.directive=false]- the directive flag + * @param {boolean} [providedOptions.ignoreEval=false]- whether to check 'eval()' calls + * @return {ScopeManager} + */ + function analyze(tree, providedOptions) { + var resultScopes; + + options = updateDeeply(defaultOptions(), providedOptions); + resultScopes = scopes = []; + currentScope = null; + globalScope = null; + + // attach scope and collect / resolve names + estraverse.traverse(tree, { + enter: function enter(node) { + var i, iz, decl; + if (Scope.isScopeRequired(node)) { + new Scope(node, {}); + } + + switch (node.type) { + case Syntax.AssignmentExpression: + if (node.operator === '=') { + currentScope.__referencing(node.left, Reference.WRITE, node.right, (!currentScope.isStrict && node.left.name != null) && node); + } else { + currentScope.__referencing(node.left, Reference.RW, node.right); + } + currentScope.__referencing(node.right); + break; + + case Syntax.ArrayExpression: + for (i = 0, iz = node.elements.length; i < iz; ++i) { + currentScope.__referencing(node.elements[i]); + } + break; + + case Syntax.BlockStatement: + break; + + case Syntax.BinaryExpression: + currentScope.__referencing(node.left); + currentScope.__referencing(node.right); + break; + + case Syntax.BreakStatement: + break; + + case Syntax.CallExpression: + currentScope.__referencing(node.callee); + for (i = 0, iz = node['arguments'].length; i < iz; ++i) { + currentScope.__referencing(node['arguments'][i]); + } + + // check this is direct call to eval + if (!options.ignoreEval && node.callee.type === Syntax.Identifier && node.callee.name === 'eval') { + currentScope.variableScope.__detectEval(); + } + break; + + case Syntax.CatchClause: + currentScope.__define(node.param, { + type: Variable.CatchClause, + name: node.param, + node: node + }); + break; + + case Syntax.ConditionalExpression: + currentScope.__referencing(node.test); + currentScope.__referencing(node.consequent); + currentScope.__referencing(node.alternate); + break; + + case Syntax.ContinueStatement: + break; + + case Syntax.DirectiveStatement: + break; + + case Syntax.DoWhileStatement: + currentScope.__referencing(node.test); + break; + + case Syntax.DebuggerStatement: + break; + + case Syntax.EmptyStatement: + break; + + case Syntax.ExpressionStatement: + currentScope.__referencing(node.expression); + break; + + case Syntax.ForStatement: + currentScope.__referencing(node.init); + currentScope.__referencing(node.test); + currentScope.__referencing(node.update); + break; + + case Syntax.ForInStatement: + if (node.left.type === Syntax.VariableDeclaration) { + currentScope.__referencing(node.left.declarations[0].id, Reference.WRITE, null, false); + } else { + currentScope.__referencing(node.left, Reference.WRITE, null, (!currentScope.isStrict && node.left.name != null) && node); + } + currentScope.__referencing(node.right); + break; + + case Syntax.FunctionDeclaration: + // FunctionDeclaration name is defined in upper scope + currentScope.upper.__define(node.id, { + type: Variable.FunctionName, + name: node.id, + node: node + }); + for (i = 0, iz = node.params.length; i < iz; ++i) { + currentScope.__define(node.params[i], { + type: Variable.Parameter, + name: node.params[i], + node: node, + index: i + }); + } + break; + + case Syntax.FunctionExpression: + // id is defined in upper scope + for (i = 0, iz = node.params.length; i < iz; ++i) { + currentScope.__define(node.params[i], { + type: Variable.Parameter, + name: node.params[i], + node: node, + index: i + }); + } + break; + + case Syntax.Identifier: + break; + + case Syntax.IfStatement: + currentScope.__referencing(node.test); + break; + + case Syntax.Literal: + break; + + case Syntax.LabeledStatement: + break; + + case Syntax.LogicalExpression: + currentScope.__referencing(node.left); + currentScope.__referencing(node.right); + break; + + case Syntax.MemberExpression: + currentScope.__referencing(node.object); + if (node.computed) { + currentScope.__referencing(node.property); + } + break; + + case Syntax.NewExpression: + currentScope.__referencing(node.callee); + for (i = 0, iz = node['arguments'].length; i < iz; ++i) { + currentScope.__referencing(node['arguments'][i]); + } + break; + + case Syntax.ObjectExpression: + break; + + case Syntax.Program: + break; + + case Syntax.Property: + currentScope.__referencing(node.value); + break; + + case Syntax.ReturnStatement: + currentScope.__referencing(node.argument); + break; + + case Syntax.SequenceExpression: + for (i = 0, iz = node.expressions.length; i < iz; ++i) { + currentScope.__referencing(node.expressions[i]); + } + break; + + case Syntax.SwitchStatement: + currentScope.__referencing(node.discriminant); + break; + + case Syntax.SwitchCase: + currentScope.__referencing(node.test); + break; + + case Syntax.ThisExpression: + currentScope.variableScope.__detectThis(); + break; + + case Syntax.ThrowStatement: + currentScope.__referencing(node.argument); + break; + + case Syntax.TryStatement: + break; + + case Syntax.UnaryExpression: + currentScope.__referencing(node.argument); + break; + + case Syntax.UpdateExpression: + currentScope.__referencing(node.argument, Reference.RW, null); + break; + + case Syntax.VariableDeclaration: + for (i = 0, iz = node.declarations.length; i < iz; ++i) { + decl = node.declarations[i]; + currentScope.variableScope.__define(decl.id, { + type: Variable.Variable, + name: decl.id, + node: decl, + index: i, + parent: node + }); + if (decl.init) { + // initializer is found + currentScope.__referencing(decl.id, Reference.WRITE, decl.init, false); + currentScope.__referencing(decl.init); + } + } + break; + + case Syntax.VariableDeclarator: + break; + + case Syntax.WhileStatement: + currentScope.__referencing(node.test); + break; + + case Syntax.WithStatement: + // WithStatement object is referenced at upper scope + currentScope.upper.__referencing(node.object); + break; + } + }, + + leave: function leave(node) { + while (currentScope && node === currentScope.block) { + currentScope.__close(); + } + } + }); + + assert(currentScope === null); + globalScope = null; + scopes = null; + options = null; + + return new ScopeManager(resultScopes); + } + + /** @name module:escope.version */ + exports.version = '1.0.1'; + /** @name module:escope.Reference */ + exports.Reference = Reference; + /** @name module:escope.Variable */ + exports.Variable = Variable; + /** @name module:escope.Scope */ + exports.Scope = Scope; + /** @name module:escope.ScopeManager */ + exports.ScopeManager = ScopeManager; + /** @name module:escope.analyze */ + exports.analyze = analyze; +}, this)); +/* vim: set sw=4 ts=4 et tw=80 : */ + +},{"estraverse":7}],6:[function(require,module,exports){ +/* + Copyright (C) 2013 Ariya Hidayat + Copyright (C) 2013 Thaddee Tyl + Copyright (C) 2013 Mathias Bynens + Copyright (C) 2012 Ariya Hidayat + Copyright (C) 2012 Mathias Bynens + Copyright (C) 2012 Joost-Wim Boekesteijn + Copyright (C) 2012 Kris Kowal + Copyright (C) 2012 Yusuke Suzuki + Copyright (C) 2012 Arpad Borsos + Copyright (C) 2011 Ariya Hidayat + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/*jslint bitwise:true plusplus:true */ +/*global esprima:true, define:true, exports:true, window: true, +throwErrorTolerant: true, +throwError: true, generateStatement: true, peek: true, +parseAssignmentExpression: true, parseBlock: true, parseExpression: true, +parseFunctionDeclaration: true, parseFunctionExpression: true, +parseFunctionSourceElements: true, parseVariableIdentifier: true, +parseLeftHandSideExpression: true, +parseUnaryExpression: true, +parseStatement: true, parseSourceElement: true */ + +(function (root, factory) { + 'use strict'; + + // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, + // Rhino, and plain browser loading. + + /* istanbul ignore next */ + if (typeof define === 'function' && define.amd) { + define(['exports'], factory); + } else if (typeof exports !== 'undefined') { + factory(exports); + } else { + factory((root.esprima = {})); + } +}(this, function (exports) { + 'use strict'; + + var Token, + TokenName, + FnExprTokens, + Syntax, + PropertyKind, + Messages, + Regex, + SyntaxTreeDelegate, + source, + strict, + index, + lineNumber, + lineStart, + length, + delegate, + lookahead, + state, + extra; + + Token = { + BooleanLiteral: 1, + EOF: 2, + Identifier: 3, + Keyword: 4, + NullLiteral: 5, + NumericLiteral: 6, + Punctuator: 7, + StringLiteral: 8, + RegularExpression: 9 + }; + + TokenName = {}; + TokenName[Token.BooleanLiteral] = 'Boolean'; + TokenName[Token.EOF] = ''; + TokenName[Token.Identifier] = 'Identifier'; + TokenName[Token.Keyword] = 'Keyword'; + TokenName[Token.NullLiteral] = 'Null'; + TokenName[Token.NumericLiteral] = 'Numeric'; + TokenName[Token.Punctuator] = 'Punctuator'; + TokenName[Token.StringLiteral] = 'String'; + TokenName[Token.RegularExpression] = 'RegularExpression'; + + // A function following one of those tokens is an expression. + FnExprTokens = ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new', + 'return', 'case', 'delete', 'throw', 'void', + // assignment operators + '=', '+=', '-=', '*=', '/=', '%=', '<<=', '>>=', '>>>=', + '&=', '|=', '^=', ',', + // binary/unary operators + '+', '-', '*', '/', '%', '++', '--', '<<', '>>', '>>>', '&', + '|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=', + '<=', '<', '>', '!=', '!==']; + + Syntax = { + AssignmentExpression: 'AssignmentExpression', + ArrayExpression: 'ArrayExpression', + BlockStatement: 'BlockStatement', + BinaryExpression: 'BinaryExpression', + BreakStatement: 'BreakStatement', + CallExpression: 'CallExpression', + CatchClause: 'CatchClause', + ConditionalExpression: 'ConditionalExpression', + ContinueStatement: 'ContinueStatement', + DoWhileStatement: 'DoWhileStatement', + DebuggerStatement: 'DebuggerStatement', + EmptyStatement: 'EmptyStatement', + ExpressionStatement: 'ExpressionStatement', + ForStatement: 'ForStatement', + ForInStatement: 'ForInStatement', + FunctionDeclaration: 'FunctionDeclaration', + FunctionExpression: 'FunctionExpression', + Identifier: 'Identifier', + IfStatement: 'IfStatement', + Literal: 'Literal', + LabeledStatement: 'LabeledStatement', + LogicalExpression: 'LogicalExpression', + MemberExpression: 'MemberExpression', + NewExpression: 'NewExpression', + ObjectExpression: 'ObjectExpression', + Program: 'Program', + Property: 'Property', + ReturnStatement: 'ReturnStatement', + SequenceExpression: 'SequenceExpression', + SwitchStatement: 'SwitchStatement', + SwitchCase: 'SwitchCase', + ThisExpression: 'ThisExpression', + ThrowStatement: 'ThrowStatement', + TryStatement: 'TryStatement', + UnaryExpression: 'UnaryExpression', + UpdateExpression: 'UpdateExpression', + VariableDeclaration: 'VariableDeclaration', + VariableDeclarator: 'VariableDeclarator', + WhileStatement: 'WhileStatement', + WithStatement: 'WithStatement' + }; + + PropertyKind = { + Data: 1, + Get: 2, + Set: 4 + }; + + // Error messages should be identical to V8. + Messages = { + UnexpectedToken: 'Unexpected token %0', + UnexpectedNumber: 'Unexpected number', + UnexpectedString: 'Unexpected string', + UnexpectedIdentifier: 'Unexpected identifier', + UnexpectedReserved: 'Unexpected reserved word', + UnexpectedEOS: 'Unexpected end of input', + NewlineAfterThrow: 'Illegal newline after throw', + InvalidRegExp: 'Invalid regular expression', + UnterminatedRegExp: 'Invalid regular expression: missing /', + InvalidLHSInAssignment: 'Invalid left-hand side in assignment', + InvalidLHSInForIn: 'Invalid left-hand side in for-in', + MultipleDefaultsInSwitch: 'More than one default clause in switch statement', + NoCatchOrFinally: 'Missing catch or finally after try', + UnknownLabel: 'Undefined label \'%0\'', + Redeclaration: '%0 \'%1\' has already been declared', + IllegalContinue: 'Illegal continue statement', + IllegalBreak: 'Illegal break statement', + IllegalReturn: 'Illegal return statement', + StrictModeWith: 'Strict mode code may not include a with statement', + StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode', + StrictVarName: 'Variable name may not be eval or arguments in strict mode', + StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode', + StrictParamDupe: 'Strict mode function may not have duplicate parameter names', + StrictFunctionName: 'Function name may not be eval or arguments in strict mode', + StrictOctalLiteral: 'Octal literals are not allowed in strict mode.', + StrictDelete: 'Delete of an unqualified identifier in strict mode.', + StrictDuplicateProperty: 'Duplicate data property in object literal not allowed in strict mode', + AccessorDataProperty: 'Object literal may not have data and accessor property with the same name', + AccessorGetSet: 'Object literal may not have multiple get/set accessors with the same name', + StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode', + StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode', + StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode', + StrictReservedWord: 'Use of future reserved word in strict mode' + }; + + // See also tools/generate-unicode-regex.py. + Regex = { + NonAsciiIdentifierStart: new RegExp('[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F0\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]'), + NonAsciiIdentifierPart: new RegExp('[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0\u08A2-\u08AC\u08E4-\u08FE\u0900-\u0963\u0966-\u096F\u0971-\u0977\u0979-\u097F\u0981-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C01-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C82\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D02\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F0\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191C\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1D00-\u1DE6\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA697\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A\uAA7B\uAA80-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE26\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]') + }; + + // Ensure the condition is true, otherwise throw an error. + // This is only to have a better contract semantic, i.e. another safety net + // to catch a logic error. The condition shall be fulfilled in normal case. + // Do NOT use this to enforce a certain condition on any user input. + + function assert(condition, message) { + /* istanbul ignore if */ + if (!condition) { + throw new Error('ASSERT: ' + message); + } + } + + function isDecimalDigit(ch) { + return (ch >= 48 && ch <= 57); // 0..9 + } + + function isHexDigit(ch) { + return '0123456789abcdefABCDEF'.indexOf(ch) >= 0; + } + + function isOctalDigit(ch) { + return '01234567'.indexOf(ch) >= 0; + } + + + // 7.2 White Space + + function isWhiteSpace(ch) { + return (ch === 0x20) || (ch === 0x09) || (ch === 0x0B) || (ch === 0x0C) || (ch === 0xA0) || + (ch >= 0x1680 && [0x1680, 0x180E, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(ch) >= 0); + } + + // 7.3 Line Terminators + + function isLineTerminator(ch) { + return (ch === 0x0A) || (ch === 0x0D) || (ch === 0x2028) || (ch === 0x2029); + } + + // 7.6 Identifier Names and Identifiers + + function isIdentifierStart(ch) { + return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore) + (ch >= 0x41 && ch <= 0x5A) || // A..Z + (ch >= 0x61 && ch <= 0x7A) || // a..z + (ch === 0x5C) || // \ (backslash) + ((ch >= 0x80) && Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch))); + } + + function isIdentifierPart(ch) { + return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore) + (ch >= 0x41 && ch <= 0x5A) || // A..Z + (ch >= 0x61 && ch <= 0x7A) || // a..z + (ch >= 0x30 && ch <= 0x39) || // 0..9 + (ch === 0x5C) || // \ (backslash) + ((ch >= 0x80) && Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch))); + } + + // 7.6.1.2 Future Reserved Words + + function isFutureReservedWord(id) { + switch (id) { + case 'class': + case 'enum': + case 'export': + case 'extends': + case 'import': + case 'super': + return true; + default: + return false; + } + } + + function isStrictModeReservedWord(id) { + switch (id) { + case 'implements': + case 'interface': + case 'package': + case 'private': + case 'protected': + case 'public': + case 'static': + case 'yield': + case 'let': + return true; + default: + return false; + } + } + + function isRestrictedWord(id) { + return id === 'eval' || id === 'arguments'; + } + + // 7.6.1.1 Keywords + + function isKeyword(id) { + if (strict && isStrictModeReservedWord(id)) { + return true; + } + + // 'const' is specialized as Keyword in V8. + // 'yield' and 'let' are for compatiblity with SpiderMonkey and ES.next. + // Some others are from future reserved words. + + switch (id.length) { + case 2: + return (id === 'if') || (id === 'in') || (id === 'do'); + case 3: + return (id === 'var') || (id === 'for') || (id === 'new') || + (id === 'try') || (id === 'let'); + case 4: + return (id === 'this') || (id === 'else') || (id === 'case') || + (id === 'void') || (id === 'with') || (id === 'enum'); + case 5: + return (id === 'while') || (id === 'break') || (id === 'catch') || + (id === 'throw') || (id === 'const') || (id === 'yield') || + (id === 'class') || (id === 'super'); + case 6: + return (id === 'return') || (id === 'typeof') || (id === 'delete') || + (id === 'switch') || (id === 'export') || (id === 'import'); + case 7: + return (id === 'default') || (id === 'finally') || (id === 'extends'); + case 8: + return (id === 'function') || (id === 'continue') || (id === 'debugger'); + case 10: + return (id === 'instanceof'); + default: + return false; + } + } + + // 7.4 Comments + + function addComment(type, value, start, end, loc) { + var comment, attacher; + + assert(typeof start === 'number', 'Comment must have valid position'); + + // Because the way the actual token is scanned, often the comments + // (if any) are skipped twice during the lexical analysis. + // Thus, we need to skip adding a comment if the comment array already + // handled it. + if (state.lastCommentStart >= start) { + return; + } + state.lastCommentStart = start; + + comment = { + type: type, + value: value + }; + if (extra.range) { + comment.range = [start, end]; + } + if (extra.loc) { + comment.loc = loc; + } + extra.comments.push(comment); + if (extra.attachComment) { + extra.leadingComments.push(comment); + extra.trailingComments.push(comment); + } + } + + function skipSingleLineComment(offset) { + var start, loc, ch, comment; + + start = index - offset; + loc = { + start: { + line: lineNumber, + column: index - lineStart - offset + } + }; + + while (index < length) { + ch = source.charCodeAt(index); + ++index; + if (isLineTerminator(ch)) { + if (extra.comments) { + comment = source.slice(start + offset, index - 1); + loc.end = { + line: lineNumber, + column: index - lineStart - 1 + }; + addComment('Line', comment, start, index - 1, loc); + } + if (ch === 13 && source.charCodeAt(index) === 10) { + ++index; + } + ++lineNumber; + lineStart = index; + return; + } + } + + if (extra.comments) { + comment = source.slice(start + offset, index); + loc.end = { + line: lineNumber, + column: index - lineStart + }; + addComment('Line', comment, start, index, loc); + } + } + + function skipMultiLineComment() { + var start, loc, ch, comment; + + if (extra.comments) { + start = index - 2; + loc = { + start: { + line: lineNumber, + column: index - lineStart - 2 + } + }; + } + + while (index < length) { + ch = source.charCodeAt(index); + if (isLineTerminator(ch)) { + if (ch === 0x0D && source.charCodeAt(index + 1) === 0x0A) { + ++index; + } + ++lineNumber; + ++index; + lineStart = index; + if (index >= length) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + } else if (ch === 0x2A) { + // Block comment ends with '*/'. + if (source.charCodeAt(index + 1) === 0x2F) { + ++index; + ++index; + if (extra.comments) { + comment = source.slice(start + 2, index - 2); + loc.end = { + line: lineNumber, + column: index - lineStart + }; + addComment('Block', comment, start, index, loc); + } + return; + } + ++index; + } else { + ++index; + } + } + + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + + function skipComment() { + var ch, start; + + start = (index === 0); + while (index < length) { + ch = source.charCodeAt(index); + + if (isWhiteSpace(ch)) { + ++index; + } else if (isLineTerminator(ch)) { + ++index; + if (ch === 0x0D && source.charCodeAt(index) === 0x0A) { + ++index; + } + ++lineNumber; + lineStart = index; + start = true; + } else if (ch === 0x2F) { // U+002F is '/' + ch = source.charCodeAt(index + 1); + if (ch === 0x2F) { + ++index; + ++index; + skipSingleLineComment(2); + start = true; + } else if (ch === 0x2A) { // U+002A is '*' + ++index; + ++index; + skipMultiLineComment(); + } else { + break; + } + } else if (start && ch === 0x2D) { // U+002D is '-' + // U+003E is '>' + if ((source.charCodeAt(index + 1) === 0x2D) && (source.charCodeAt(index + 2) === 0x3E)) { + // '-->' is a single-line comment + index += 3; + skipSingleLineComment(3); + } else { + break; + } + } else if (ch === 0x3C) { // U+003C is '<' + if (source.slice(index + 1, index + 4) === '!--') { + ++index; // `<` + ++index; // `!` + ++index; // `-` + ++index; // `-` + skipSingleLineComment(4); + } else { + break; + } + } else { + break; + } + } + } + + function scanHexEscape(prefix) { + var i, len, ch, code = 0; + + len = (prefix === 'u') ? 4 : 2; + for (i = 0; i < len; ++i) { + if (index < length && isHexDigit(source[index])) { + ch = source[index++]; + code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); + } else { + return ''; + } + } + return String.fromCharCode(code); + } + + function getEscapedIdentifier() { + var ch, id; + + ch = source.charCodeAt(index++); + id = String.fromCharCode(ch); + + // '\u' (U+005C, U+0075) denotes an escaped character. + if (ch === 0x5C) { + if (source.charCodeAt(index) !== 0x75) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + ++index; + ch = scanHexEscape('u'); + if (!ch || ch === '\\' || !isIdentifierStart(ch.charCodeAt(0))) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + id = ch; + } + + while (index < length) { + ch = source.charCodeAt(index); + if (!isIdentifierPart(ch)) { + break; + } + ++index; + id += String.fromCharCode(ch); + + // '\u' (U+005C, U+0075) denotes an escaped character. + if (ch === 0x5C) { + id = id.substr(0, id.length - 1); + if (source.charCodeAt(index) !== 0x75) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + ++index; + ch = scanHexEscape('u'); + if (!ch || ch === '\\' || !isIdentifierPart(ch.charCodeAt(0))) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + id += ch; + } + } + + return id; + } + + function getIdentifier() { + var start, ch; + + start = index++; + while (index < length) { + ch = source.charCodeAt(index); + if (ch === 0x5C) { + // Blackslash (U+005C) marks Unicode escape sequence. + index = start; + return getEscapedIdentifier(); + } + if (isIdentifierPart(ch)) { + ++index; + } else { + break; + } + } + + return source.slice(start, index); + } + + function scanIdentifier() { + var start, id, type; + + start = index; + + // Backslash (U+005C) starts an escaped character. + id = (source.charCodeAt(index) === 0x5C) ? getEscapedIdentifier() : getIdentifier(); + + // There is no keyword or literal with only one character. + // Thus, it must be an identifier. + if (id.length === 1) { + type = Token.Identifier; + } else if (isKeyword(id)) { + type = Token.Keyword; + } else if (id === 'null') { + type = Token.NullLiteral; + } else if (id === 'true' || id === 'false') { + type = Token.BooleanLiteral; + } else { + type = Token.Identifier; + } + + return { + type: type, + value: id, + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + } + + + // 7.7 Punctuators + + function scanPunctuator() { + var start = index, + code = source.charCodeAt(index), + code2, + ch1 = source[index], + ch2, + ch3, + ch4; + + switch (code) { + + // Check for most common single-character punctuators. + case 0x2E: // . dot + case 0x28: // ( open bracket + case 0x29: // ) close bracket + case 0x3B: // ; semicolon + case 0x2C: // , comma + case 0x7B: // { open curly brace + case 0x7D: // } close curly brace + case 0x5B: // [ + case 0x5D: // ] + case 0x3A: // : + case 0x3F: // ? + case 0x7E: // ~ + ++index; + if (extra.tokenize) { + if (code === 0x28) { + extra.openParenToken = extra.tokens.length; + } else if (code === 0x7B) { + extra.openCurlyToken = extra.tokens.length; + } + } + return { + type: Token.Punctuator, + value: String.fromCharCode(code), + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + + default: + code2 = source.charCodeAt(index + 1); + + // '=' (U+003D) marks an assignment or comparison operator. + if (code2 === 0x3D) { + switch (code) { + case 0x2B: // + + case 0x2D: // - + case 0x2F: // / + case 0x3C: // < + case 0x3E: // > + case 0x5E: // ^ + case 0x7C: // | + case 0x25: // % + case 0x26: // & + case 0x2A: // * + index += 2; + return { + type: Token.Punctuator, + value: String.fromCharCode(code) + String.fromCharCode(code2), + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + + case 0x21: // ! + case 0x3D: // = + index += 2; + + // !== and === + if (source.charCodeAt(index) === 0x3D) { + ++index; + } + return { + type: Token.Punctuator, + value: source.slice(start, index), + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + } + } + } + + // 4-character punctuator: >>>= + + ch4 = source.substr(index, 4); + + if (ch4 === '>>>=') { + index += 4; + return { + type: Token.Punctuator, + value: ch4, + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + } + + // 3-character punctuators: === !== >>> <<= >>= + + ch3 = ch4.substr(0, 3); + + if (ch3 === '>>>' || ch3 === '<<=' || ch3 === '>>=') { + index += 3; + return { + type: Token.Punctuator, + value: ch3, + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + } + + // Other 2-character punctuators: ++ -- << >> && || + ch2 = ch3.substr(0, 2); + + if ((ch1 === ch2[1] && ('+-<>&|'.indexOf(ch1) >= 0)) || ch2 === '=>') { + index += 2; + return { + type: Token.Punctuator, + value: ch2, + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + } + + // 1-character punctuators: < > = ! + - * % & | ^ / + if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) { + ++index; + return { + type: Token.Punctuator, + value: ch1, + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + } + + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + + // 7.8.3 Numeric Literals + + function scanHexLiteral(start) { + var number = ''; + + while (index < length) { + if (!isHexDigit(source[index])) { + break; + } + number += source[index++]; + } + + if (number.length === 0) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + + if (isIdentifierStart(source.charCodeAt(index))) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + + return { + type: Token.NumericLiteral, + value: parseInt('0x' + number, 16), + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + } + + function scanOctalLiteral(start) { + var number = '0' + source[index++]; + while (index < length) { + if (!isOctalDigit(source[index])) { + break; + } + number += source[index++]; + } + + if (isIdentifierStart(source.charCodeAt(index)) || isDecimalDigit(source.charCodeAt(index))) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + + return { + type: Token.NumericLiteral, + value: parseInt(number, 8), + octal: true, + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + } + + function scanNumericLiteral() { + var number, start, ch; + + ch = source[index]; + assert(isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'), + 'Numeric literal must start with a decimal digit or a decimal point'); + + start = index; + number = ''; + if (ch !== '.') { + number = source[index++]; + ch = source[index]; + + // Hex number starts with '0x'. + // Octal number starts with '0'. + if (number === '0') { + if (ch === 'x' || ch === 'X') { + ++index; + return scanHexLiteral(start); + } + if (isOctalDigit(ch)) { + return scanOctalLiteral(start); + } + + // decimal number starts with '0' such as '09' is illegal. + if (ch && isDecimalDigit(ch.charCodeAt(0))) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + } + + while (isDecimalDigit(source.charCodeAt(index))) { + number += source[index++]; + } + ch = source[index]; + } + + if (ch === '.') { + number += source[index++]; + while (isDecimalDigit(source.charCodeAt(index))) { + number += source[index++]; + } + ch = source[index]; + } + + if (ch === 'e' || ch === 'E') { + number += source[index++]; + + ch = source[index]; + if (ch === '+' || ch === '-') { + number += source[index++]; + } + if (isDecimalDigit(source.charCodeAt(index))) { + while (isDecimalDigit(source.charCodeAt(index))) { + number += source[index++]; + } + } else { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + } + + if (isIdentifierStart(source.charCodeAt(index))) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + + return { + type: Token.NumericLiteral, + value: parseFloat(number), + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + } + + // 7.8.4 String Literals + + function scanStringLiteral() { + var str = '', quote, start, ch, code, unescaped, restore, octal = false, startLineNumber, startLineStart; + startLineNumber = lineNumber; + startLineStart = lineStart; + + quote = source[index]; + assert((quote === '\'' || quote === '"'), + 'String literal must starts with a quote'); + + start = index; + ++index; + + while (index < length) { + ch = source[index++]; + + if (ch === quote) { + quote = ''; + break; + } else if (ch === '\\') { + ch = source[index++]; + if (!ch || !isLineTerminator(ch.charCodeAt(0))) { + switch (ch) { + case 'u': + case 'x': + restore = index; + unescaped = scanHexEscape(ch); + if (unescaped) { + str += unescaped; + } else { + index = restore; + str += ch; + } + break; + case 'n': + str += '\n'; + break; + case 'r': + str += '\r'; + break; + case 't': + str += '\t'; + break; + case 'b': + str += '\b'; + break; + case 'f': + str += '\f'; + break; + case 'v': + str += '\x0B'; + break; + + default: + if (isOctalDigit(ch)) { + code = '01234567'.indexOf(ch); + + // \0 is not octal escape sequence + if (code !== 0) { + octal = true; + } + + if (index < length && isOctalDigit(source[index])) { + octal = true; + code = code * 8 + '01234567'.indexOf(source[index++]); + + // 3 digits are only allowed when string starts + // with 0, 1, 2, 3 + if ('0123'.indexOf(ch) >= 0 && + index < length && + isOctalDigit(source[index])) { + code = code * 8 + '01234567'.indexOf(source[index++]); + } + } + str += String.fromCharCode(code); + } else { + str += ch; + } + break; + } + } else { + ++lineNumber; + if (ch === '\r' && source[index] === '\n') { + ++index; + } + lineStart = index; + } + } else if (isLineTerminator(ch.charCodeAt(0))) { + break; + } else { + str += ch; + } + } + + if (quote !== '') { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + + return { + type: Token.StringLiteral, + value: str, + octal: octal, + startLineNumber: startLineNumber, + startLineStart: startLineStart, + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + } + + function testRegExp(pattern, flags) { + var value; + try { + value = new RegExp(pattern, flags); + } catch (e) { + throwError({}, Messages.InvalidRegExp); + } + return value; + } + + function scanRegExpBody() { + var ch, str, classMarker, terminated, body; + + ch = source[index]; + assert(ch === '/', 'Regular expression literal must start with a slash'); + str = source[index++]; + + classMarker = false; + terminated = false; + while (index < length) { + ch = source[index++]; + str += ch; + if (ch === '\\') { + ch = source[index++]; + // ECMA-262 7.8.5 + if (isLineTerminator(ch.charCodeAt(0))) { + throwError({}, Messages.UnterminatedRegExp); + } + str += ch; + } else if (isLineTerminator(ch.charCodeAt(0))) { + throwError({}, Messages.UnterminatedRegExp); + } else if (classMarker) { + if (ch === ']') { + classMarker = false; + } + } else { + if (ch === '/') { + terminated = true; + break; + } else if (ch === '[') { + classMarker = true; + } + } + } + + if (!terminated) { + throwError({}, Messages.UnterminatedRegExp); + } + + // Exclude leading and trailing slash. + body = str.substr(1, str.length - 2); + return { + value: body, + literal: str + }; + } + + function scanRegExpFlags() { + var ch, str, flags, restore; + + str = ''; + flags = ''; + while (index < length) { + ch = source[index]; + if (!isIdentifierPart(ch.charCodeAt(0))) { + break; + } + + ++index; + if (ch === '\\' && index < length) { + ch = source[index]; + if (ch === 'u') { + ++index; + restore = index; + ch = scanHexEscape('u'); + if (ch) { + flags += ch; + for (str += '\\u'; restore < index; ++restore) { + str += source[restore]; + } + } else { + index = restore; + flags += 'u'; + str += '\\u'; + } + throwErrorTolerant({}, Messages.UnexpectedToken, 'ILLEGAL'); + } else { + str += '\\'; + throwErrorTolerant({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + } else { + flags += ch; + str += ch; + } + } + + return { + value: flags, + literal: str + }; + } + + function scanRegExp() { + var start, body, flags, pattern, value; + + lookahead = null; + skipComment(); + start = index; + + body = scanRegExpBody(); + flags = scanRegExpFlags(); + value = testRegExp(body.value, flags.value); + + if (extra.tokenize) { + return { + type: Token.RegularExpression, + value: value, + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + } + + return { + literal: body.literal + flags.literal, + value: value, + start: start, + end: index + }; + } + + function collectRegex() { + var pos, loc, regex, token; + + skipComment(); + + pos = index; + loc = { + start: { + line: lineNumber, + column: index - lineStart + } + }; + + regex = scanRegExp(); + loc.end = { + line: lineNumber, + column: index - lineStart + }; + + /* istanbul ignore next */ + if (!extra.tokenize) { + // Pop the previous token, which is likely '/' or '/=' + if (extra.tokens.length > 0) { + token = extra.tokens[extra.tokens.length - 1]; + if (token.range[0] === pos && token.type === 'Punctuator') { + if (token.value === '/' || token.value === '/=') { + extra.tokens.pop(); + } + } + } + + extra.tokens.push({ + type: 'RegularExpression', + value: regex.literal, + range: [pos, index], + loc: loc + }); + } + + return regex; + } + + function isIdentifierName(token) { + return token.type === Token.Identifier || + token.type === Token.Keyword || + token.type === Token.BooleanLiteral || + token.type === Token.NullLiteral; + } + + function advanceSlash() { + var prevToken, + checkToken; + // Using the following algorithm: + // https://github.com/mozilla/sweet.js/wiki/design + prevToken = extra.tokens[extra.tokens.length - 1]; + if (!prevToken) { + // Nothing before that: it cannot be a division. + return collectRegex(); + } + if (prevToken.type === 'Punctuator') { + if (prevToken.value === ']') { + return scanPunctuator(); + } + if (prevToken.value === ')') { + checkToken = extra.tokens[extra.openParenToken - 1]; + if (checkToken && + checkToken.type === 'Keyword' && + (checkToken.value === 'if' || + checkToken.value === 'while' || + checkToken.value === 'for' || + checkToken.value === 'with')) { + return collectRegex(); + } + return scanPunctuator(); + } + if (prevToken.value === '}') { + // Dividing a function by anything makes little sense, + // but we have to check for that. + if (extra.tokens[extra.openCurlyToken - 3] && + extra.tokens[extra.openCurlyToken - 3].type === 'Keyword') { + // Anonymous function. + checkToken = extra.tokens[extra.openCurlyToken - 4]; + if (!checkToken) { + return scanPunctuator(); + } + } else if (extra.tokens[extra.openCurlyToken - 4] && + extra.tokens[extra.openCurlyToken - 4].type === 'Keyword') { + // Named function. + checkToken = extra.tokens[extra.openCurlyToken - 5]; + if (!checkToken) { + return collectRegex(); + } + } else { + return scanPunctuator(); + } + // checkToken determines whether the function is + // a declaration or an expression. + if (FnExprTokens.indexOf(checkToken.value) >= 0) { + // It is an expression. + return scanPunctuator(); + } + // It is a declaration. + return collectRegex(); + } + return collectRegex(); + } + if (prevToken.type === 'Keyword') { + return collectRegex(); + } + return scanPunctuator(); + } + + function advance() { + var ch; + + skipComment(); + + if (index >= length) { + return { + type: Token.EOF, + lineNumber: lineNumber, + lineStart: lineStart, + start: index, + end: index + }; + } + + ch = source.charCodeAt(index); + + if (isIdentifierStart(ch)) { + return scanIdentifier(); + } + + // Very common: ( and ) and ; + if (ch === 0x28 || ch === 0x29 || ch === 0x3B) { + return scanPunctuator(); + } + + // String literal starts with single quote (U+0027) or double quote (U+0022). + if (ch === 0x27 || ch === 0x22) { + return scanStringLiteral(); + } + + + // Dot (.) U+002E can also start a floating-point number, hence the need + // to check the next character. + if (ch === 0x2E) { + if (isDecimalDigit(source.charCodeAt(index + 1))) { + return scanNumericLiteral(); + } + return scanPunctuator(); + } + + if (isDecimalDigit(ch)) { + return scanNumericLiteral(); + } + + // Slash (/) U+002F can also start a regex. + if (extra.tokenize && ch === 0x2F) { + return advanceSlash(); + } + + return scanPunctuator(); + } + + function collectToken() { + var loc, token, range, value; + + skipComment(); + loc = { + start: { + line: lineNumber, + column: index - lineStart + } + }; + + token = advance(); + loc.end = { + line: lineNumber, + column: index - lineStart + }; + + if (token.type !== Token.EOF) { + value = source.slice(token.start, token.end); + extra.tokens.push({ + type: TokenName[token.type], + value: value, + range: [token.start, token.end], + loc: loc + }); + } + + return token; + } + + function lex() { + var token; + + token = lookahead; + index = token.end; + lineNumber = token.lineNumber; + lineStart = token.lineStart; + + lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance(); + + index = token.end; + lineNumber = token.lineNumber; + lineStart = token.lineStart; + + return token; + } + + function peek() { + var pos, line, start; + + pos = index; + line = lineNumber; + start = lineStart; + lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance(); + index = pos; + lineNumber = line; + lineStart = start; + } + + function Position(line, column) { + this.line = line; + this.column = column; + } + + function SourceLocation(startLine, startColumn, line, column) { + this.start = new Position(startLine, startColumn); + this.end = new Position(line, column); + } + + SyntaxTreeDelegate = { + + name: 'SyntaxTree', + + processComment: function (node) { + var lastChild, trailingComments; + + if (node.type === Syntax.Program) { + if (node.body.length > 0) { + return; + } + } + + if (extra.trailingComments.length > 0) { + if (extra.trailingComments[0].range[0] >= node.range[1]) { + trailingComments = extra.trailingComments; + extra.trailingComments = []; + } else { + extra.trailingComments.length = 0; + } + } else { + if (extra.bottomRightStack.length > 0 && + extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments && + extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments[0].range[0] >= node.range[1]) { + trailingComments = extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments; + delete extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments; + } + } + + // Eating the stack. + while (extra.bottomRightStack.length > 0 && extra.bottomRightStack[extra.bottomRightStack.length - 1].range[0] >= node.range[0]) { + lastChild = extra.bottomRightStack.pop(); + } + + if (lastChild) { + if (lastChild.leadingComments && lastChild.leadingComments[lastChild.leadingComments.length - 1].range[1] <= node.range[0]) { + node.leadingComments = lastChild.leadingComments; + delete lastChild.leadingComments; + } + } else if (extra.leadingComments.length > 0 && extra.leadingComments[extra.leadingComments.length - 1].range[1] <= node.range[0]) { + node.leadingComments = extra.leadingComments; + extra.leadingComments = []; + } + + + if (trailingComments) { + node.trailingComments = trailingComments; + } + + extra.bottomRightStack.push(node); + }, + + markEnd: function (node, startToken) { + if (extra.range) { + node.range = [startToken.start, index]; + } + if (extra.loc) { + node.loc = new SourceLocation( + startToken.startLineNumber === undefined ? startToken.lineNumber : startToken.startLineNumber, + startToken.start - (startToken.startLineStart === undefined ? startToken.lineStart : startToken.startLineStart), + lineNumber, + index - lineStart + ); + this.postProcess(node); + } + + if (extra.attachComment) { + this.processComment(node); + } + return node; + }, + + postProcess: function (node) { + if (extra.source) { + node.loc.source = extra.source; + } + return node; + }, + + createArrayExpression: function (elements) { + return { + type: Syntax.ArrayExpression, + elements: elements + }; + }, + + createAssignmentExpression: function (operator, left, right) { + return { + type: Syntax.AssignmentExpression, + operator: operator, + left: left, + right: right + }; + }, + + createBinaryExpression: function (operator, left, right) { + var type = (operator === '||' || operator === '&&') ? Syntax.LogicalExpression : + Syntax.BinaryExpression; + return { + type: type, + operator: operator, + left: left, + right: right + }; + }, + + createBlockStatement: function (body) { + return { + type: Syntax.BlockStatement, + body: body + }; + }, + + createBreakStatement: function (label) { + return { + type: Syntax.BreakStatement, + label: label + }; + }, + + createCallExpression: function (callee, args) { + return { + type: Syntax.CallExpression, + callee: callee, + 'arguments': args + }; + }, + + createCatchClause: function (param, body) { + return { + type: Syntax.CatchClause, + param: param, + body: body + }; + }, + + createConditionalExpression: function (test, consequent, alternate) { + return { + type: Syntax.ConditionalExpression, + test: test, + consequent: consequent, + alternate: alternate + }; + }, + + createContinueStatement: function (label) { + return { + type: Syntax.ContinueStatement, + label: label + }; + }, + + createDebuggerStatement: function () { + return { + type: Syntax.DebuggerStatement + }; + }, + + createDoWhileStatement: function (body, test) { + return { + type: Syntax.DoWhileStatement, + body: body, + test: test + }; + }, + + createEmptyStatement: function () { + return { + type: Syntax.EmptyStatement + }; + }, + + createExpressionStatement: function (expression) { + return { + type: Syntax.ExpressionStatement, + expression: expression + }; + }, + + createForStatement: function (init, test, update, body) { + return { + type: Syntax.ForStatement, + init: init, + test: test, + update: update, + body: body + }; + }, + + createForInStatement: function (left, right, body) { + return { + type: Syntax.ForInStatement, + left: left, + right: right, + body: body, + each: false + }; + }, + + createFunctionDeclaration: function (id, params, defaults, body) { + return { + type: Syntax.FunctionDeclaration, + id: id, + params: params, + defaults: defaults, + body: body, + rest: null, + generator: false, + expression: false + }; + }, + + createFunctionExpression: function (id, params, defaults, body) { + return { + type: Syntax.FunctionExpression, + id: id, + params: params, + defaults: defaults, + body: body, + rest: null, + generator: false, + expression: false + }; + }, + + createIdentifier: function (name) { + return { + type: Syntax.Identifier, + name: name + }; + }, + + createIfStatement: function (test, consequent, alternate) { + return { + type: Syntax.IfStatement, + test: test, + consequent: consequent, + alternate: alternate + }; + }, + + createLabeledStatement: function (label, body) { + return { + type: Syntax.LabeledStatement, + label: label, + body: body + }; + }, + + createLiteral: function (token) { + return { + type: Syntax.Literal, + value: token.value, + raw: source.slice(token.start, token.end) + }; + }, + + createMemberExpression: function (accessor, object, property) { + return { + type: Syntax.MemberExpression, + computed: accessor === '[', + object: object, + property: property + }; + }, + + createNewExpression: function (callee, args) { + return { + type: Syntax.NewExpression, + callee: callee, + 'arguments': args + }; + }, + + createObjectExpression: function (properties) { + return { + type: Syntax.ObjectExpression, + properties: properties + }; + }, + + createPostfixExpression: function (operator, argument) { + return { + type: Syntax.UpdateExpression, + operator: operator, + argument: argument, + prefix: false + }; + }, + + createProgram: function (body) { + return { + type: Syntax.Program, + body: body + }; + }, + + createProperty: function (kind, key, value) { + return { + type: Syntax.Property, + key: key, + value: value, + kind: kind + }; + }, + + createReturnStatement: function (argument) { + return { + type: Syntax.ReturnStatement, + argument: argument + }; + }, + + createSequenceExpression: function (expressions) { + return { + type: Syntax.SequenceExpression, + expressions: expressions + }; + }, + + createSwitchCase: function (test, consequent) { + return { + type: Syntax.SwitchCase, + test: test, + consequent: consequent + }; + }, + + createSwitchStatement: function (discriminant, cases) { + return { + type: Syntax.SwitchStatement, + discriminant: discriminant, + cases: cases + }; + }, + + createThisExpression: function () { + return { + type: Syntax.ThisExpression + }; + }, + + createThrowStatement: function (argument) { + return { + type: Syntax.ThrowStatement, + argument: argument + }; + }, + + createTryStatement: function (block, guardedHandlers, handlers, finalizer) { + return { + type: Syntax.TryStatement, + block: block, + guardedHandlers: guardedHandlers, + handlers: handlers, + finalizer: finalizer + }; + }, + + createUnaryExpression: function (operator, argument) { + if (operator === '++' || operator === '--') { + return { + type: Syntax.UpdateExpression, + operator: operator, + argument: argument, + prefix: true + }; + } + return { + type: Syntax.UnaryExpression, + operator: operator, + argument: argument, + prefix: true + }; + }, + + createVariableDeclaration: function (declarations, kind) { + return { + type: Syntax.VariableDeclaration, + declarations: declarations, + kind: kind + }; + }, + + createVariableDeclarator: function (id, init) { + return { + type: Syntax.VariableDeclarator, + id: id, + init: init + }; + }, + + createWhileStatement: function (test, body) { + return { + type: Syntax.WhileStatement, + test: test, + body: body + }; + }, + + createWithStatement: function (object, body) { + return { + type: Syntax.WithStatement, + object: object, + body: body + }; + } + }; + + // Return true if there is a line terminator before the next token. + + function peekLineTerminator() { + var pos, line, start, found; + + pos = index; + line = lineNumber; + start = lineStart; + skipComment(); + found = lineNumber !== line; + index = pos; + lineNumber = line; + lineStart = start; + + return found; + } + + // Throw an exception + + function throwError(token, messageFormat) { + var error, + args = Array.prototype.slice.call(arguments, 2), + msg = messageFormat.replace( + /%(\d)/g, + function (whole, index) { + assert(index < args.length, 'Message reference must be in range'); + return args[index]; + } + ); + + if (typeof token.lineNumber === 'number') { + error = new Error('Line ' + token.lineNumber + ': ' + msg); + error.index = token.start; + error.lineNumber = token.lineNumber; + error.column = token.start - lineStart + 1; + } else { + error = new Error('Line ' + lineNumber + ': ' + msg); + error.index = index; + error.lineNumber = lineNumber; + error.column = index - lineStart + 1; + } + + error.description = msg; + throw error; + } + + function throwErrorTolerant() { + try { + throwError.apply(null, arguments); + } catch (e) { + if (extra.errors) { + extra.errors.push(e); + } else { + throw e; + } + } + } + + + // Throw an exception because of the token. + + function throwUnexpected(token) { + if (token.type === Token.EOF) { + throwError(token, Messages.UnexpectedEOS); + } + + if (token.type === Token.NumericLiteral) { + throwError(token, Messages.UnexpectedNumber); + } + + if (token.type === Token.StringLiteral) { + throwError(token, Messages.UnexpectedString); + } + + if (token.type === Token.Identifier) { + throwError(token, Messages.UnexpectedIdentifier); + } + + if (token.type === Token.Keyword) { + if (isFutureReservedWord(token.value)) { + throwError(token, Messages.UnexpectedReserved); + } else if (strict && isStrictModeReservedWord(token.value)) { + throwErrorTolerant(token, Messages.StrictReservedWord); + return; + } + throwError(token, Messages.UnexpectedToken, token.value); + } + + // BooleanLiteral, NullLiteral, or Punctuator. + throwError(token, Messages.UnexpectedToken, token.value); + } + + // Expect the next token to match the specified punctuator. + // If not, an exception will be thrown. + + function expect(value) { + var token = lex(); + if (token.type !== Token.Punctuator || token.value !== value) { + throwUnexpected(token); + } + } + + // Expect the next token to match the specified keyword. + // If not, an exception will be thrown. + + function expectKeyword(keyword) { + var token = lex(); + if (token.type !== Token.Keyword || token.value !== keyword) { + throwUnexpected(token); + } + } + + // Return true if the next token matches the specified punctuator. + + function match(value) { + return lookahead.type === Token.Punctuator && lookahead.value === value; + } + + // Return true if the next token matches the specified keyword + + function matchKeyword(keyword) { + return lookahead.type === Token.Keyword && lookahead.value === keyword; + } + + // Return true if the next token is an assignment operator + + function matchAssign() { + var op; + + if (lookahead.type !== Token.Punctuator) { + return false; + } + op = lookahead.value; + return op === '=' || + op === '*=' || + op === '/=' || + op === '%=' || + op === '+=' || + op === '-=' || + op === '<<=' || + op === '>>=' || + op === '>>>=' || + op === '&=' || + op === '^=' || + op === '|='; + } + + function consumeSemicolon() { + var line; + + // Catch the very common case first: immediately a semicolon (U+003B). + if (source.charCodeAt(index) === 0x3B || match(';')) { + lex(); + return; + } + + line = lineNumber; + skipComment(); + if (lineNumber !== line) { + return; + } + + if (lookahead.type !== Token.EOF && !match('}')) { + throwUnexpected(lookahead); + } + } + + // Return true if provided expression is LeftHandSideExpression + + function isLeftHandSide(expr) { + return expr.type === Syntax.Identifier || expr.type === Syntax.MemberExpression; + } + + // 11.1.4 Array Initialiser + + function parseArrayInitialiser() { + var elements = [], startToken; + + startToken = lookahead; + expect('['); + + while (!match(']')) { + if (match(',')) { + lex(); + elements.push(null); + } else { + elements.push(parseAssignmentExpression()); + + if (!match(']')) { + expect(','); + } + } + } + + lex(); + + return delegate.markEnd(delegate.createArrayExpression(elements), startToken); + } + + // 11.1.5 Object Initialiser + + function parsePropertyFunction(param, first) { + var previousStrict, body, startToken; + + previousStrict = strict; + startToken = lookahead; + body = parseFunctionSourceElements(); + if (first && strict && isRestrictedWord(param[0].name)) { + throwErrorTolerant(first, Messages.StrictParamName); + } + strict = previousStrict; + return delegate.markEnd(delegate.createFunctionExpression(null, param, [], body), startToken); + } + + function parseObjectPropertyKey() { + var token, startToken; + + startToken = lookahead; + token = lex(); + + // Note: This function is called only from parseObjectProperty(), where + // EOF and Punctuator tokens are already filtered out. + + if (token.type === Token.StringLiteral || token.type === Token.NumericLiteral) { + if (strict && token.octal) { + throwErrorTolerant(token, Messages.StrictOctalLiteral); + } + return delegate.markEnd(delegate.createLiteral(token), startToken); + } + + return delegate.markEnd(delegate.createIdentifier(token.value), startToken); + } + + function parseObjectProperty() { + var token, key, id, value, param, startToken; + + token = lookahead; + startToken = lookahead; + + if (token.type === Token.Identifier) { + + id = parseObjectPropertyKey(); + + // Property Assignment: Getter and Setter. + + if (token.value === 'get' && !match(':')) { + key = parseObjectPropertyKey(); + expect('('); + expect(')'); + value = parsePropertyFunction([]); + return delegate.markEnd(delegate.createProperty('get', key, value), startToken); + } + if (token.value === 'set' && !match(':')) { + key = parseObjectPropertyKey(); + expect('('); + token = lookahead; + if (token.type !== Token.Identifier) { + expect(')'); + throwErrorTolerant(token, Messages.UnexpectedToken, token.value); + value = parsePropertyFunction([]); + } else { + param = [ parseVariableIdentifier() ]; + expect(')'); + value = parsePropertyFunction(param, token); + } + return delegate.markEnd(delegate.createProperty('set', key, value), startToken); + } + expect(':'); + value = parseAssignmentExpression(); + return delegate.markEnd(delegate.createProperty('init', id, value), startToken); + } + if (token.type === Token.EOF || token.type === Token.Punctuator) { + throwUnexpected(token); + } else { + key = parseObjectPropertyKey(); + expect(':'); + value = parseAssignmentExpression(); + return delegate.markEnd(delegate.createProperty('init', key, value), startToken); + } + } + + function parseObjectInitialiser() { + var properties = [], property, name, key, kind, map = {}, toString = String, startToken; + + startToken = lookahead; + + expect('{'); + + while (!match('}')) { + property = parseObjectProperty(); + + if (property.key.type === Syntax.Identifier) { + name = property.key.name; + } else { + name = toString(property.key.value); + } + kind = (property.kind === 'init') ? PropertyKind.Data : (property.kind === 'get') ? PropertyKind.Get : PropertyKind.Set; + + key = '$' + name; + if (Object.prototype.hasOwnProperty.call(map, key)) { + if (map[key] === PropertyKind.Data) { + if (strict && kind === PropertyKind.Data) { + throwErrorTolerant({}, Messages.StrictDuplicateProperty); + } else if (kind !== PropertyKind.Data) { + throwErrorTolerant({}, Messages.AccessorDataProperty); + } + } else { + if (kind === PropertyKind.Data) { + throwErrorTolerant({}, Messages.AccessorDataProperty); + } else if (map[key] & kind) { + throwErrorTolerant({}, Messages.AccessorGetSet); + } + } + map[key] |= kind; + } else { + map[key] = kind; + } + + properties.push(property); + + if (!match('}')) { + expect(','); + } + } + + expect('}'); + + return delegate.markEnd(delegate.createObjectExpression(properties), startToken); + } + + // 11.1.6 The Grouping Operator + + function parseGroupExpression() { + var expr; + + expect('('); + + expr = parseExpression(); + + expect(')'); + + return expr; + } + + + // 11.1 Primary Expressions + + function parsePrimaryExpression() { + var type, token, expr, startToken; + + if (match('(')) { + return parseGroupExpression(); + } + + if (match('[')) { + return parseArrayInitialiser(); + } + + if (match('{')) { + return parseObjectInitialiser(); + } + + type = lookahead.type; + startToken = lookahead; + + if (type === Token.Identifier) { + expr = delegate.createIdentifier(lex().value); + } else if (type === Token.StringLiteral || type === Token.NumericLiteral) { + if (strict && lookahead.octal) { + throwErrorTolerant(lookahead, Messages.StrictOctalLiteral); + } + expr = delegate.createLiteral(lex()); + } else if (type === Token.Keyword) { + if (matchKeyword('function')) { + return parseFunctionExpression(); + } + if (matchKeyword('this')) { + lex(); + expr = delegate.createThisExpression(); + } else { + throwUnexpected(lex()); + } + } else if (type === Token.BooleanLiteral) { + token = lex(); + token.value = (token.value === 'true'); + expr = delegate.createLiteral(token); + } else if (type === Token.NullLiteral) { + token = lex(); + token.value = null; + expr = delegate.createLiteral(token); + } else if (match('/') || match('/=')) { + if (typeof extra.tokens !== 'undefined') { + expr = delegate.createLiteral(collectRegex()); + } else { + expr = delegate.createLiteral(scanRegExp()); + } + peek(); + } else { + throwUnexpected(lex()); + } + + return delegate.markEnd(expr, startToken); + } + + // 11.2 Left-Hand-Side Expressions + + function parseArguments() { + var args = []; + + expect('('); + + if (!match(')')) { + while (index < length) { + args.push(parseAssignmentExpression()); + if (match(')')) { + break; + } + expect(','); + } + } + + expect(')'); + + return args; + } + + function parseNonComputedProperty() { + var token, startToken; + + startToken = lookahead; + token = lex(); + + if (!isIdentifierName(token)) { + throwUnexpected(token); + } + + return delegate.markEnd(delegate.createIdentifier(token.value), startToken); + } + + function parseNonComputedMember() { + expect('.'); + + return parseNonComputedProperty(); + } + + function parseComputedMember() { + var expr; + + expect('['); + + expr = parseExpression(); + + expect(']'); + + return expr; + } + + function parseNewExpression() { + var callee, args, startToken; + + startToken = lookahead; + expectKeyword('new'); + callee = parseLeftHandSideExpression(); + args = match('(') ? parseArguments() : []; + + return delegate.markEnd(delegate.createNewExpression(callee, args), startToken); + } + + function parseLeftHandSideExpressionAllowCall() { + var previousAllowIn, expr, args, property, startToken; + + startToken = lookahead; + + previousAllowIn = state.allowIn; + state.allowIn = true; + expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression(); + state.allowIn = previousAllowIn; + + for (;;) { + if (match('.')) { + property = parseNonComputedMember(); + expr = delegate.createMemberExpression('.', expr, property); + } else if (match('(')) { + args = parseArguments(); + expr = delegate.createCallExpression(expr, args); + } else if (match('[')) { + property = parseComputedMember(); + expr = delegate.createMemberExpression('[', expr, property); + } else { + break; + } + delegate.markEnd(expr, startToken); + } + + return expr; + } + + function parseLeftHandSideExpression() { + var previousAllowIn, expr, property, startToken; + + startToken = lookahead; + + previousAllowIn = state.allowIn; + expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression(); + state.allowIn = previousAllowIn; + + while (match('.') || match('[')) { + if (match('[')) { + property = parseComputedMember(); + expr = delegate.createMemberExpression('[', expr, property); + } else { + property = parseNonComputedMember(); + expr = delegate.createMemberExpression('.', expr, property); + } + delegate.markEnd(expr, startToken); + } + + return expr; + } + + // 11.3 Postfix Expressions + + function parsePostfixExpression() { + var expr, token, startToken = lookahead; + + expr = parseLeftHandSideExpressionAllowCall(); + + if (lookahead.type === Token.Punctuator) { + if ((match('++') || match('--')) && !peekLineTerminator()) { + // 11.3.1, 11.3.2 + if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { + throwErrorTolerant({}, Messages.StrictLHSPostfix); + } + + if (!isLeftHandSide(expr)) { + throwErrorTolerant({}, Messages.InvalidLHSInAssignment); + } + + token = lex(); + expr = delegate.markEnd(delegate.createPostfixExpression(token.value, expr), startToken); + } + } + + return expr; + } + + // 11.4 Unary Operators + + function parseUnaryExpression() { + var token, expr, startToken; + + if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) { + expr = parsePostfixExpression(); + } else if (match('++') || match('--')) { + startToken = lookahead; + token = lex(); + expr = parseUnaryExpression(); + // 11.4.4, 11.4.5 + if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { + throwErrorTolerant({}, Messages.StrictLHSPrefix); + } + + if (!isLeftHandSide(expr)) { + throwErrorTolerant({}, Messages.InvalidLHSInAssignment); + } + + expr = delegate.createUnaryExpression(token.value, expr); + expr = delegate.markEnd(expr, startToken); + } else if (match('+') || match('-') || match('~') || match('!')) { + startToken = lookahead; + token = lex(); + expr = parseUnaryExpression(); + expr = delegate.createUnaryExpression(token.value, expr); + expr = delegate.markEnd(expr, startToken); + } else if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) { + startToken = lookahead; + token = lex(); + expr = parseUnaryExpression(); + expr = delegate.createUnaryExpression(token.value, expr); + expr = delegate.markEnd(expr, startToken); + if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) { + throwErrorTolerant({}, Messages.StrictDelete); + } + } else { + expr = parsePostfixExpression(); + } + + return expr; + } + + function binaryPrecedence(token, allowIn) { + var prec = 0; + + if (token.type !== Token.Punctuator && token.type !== Token.Keyword) { + return 0; + } + + switch (token.value) { + case '||': + prec = 1; + break; + + case '&&': + prec = 2; + break; + + case '|': + prec = 3; + break; + + case '^': + prec = 4; + break; + + case '&': + prec = 5; + break; + + case '==': + case '!=': + case '===': + case '!==': + prec = 6; + break; + + case '<': + case '>': + case '<=': + case '>=': + case 'instanceof': + prec = 7; + break; + + case 'in': + prec = allowIn ? 7 : 0; + break; + + case '<<': + case '>>': + case '>>>': + prec = 8; + break; + + case '+': + case '-': + prec = 9; + break; + + case '*': + case '/': + case '%': + prec = 11; + break; + + default: + break; + } + + return prec; + } + + // 11.5 Multiplicative Operators + // 11.6 Additive Operators + // 11.7 Bitwise Shift Operators + // 11.8 Relational Operators + // 11.9 Equality Operators + // 11.10 Binary Bitwise Operators + // 11.11 Binary Logical Operators + + function parseBinaryExpression() { + var marker, markers, expr, token, prec, stack, right, operator, left, i; + + marker = lookahead; + left = parseUnaryExpression(); + + token = lookahead; + prec = binaryPrecedence(token, state.allowIn); + if (prec === 0) { + return left; + } + token.prec = prec; + lex(); + + markers = [marker, lookahead]; + right = parseUnaryExpression(); + + stack = [left, token, right]; + + while ((prec = binaryPrecedence(lookahead, state.allowIn)) > 0) { + + // Reduce: make a binary expression from the three topmost entries. + while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) { + right = stack.pop(); + operator = stack.pop().value; + left = stack.pop(); + expr = delegate.createBinaryExpression(operator, left, right); + markers.pop(); + marker = markers[markers.length - 1]; + delegate.markEnd(expr, marker); + stack.push(expr); + } + + // Shift. + token = lex(); + token.prec = prec; + stack.push(token); + markers.push(lookahead); + expr = parseUnaryExpression(); + stack.push(expr); + } + + // Final reduce to clean-up the stack. + i = stack.length - 1; + expr = stack[i]; + markers.pop(); + while (i > 1) { + expr = delegate.createBinaryExpression(stack[i - 1].value, stack[i - 2], expr); + i -= 2; + marker = markers.pop(); + delegate.markEnd(expr, marker); + } + + return expr; + } + + + // 11.12 Conditional Operator + + function parseConditionalExpression() { + var expr, previousAllowIn, consequent, alternate, startToken; + + startToken = lookahead; + + expr = parseBinaryExpression(); + + if (match('?')) { + lex(); + previousAllowIn = state.allowIn; + state.allowIn = true; + consequent = parseAssignmentExpression(); + state.allowIn = previousAllowIn; + expect(':'); + alternate = parseAssignmentExpression(); + + expr = delegate.createConditionalExpression(expr, consequent, alternate); + delegate.markEnd(expr, startToken); + } + + return expr; + } + + // 11.13 Assignment Operators + + function parseAssignmentExpression() { + var token, left, right, node, startToken; + + token = lookahead; + startToken = lookahead; + + node = left = parseConditionalExpression(); + + if (matchAssign()) { + // LeftHandSideExpression + if (!isLeftHandSide(left)) { + throwErrorTolerant({}, Messages.InvalidLHSInAssignment); + } + + // 11.13.1 + if (strict && left.type === Syntax.Identifier && isRestrictedWord(left.name)) { + throwErrorTolerant(token, Messages.StrictLHSAssignment); + } + + token = lex(); + right = parseAssignmentExpression(); + node = delegate.markEnd(delegate.createAssignmentExpression(token.value, left, right), startToken); + } + + return node; + } + + // 11.14 Comma Operator + + function parseExpression() { + var expr, startToken = lookahead; + + expr = parseAssignmentExpression(); + + if (match(',')) { + expr = delegate.createSequenceExpression([ expr ]); + + while (index < length) { + if (!match(',')) { + break; + } + lex(); + expr.expressions.push(parseAssignmentExpression()); + } + + delegate.markEnd(expr, startToken); + } + + return expr; + } + + // 12.1 Block + + function parseStatementList() { + var list = [], + statement; + + while (index < length) { + if (match('}')) { + break; + } + statement = parseSourceElement(); + if (typeof statement === 'undefined') { + break; + } + list.push(statement); + } + + return list; + } + + function parseBlock() { + var block, startToken; + + startToken = lookahead; + expect('{'); + + block = parseStatementList(); + + expect('}'); + + return delegate.markEnd(delegate.createBlockStatement(block), startToken); + } + + // 12.2 Variable Statement + + function parseVariableIdentifier() { + var token, startToken; + + startToken = lookahead; + token = lex(); + + if (token.type !== Token.Identifier) { + throwUnexpected(token); + } + + return delegate.markEnd(delegate.createIdentifier(token.value), startToken); + } + + function parseVariableDeclaration(kind) { + var init = null, id, startToken; + + startToken = lookahead; + id = parseVariableIdentifier(); + + // 12.2.1 + if (strict && isRestrictedWord(id.name)) { + throwErrorTolerant({}, Messages.StrictVarName); + } + + if (kind === 'const') { + expect('='); + init = parseAssignmentExpression(); + } else if (match('=')) { + lex(); + init = parseAssignmentExpression(); + } + + return delegate.markEnd(delegate.createVariableDeclarator(id, init), startToken); + } + + function parseVariableDeclarationList(kind) { + var list = []; + + do { + list.push(parseVariableDeclaration(kind)); + if (!match(',')) { + break; + } + lex(); + } while (index < length); + + return list; + } + + function parseVariableStatement() { + var declarations; + + expectKeyword('var'); + + declarations = parseVariableDeclarationList(); + + consumeSemicolon(); + + return delegate.createVariableDeclaration(declarations, 'var'); + } + + // kind may be `const` or `let` + // Both are experimental and not in the specification yet. + // see http://wiki.ecmascript.org/doku.php?id=harmony:const + // and http://wiki.ecmascript.org/doku.php?id=harmony:let + function parseConstLetDeclaration(kind) { + var declarations, startToken; + + startToken = lookahead; + + expectKeyword(kind); + + declarations = parseVariableDeclarationList(kind); + + consumeSemicolon(); + + return delegate.markEnd(delegate.createVariableDeclaration(declarations, kind), startToken); + } + + // 12.3 Empty Statement + + function parseEmptyStatement() { + expect(';'); + return delegate.createEmptyStatement(); + } + + // 12.4 Expression Statement + + function parseExpressionStatement() { + var expr = parseExpression(); + consumeSemicolon(); + return delegate.createExpressionStatement(expr); + } + + // 12.5 If statement + + function parseIfStatement() { + var test, consequent, alternate; + + expectKeyword('if'); + + expect('('); + + test = parseExpression(); + + expect(')'); + + consequent = parseStatement(); + + if (matchKeyword('else')) { + lex(); + alternate = parseStatement(); + } else { + alternate = null; + } + + return delegate.createIfStatement(test, consequent, alternate); + } + + // 12.6 Iteration Statements + + function parseDoWhileStatement() { + var body, test, oldInIteration; + + expectKeyword('do'); + + oldInIteration = state.inIteration; + state.inIteration = true; + + body = parseStatement(); + + state.inIteration = oldInIteration; + + expectKeyword('while'); + + expect('('); + + test = parseExpression(); + + expect(')'); + + if (match(';')) { + lex(); + } + + return delegate.createDoWhileStatement(body, test); + } + + function parseWhileStatement() { + var test, body, oldInIteration; + + expectKeyword('while'); + + expect('('); + + test = parseExpression(); + + expect(')'); + + oldInIteration = state.inIteration; + state.inIteration = true; + + body = parseStatement(); + + state.inIteration = oldInIteration; + + return delegate.createWhileStatement(test, body); + } + + function parseForVariableDeclaration() { + var token, declarations, startToken; + + startToken = lookahead; + token = lex(); + declarations = parseVariableDeclarationList(); + + return delegate.markEnd(delegate.createVariableDeclaration(declarations, token.value), startToken); + } + + function parseForStatement() { + var init, test, update, left, right, body, oldInIteration; + + init = test = update = null; + + expectKeyword('for'); + + expect('('); + + if (match(';')) { + lex(); + } else { + if (matchKeyword('var') || matchKeyword('let')) { + state.allowIn = false; + init = parseForVariableDeclaration(); + state.allowIn = true; + + if (init.declarations.length === 1 && matchKeyword('in')) { + lex(); + left = init; + right = parseExpression(); + init = null; + } + } else { + state.allowIn = false; + init = parseExpression(); + state.allowIn = true; + + if (matchKeyword('in')) { + // LeftHandSideExpression + if (!isLeftHandSide(init)) { + throwErrorTolerant({}, Messages.InvalidLHSInForIn); + } + + lex(); + left = init; + right = parseExpression(); + init = null; + } + } + + if (typeof left === 'undefined') { + expect(';'); + } + } + + if (typeof left === 'undefined') { + + if (!match(';')) { + test = parseExpression(); + } + expect(';'); + + if (!match(')')) { + update = parseExpression(); + } + } + + expect(')'); + + oldInIteration = state.inIteration; + state.inIteration = true; + + body = parseStatement(); + + state.inIteration = oldInIteration; + + return (typeof left === 'undefined') ? + delegate.createForStatement(init, test, update, body) : + delegate.createForInStatement(left, right, body); + } + + // 12.7 The continue statement + + function parseContinueStatement() { + var label = null, key; + + expectKeyword('continue'); + + // Optimize the most common form: 'continue;'. + if (source.charCodeAt(index) === 0x3B) { + lex(); + + if (!state.inIteration) { + throwError({}, Messages.IllegalContinue); + } + + return delegate.createContinueStatement(null); + } + + if (peekLineTerminator()) { + if (!state.inIteration) { + throwError({}, Messages.IllegalContinue); + } + + return delegate.createContinueStatement(null); + } + + if (lookahead.type === Token.Identifier) { + label = parseVariableIdentifier(); + + key = '$' + label.name; + if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) { + throwError({}, Messages.UnknownLabel, label.name); + } + } + + consumeSemicolon(); + + if (label === null && !state.inIteration) { + throwError({}, Messages.IllegalContinue); + } + + return delegate.createContinueStatement(label); + } + + // 12.8 The break statement + + function parseBreakStatement() { + var label = null, key; + + expectKeyword('break'); + + // Catch the very common case first: immediately a semicolon (U+003B). + if (source.charCodeAt(index) === 0x3B) { + lex(); + + if (!(state.inIteration || state.inSwitch)) { + throwError({}, Messages.IllegalBreak); + } + + return delegate.createBreakStatement(null); + } + + if (peekLineTerminator()) { + if (!(state.inIteration || state.inSwitch)) { + throwError({}, Messages.IllegalBreak); + } + + return delegate.createBreakStatement(null); + } + + if (lookahead.type === Token.Identifier) { + label = parseVariableIdentifier(); + + key = '$' + label.name; + if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) { + throwError({}, Messages.UnknownLabel, label.name); + } + } + + consumeSemicolon(); + + if (label === null && !(state.inIteration || state.inSwitch)) { + throwError({}, Messages.IllegalBreak); + } + + return delegate.createBreakStatement(label); + } + + // 12.9 The return statement + + function parseReturnStatement() { + var argument = null; + + expectKeyword('return'); + + if (!state.inFunctionBody) { + throwErrorTolerant({}, Messages.IllegalReturn); + } + + // 'return' followed by a space and an identifier is very common. + if (source.charCodeAt(index) === 0x20) { + if (isIdentifierStart(source.charCodeAt(index + 1))) { + argument = parseExpression(); + consumeSemicolon(); + return delegate.createReturnStatement(argument); + } + } + + if (peekLineTerminator()) { + return delegate.createReturnStatement(null); + } + + if (!match(';')) { + if (!match('}') && lookahead.type !== Token.EOF) { + argument = parseExpression(); + } + } + + consumeSemicolon(); + + return delegate.createReturnStatement(argument); + } + + // 12.10 The with statement + + function parseWithStatement() { + var object, body; + + if (strict) { + // TODO(ikarienator): Should we update the test cases instead? + skipComment(); + throwErrorTolerant({}, Messages.StrictModeWith); + } + + expectKeyword('with'); + + expect('('); + + object = parseExpression(); + + expect(')'); + + body = parseStatement(); + + return delegate.createWithStatement(object, body); + } + + // 12.10 The swith statement + + function parseSwitchCase() { + var test, consequent = [], statement, startToken; + + startToken = lookahead; + if (matchKeyword('default')) { + lex(); + test = null; + } else { + expectKeyword('case'); + test = parseExpression(); + } + expect(':'); + + while (index < length) { + if (match('}') || matchKeyword('default') || matchKeyword('case')) { + break; + } + statement = parseStatement(); + consequent.push(statement); + } + + return delegate.markEnd(delegate.createSwitchCase(test, consequent), startToken); + } + + function parseSwitchStatement() { + var discriminant, cases, clause, oldInSwitch, defaultFound; + + expectKeyword('switch'); + + expect('('); + + discriminant = parseExpression(); + + expect(')'); + + expect('{'); + + cases = []; + + if (match('}')) { + lex(); + return delegate.createSwitchStatement(discriminant, cases); + } + + oldInSwitch = state.inSwitch; + state.inSwitch = true; + defaultFound = false; + + while (index < length) { + if (match('}')) { + break; + } + clause = parseSwitchCase(); + if (clause.test === null) { + if (defaultFound) { + throwError({}, Messages.MultipleDefaultsInSwitch); + } + defaultFound = true; + } + cases.push(clause); + } + + state.inSwitch = oldInSwitch; + + expect('}'); + + return delegate.createSwitchStatement(discriminant, cases); + } + + // 12.13 The throw statement + + function parseThrowStatement() { + var argument; + + expectKeyword('throw'); + + if (peekLineTerminator()) { + throwError({}, Messages.NewlineAfterThrow); + } + + argument = parseExpression(); + + consumeSemicolon(); + + return delegate.createThrowStatement(argument); + } + + // 12.14 The try statement + + function parseCatchClause() { + var param, body, startToken; + + startToken = lookahead; + expectKeyword('catch'); + + expect('('); + if (match(')')) { + throwUnexpected(lookahead); + } + + param = parseVariableIdentifier(); + // 12.14.1 + if (strict && isRestrictedWord(param.name)) { + throwErrorTolerant({}, Messages.StrictCatchVariable); + } + + expect(')'); + body = parseBlock(); + return delegate.markEnd(delegate.createCatchClause(param, body), startToken); + } + + function parseTryStatement() { + var block, handlers = [], finalizer = null; + + expectKeyword('try'); + + block = parseBlock(); + + if (matchKeyword('catch')) { + handlers.push(parseCatchClause()); + } + + if (matchKeyword('finally')) { + lex(); + finalizer = parseBlock(); + } + + if (handlers.length === 0 && !finalizer) { + throwError({}, Messages.NoCatchOrFinally); + } + + return delegate.createTryStatement(block, [], handlers, finalizer); + } + + // 12.15 The debugger statement + + function parseDebuggerStatement() { + expectKeyword('debugger'); + + consumeSemicolon(); + + return delegate.createDebuggerStatement(); + } + + // 12 Statements + + function parseStatement() { + var type = lookahead.type, + expr, + labeledBody, + key, + startToken; + + if (type === Token.EOF) { + throwUnexpected(lookahead); + } + + if (type === Token.Punctuator && lookahead.value === '{') { + return parseBlock(); + } + + startToken = lookahead; + + if (type === Token.Punctuator) { + switch (lookahead.value) { + case ';': + return delegate.markEnd(parseEmptyStatement(), startToken); + case '(': + return delegate.markEnd(parseExpressionStatement(), startToken); + default: + break; + } + } + + if (type === Token.Keyword) { + switch (lookahead.value) { + case 'break': + return delegate.markEnd(parseBreakStatement(), startToken); + case 'continue': + return delegate.markEnd(parseContinueStatement(), startToken); + case 'debugger': + return delegate.markEnd(parseDebuggerStatement(), startToken); + case 'do': + return delegate.markEnd(parseDoWhileStatement(), startToken); + case 'for': + return delegate.markEnd(parseForStatement(), startToken); + case 'function': + return delegate.markEnd(parseFunctionDeclaration(), startToken); + case 'if': + return delegate.markEnd(parseIfStatement(), startToken); + case 'return': + return delegate.markEnd(parseReturnStatement(), startToken); + case 'switch': + return delegate.markEnd(parseSwitchStatement(), startToken); + case 'throw': + return delegate.markEnd(parseThrowStatement(), startToken); + case 'try': + return delegate.markEnd(parseTryStatement(), startToken); + case 'var': + return delegate.markEnd(parseVariableStatement(), startToken); + case 'while': + return delegate.markEnd(parseWhileStatement(), startToken); + case 'with': + return delegate.markEnd(parseWithStatement(), startToken); + default: + break; + } + } + + expr = parseExpression(); + + // 12.12 Labelled Statements + if ((expr.type === Syntax.Identifier) && match(':')) { + lex(); + + key = '$' + expr.name; + if (Object.prototype.hasOwnProperty.call(state.labelSet, key)) { + throwError({}, Messages.Redeclaration, 'Label', expr.name); + } + + state.labelSet[key] = true; + labeledBody = parseStatement(); + delete state.labelSet[key]; + return delegate.markEnd(delegate.createLabeledStatement(expr, labeledBody), startToken); + } + + consumeSemicolon(); + + return delegate.markEnd(delegate.createExpressionStatement(expr), startToken); + } + + // 13 Function Definition + + function parseFunctionSourceElements() { + var sourceElement, sourceElements = [], token, directive, firstRestricted, + oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody, startToken; + + startToken = lookahead; + expect('{'); + + while (index < length) { + if (lookahead.type !== Token.StringLiteral) { + break; + } + token = lookahead; + + sourceElement = parseSourceElement(); + sourceElements.push(sourceElement); + if (sourceElement.expression.type !== Syntax.Literal) { + // this is not directive + break; + } + directive = source.slice(token.start + 1, token.end - 1); + if (directive === 'use strict') { + strict = true; + if (firstRestricted) { + throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral); + } + } else { + if (!firstRestricted && token.octal) { + firstRestricted = token; + } + } + } + + oldLabelSet = state.labelSet; + oldInIteration = state.inIteration; + oldInSwitch = state.inSwitch; + oldInFunctionBody = state.inFunctionBody; + + state.labelSet = {}; + state.inIteration = false; + state.inSwitch = false; + state.inFunctionBody = true; + + while (index < length) { + if (match('}')) { + break; + } + sourceElement = parseSourceElement(); + if (typeof sourceElement === 'undefined') { + break; + } + sourceElements.push(sourceElement); + } + + expect('}'); + + state.labelSet = oldLabelSet; + state.inIteration = oldInIteration; + state.inSwitch = oldInSwitch; + state.inFunctionBody = oldInFunctionBody; + + return delegate.markEnd(delegate.createBlockStatement(sourceElements), startToken); + } + + function parseParams(firstRestricted) { + var param, params = [], token, stricted, paramSet, key, message; + expect('('); + + if (!match(')')) { + paramSet = {}; + while (index < length) { + token = lookahead; + param = parseVariableIdentifier(); + key = '$' + token.value; + if (strict) { + if (isRestrictedWord(token.value)) { + stricted = token; + message = Messages.StrictParamName; + } + if (Object.prototype.hasOwnProperty.call(paramSet, key)) { + stricted = token; + message = Messages.StrictParamDupe; + } + } else if (!firstRestricted) { + if (isRestrictedWord(token.value)) { + firstRestricted = token; + message = Messages.StrictParamName; + } else if (isStrictModeReservedWord(token.value)) { + firstRestricted = token; + message = Messages.StrictReservedWord; + } else if (Object.prototype.hasOwnProperty.call(paramSet, key)) { + firstRestricted = token; + message = Messages.StrictParamDupe; + } + } + params.push(param); + paramSet[key] = true; + if (match(')')) { + break; + } + expect(','); + } + } + + expect(')'); + + return { + params: params, + stricted: stricted, + firstRestricted: firstRestricted, + message: message + }; + } + + function parseFunctionDeclaration() { + var id, params = [], body, token, stricted, tmp, firstRestricted, message, previousStrict, startToken; + + startToken = lookahead; + + expectKeyword('function'); + token = lookahead; + id = parseVariableIdentifier(); + if (strict) { + if (isRestrictedWord(token.value)) { + throwErrorTolerant(token, Messages.StrictFunctionName); + } + } else { + if (isRestrictedWord(token.value)) { + firstRestricted = token; + message = Messages.StrictFunctionName; + } else if (isStrictModeReservedWord(token.value)) { + firstRestricted = token; + message = Messages.StrictReservedWord; + } + } + + tmp = parseParams(firstRestricted); + params = tmp.params; + stricted = tmp.stricted; + firstRestricted = tmp.firstRestricted; + if (tmp.message) { + message = tmp.message; + } + + previousStrict = strict; + body = parseFunctionSourceElements(); + if (strict && firstRestricted) { + throwError(firstRestricted, message); + } + if (strict && stricted) { + throwErrorTolerant(stricted, message); + } + strict = previousStrict; + + return delegate.markEnd(delegate.createFunctionDeclaration(id, params, [], body), startToken); + } + + function parseFunctionExpression() { + var token, id = null, stricted, firstRestricted, message, tmp, params = [], body, previousStrict, startToken; + + startToken = lookahead; + expectKeyword('function'); + + if (!match('(')) { + token = lookahead; + id = parseVariableIdentifier(); + if (strict) { + if (isRestrictedWord(token.value)) { + throwErrorTolerant(token, Messages.StrictFunctionName); + } + } else { + if (isRestrictedWord(token.value)) { + firstRestricted = token; + message = Messages.StrictFunctionName; + } else if (isStrictModeReservedWord(token.value)) { + firstRestricted = token; + message = Messages.StrictReservedWord; + } + } + } + + tmp = parseParams(firstRestricted); + params = tmp.params; + stricted = tmp.stricted; + firstRestricted = tmp.firstRestricted; + if (tmp.message) { + message = tmp.message; + } + + previousStrict = strict; + body = parseFunctionSourceElements(); + if (strict && firstRestricted) { + throwError(firstRestricted, message); + } + if (strict && stricted) { + throwErrorTolerant(stricted, message); + } + strict = previousStrict; + + return delegate.markEnd(delegate.createFunctionExpression(id, params, [], body), startToken); + } + + // 14 Program + + function parseSourceElement() { + if (lookahead.type === Token.Keyword) { + switch (lookahead.value) { + case 'const': + case 'let': + return parseConstLetDeclaration(lookahead.value); + case 'function': + return parseFunctionDeclaration(); + default: + return parseStatement(); + } + } + + if (lookahead.type !== Token.EOF) { + return parseStatement(); + } + } + + function parseSourceElements() { + var sourceElement, sourceElements = [], token, directive, firstRestricted; + + while (index < length) { + token = lookahead; + if (token.type !== Token.StringLiteral) { + break; + } + + sourceElement = parseSourceElement(); + sourceElements.push(sourceElement); + if (sourceElement.expression.type !== Syntax.Literal) { + // this is not directive + break; + } + directive = source.slice(token.start + 1, token.end - 1); + if (directive === 'use strict') { + strict = true; + if (firstRestricted) { + throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral); + } + } else { + if (!firstRestricted && token.octal) { + firstRestricted = token; + } + } + } + + while (index < length) { + sourceElement = parseSourceElement(); + /* istanbul ignore if */ + if (typeof sourceElement === 'undefined') { + break; + } + sourceElements.push(sourceElement); + } + return sourceElements; + } + + function parseProgram() { + var body, startToken; + + skipComment(); + peek(); + startToken = lookahead; + strict = false; + + body = parseSourceElements(); + return delegate.markEnd(delegate.createProgram(body), startToken); + } + + function filterTokenLocation() { + var i, entry, token, tokens = []; + + for (i = 0; i < extra.tokens.length; ++i) { + entry = extra.tokens[i]; + token = { + type: entry.type, + value: entry.value + }; + if (extra.range) { + token.range = entry.range; + } + if (extra.loc) { + token.loc = entry.loc; + } + tokens.push(token); + } + + extra.tokens = tokens; + } + + function tokenize(code, options) { + var toString, + token, + tokens; + + toString = String; + if (typeof code !== 'string' && !(code instanceof String)) { + code = toString(code); + } + + delegate = SyntaxTreeDelegate; + source = code; + index = 0; + lineNumber = (source.length > 0) ? 1 : 0; + lineStart = 0; + length = source.length; + lookahead = null; + state = { + allowIn: true, + labelSet: {}, + inFunctionBody: false, + inIteration: false, + inSwitch: false, + lastCommentStart: -1 + }; + + extra = {}; + + // Options matching. + options = options || {}; + + // Of course we collect tokens here. + options.tokens = true; + extra.tokens = []; + extra.tokenize = true; + // The following two fields are necessary to compute the Regex tokens. + extra.openParenToken = -1; + extra.openCurlyToken = -1; + + extra.range = (typeof options.range === 'boolean') && options.range; + extra.loc = (typeof options.loc === 'boolean') && options.loc; + + if (typeof options.comment === 'boolean' && options.comment) { + extra.comments = []; + } + if (typeof options.tolerant === 'boolean' && options.tolerant) { + extra.errors = []; + } + + try { + peek(); + if (lookahead.type === Token.EOF) { + return extra.tokens; + } + + token = lex(); + while (lookahead.type !== Token.EOF) { + try { + token = lex(); + } catch (lexError) { + token = lookahead; + if (extra.errors) { + extra.errors.push(lexError); + // We have to break on the first error + // to avoid infinite loops. + break; + } else { + throw lexError; + } + } + } + + filterTokenLocation(); + tokens = extra.tokens; + if (typeof extra.comments !== 'undefined') { + tokens.comments = extra.comments; + } + if (typeof extra.errors !== 'undefined') { + tokens.errors = extra.errors; + } + } catch (e) { + throw e; + } finally { + extra = {}; + } + return tokens; + } + + function parse(code, options) { + var program, toString; + + toString = String; + if (typeof code !== 'string' && !(code instanceof String)) { + code = toString(code); + } + + delegate = SyntaxTreeDelegate; + source = code; + index = 0; + lineNumber = (source.length > 0) ? 1 : 0; + lineStart = 0; + length = source.length; + lookahead = null; + state = { + allowIn: true, + labelSet: {}, + inFunctionBody: false, + inIteration: false, + inSwitch: false, + lastCommentStart: -1 + }; + + extra = {}; + if (typeof options !== 'undefined') { + extra.range = (typeof options.range === 'boolean') && options.range; + extra.loc = (typeof options.loc === 'boolean') && options.loc; + extra.attachComment = (typeof options.attachComment === 'boolean') && options.attachComment; + + if (extra.loc && options.source !== null && options.source !== undefined) { + extra.source = toString(options.source); + } + + if (typeof options.tokens === 'boolean' && options.tokens) { + extra.tokens = []; + } + if (typeof options.comment === 'boolean' && options.comment) { + extra.comments = []; + } + if (typeof options.tolerant === 'boolean' && options.tolerant) { + extra.errors = []; + } + if (extra.attachComment) { + extra.range = true; + extra.comments = []; + extra.bottomRightStack = []; + extra.trailingComments = []; + extra.leadingComments = []; + } + } + + try { + program = parseProgram(); + if (typeof extra.comments !== 'undefined') { + program.comments = extra.comments; + } + if (typeof extra.tokens !== 'undefined') { + filterTokenLocation(); + program.tokens = extra.tokens; + } + if (typeof extra.errors !== 'undefined') { + program.errors = extra.errors; + } + } catch (e) { + throw e; + } finally { + extra = {}; + } + + return program; + } + + // Sync with *.json manifests. + exports.version = '1.2.2'; + + exports.tokenize = tokenize; + + exports.parse = parse; + + // Deep copy. + /* istanbul ignore next */ + exports.Syntax = (function () { + var name, types = {}; + + if (typeof Object.create === 'function') { + types = Object.create(null); + } + + for (name in Syntax) { + if (Syntax.hasOwnProperty(name)) { + types[name] = Syntax[name]; + } + } + + if (typeof Object.freeze === 'function') { + Object.freeze(types); + } + + return types; + }()); + +})); +/* vim: set sw=4 ts=4 et tw=80 : */ + +},{}],7:[function(require,module,exports){ +/* + Copyright (C) 2012-2013 Yusuke Suzuki + Copyright (C) 2012 Ariya Hidayat + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/*jslint vars:false, bitwise:true*/ +/*jshint indent:4*/ +/*global exports:true, define:true*/ +(function (root, factory) { + 'use strict'; + + // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, + // and plain browser loading, + if (typeof define === 'function' && define.amd) { + define(['exports'], factory); + } else if (typeof exports !== 'undefined') { + factory(exports); + } else { + factory((root.estraverse = {})); + } +}(this, function (exports) { + 'use strict'; + + var Syntax, + isArray, + VisitorOption, + VisitorKeys, + BREAK, + SKIP; + + Syntax = { + AssignmentExpression: 'AssignmentExpression', + ArrayExpression: 'ArrayExpression', + ArrayPattern: 'ArrayPattern', + ArrowFunctionExpression: 'ArrowFunctionExpression', + BlockStatement: 'BlockStatement', + BinaryExpression: 'BinaryExpression', + BreakStatement: 'BreakStatement', + CallExpression: 'CallExpression', + CatchClause: 'CatchClause', + ClassBody: 'ClassBody', + ClassDeclaration: 'ClassDeclaration', + ClassExpression: 'ClassExpression', + ConditionalExpression: 'ConditionalExpression', + ContinueStatement: 'ContinueStatement', + DebuggerStatement: 'DebuggerStatement', + DirectiveStatement: 'DirectiveStatement', + DoWhileStatement: 'DoWhileStatement', + EmptyStatement: 'EmptyStatement', + ExpressionStatement: 'ExpressionStatement', + ForStatement: 'ForStatement', + ForInStatement: 'ForInStatement', + FunctionDeclaration: 'FunctionDeclaration', + FunctionExpression: 'FunctionExpression', + Identifier: 'Identifier', + IfStatement: 'IfStatement', + Literal: 'Literal', + LabeledStatement: 'LabeledStatement', + LogicalExpression: 'LogicalExpression', + MemberExpression: 'MemberExpression', + MethodDefinition: 'MethodDefinition', + NewExpression: 'NewExpression', + ObjectExpression: 'ObjectExpression', + ObjectPattern: 'ObjectPattern', + Program: 'Program', + Property: 'Property', + ReturnStatement: 'ReturnStatement', + SequenceExpression: 'SequenceExpression', + SwitchStatement: 'SwitchStatement', + SwitchCase: 'SwitchCase', + ThisExpression: 'ThisExpression', + ThrowStatement: 'ThrowStatement', + TryStatement: 'TryStatement', + UnaryExpression: 'UnaryExpression', + UpdateExpression: 'UpdateExpression', + VariableDeclaration: 'VariableDeclaration', + VariableDeclarator: 'VariableDeclarator', + WhileStatement: 'WhileStatement', + WithStatement: 'WithStatement', + YieldExpression: 'YieldExpression' + }; + + function ignoreJSHintError() { } + + isArray = Array.isArray; + if (!isArray) { + isArray = function isArray(array) { + return Object.prototype.toString.call(array) === '[object Array]'; + }; + } + + function deepCopy(obj) { + var ret = {}, key, val; + for (key in obj) { + if (obj.hasOwnProperty(key)) { + val = obj[key]; + if (typeof val === 'object' && val !== null) { + ret[key] = deepCopy(val); + } else { + ret[key] = val; + } + } + } + return ret; + } + + function shallowCopy(obj) { + var ret = {}, key; + for (key in obj) { + if (obj.hasOwnProperty(key)) { + ret[key] = obj[key]; + } + } + return ret; + } + ignoreJSHintError(shallowCopy); + + // based on LLVM libc++ upper_bound / lower_bound + // MIT License + + function upperBound(array, func) { + var diff, len, i, current; + + len = array.length; + i = 0; + + while (len) { + diff = len >>> 1; + current = i + diff; + if (func(array[current])) { + len = diff; + } else { + i = current + 1; + len -= diff + 1; + } + } + return i; + } + + function lowerBound(array, func) { + var diff, len, i, current; + + len = array.length; + i = 0; + + while (len) { + diff = len >>> 1; + current = i + diff; + if (func(array[current])) { + i = current + 1; + len -= diff + 1; + } else { + len = diff; + } + } + return i; + } + ignoreJSHintError(lowerBound); + + VisitorKeys = { + AssignmentExpression: ['left', 'right'], + ArrayExpression: ['elements'], + ArrayPattern: ['elements'], + ArrowFunctionExpression: ['params', 'defaults', 'rest', 'body'], + BlockStatement: ['body'], + BinaryExpression: ['left', 'right'], + BreakStatement: ['label'], + CallExpression: ['callee', 'arguments'], + CatchClause: ['param', 'body'], + ClassBody: ['body'], + ClassDeclaration: ['id', 'body', 'superClass'], + ClassExpression: ['id', 'body', 'superClass'], + ConditionalExpression: ['test', 'consequent', 'alternate'], + ContinueStatement: ['label'], + DebuggerStatement: [], + DirectiveStatement: [], + DoWhileStatement: ['body', 'test'], + EmptyStatement: [], + ExpressionStatement: ['expression'], + ForStatement: ['init', 'test', 'update', 'body'], + ForInStatement: ['left', 'right', 'body'], + ForOfStatement: ['left', 'right', 'body'], + FunctionDeclaration: ['id', 'params', 'defaults', 'rest', 'body'], + FunctionExpression: ['id', 'params', 'defaults', 'rest', 'body'], + Identifier: [], + IfStatement: ['test', 'consequent', 'alternate'], + Literal: [], + LabeledStatement: ['label', 'body'], + LogicalExpression: ['left', 'right'], + MemberExpression: ['object', 'property'], + MethodDefinition: ['key', 'value'], + NewExpression: ['callee', 'arguments'], + ObjectExpression: ['properties'], + ObjectPattern: ['properties'], + Program: ['body'], + Property: ['key', 'value'], + ReturnStatement: ['argument'], + SequenceExpression: ['expressions'], + SwitchStatement: ['discriminant', 'cases'], + SwitchCase: ['test', 'consequent'], + ThisExpression: [], + ThrowStatement: ['argument'], + TryStatement: ['block', 'handlers', 'handler', 'guardedHandlers', 'finalizer'], + UnaryExpression: ['argument'], + UpdateExpression: ['argument'], + VariableDeclaration: ['declarations'], + VariableDeclarator: ['id', 'init'], + WhileStatement: ['test', 'body'], + WithStatement: ['object', 'body'], + YieldExpression: ['argument'] + }; + + // unique id + BREAK = {}; + SKIP = {}; + + VisitorOption = { + Break: BREAK, + Skip: SKIP + }; + + function Reference(parent, key) { + this.parent = parent; + this.key = key; + } + + Reference.prototype.replace = function replace(node) { + this.parent[this.key] = node; + }; + + function Element(node, path, wrap, ref) { + this.node = node; + this.path = path; + this.wrap = wrap; + this.ref = ref; + } + + function Controller() { } + + // API: + // return property path array from root to current node + Controller.prototype.path = function path() { + var i, iz, j, jz, result, element; + + function addToPath(result, path) { + if (isArray(path)) { + for (j = 0, jz = path.length; j < jz; ++j) { + result.push(path[j]); + } + } else { + result.push(path); + } + } + + // root node + if (!this.__current.path) { + return null; + } + + // first node is sentinel, second node is root element + result = []; + for (i = 2, iz = this.__leavelist.length; i < iz; ++i) { + element = this.__leavelist[i]; + addToPath(result, element.path); + } + addToPath(result, this.__current.path); + return result; + }; + + // API: + // return array of parent elements + Controller.prototype.parents = function parents() { + var i, iz, result; + + // first node is sentinel + result = []; + for (i = 1, iz = this.__leavelist.length; i < iz; ++i) { + result.push(this.__leavelist[i].node); + } + + return result; + }; + + // API: + // return current node + Controller.prototype.current = function current() { + return this.__current.node; + }; + + Controller.prototype.__execute = function __execute(callback, element) { + var previous, result; + + result = undefined; + + previous = this.__current; + this.__current = element; + this.__state = null; + if (callback) { + result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node); + } + this.__current = previous; + + return result; + }; + + // API: + // notify control skip / break + Controller.prototype.notify = function notify(flag) { + this.__state = flag; + }; + + // API: + // skip child nodes of current node + Controller.prototype.skip = function () { + this.notify(SKIP); + }; + + // API: + // break traversals + Controller.prototype['break'] = function () { + this.notify(BREAK); + }; + + Controller.prototype.__initialize = function(root, visitor) { + this.visitor = visitor; + this.root = root; + this.__worklist = []; + this.__leavelist = []; + this.__current = null; + this.__state = null; + }; + + Controller.prototype.traverse = function traverse(root, visitor) { + var worklist, + leavelist, + element, + node, + nodeType, + ret, + key, + current, + current2, + candidates, + candidate, + sentinel; + + this.__initialize(root, visitor); + + sentinel = {}; + + // reference + worklist = this.__worklist; + leavelist = this.__leavelist; + + // initialize + worklist.push(new Element(root, null, null, null)); + leavelist.push(new Element(null, null, null, null)); + + while (worklist.length) { + element = worklist.pop(); + + if (element === sentinel) { + element = leavelist.pop(); + + ret = this.__execute(visitor.leave, element); + + if (this.__state === BREAK || ret === BREAK) { + return; + } + continue; + } + + if (element.node) { + + ret = this.__execute(visitor.enter, element); + + if (this.__state === BREAK || ret === BREAK) { + return; + } + + worklist.push(sentinel); + leavelist.push(element); + + if (this.__state === SKIP || ret === SKIP) { + continue; + } + + node = element.node; + nodeType = element.wrap || node.type; + candidates = VisitorKeys[nodeType]; + + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } + + if (!isArray(candidate)) { + worklist.push(new Element(candidate, key, null, null)); + continue; + } + + current2 = candidate.length; + while ((current2 -= 1) >= 0) { + if (!candidate[current2]) { + continue; + } + if ((nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === candidates[current]) { + element = new Element(candidate[current2], [key, current2], 'Property', null); + } else { + element = new Element(candidate[current2], [key, current2], null, null); + } + worklist.push(element); + } + } + } + } + }; + + Controller.prototype.replace = function replace(root, visitor) { + var worklist, + leavelist, + node, + nodeType, + target, + element, + current, + current2, + candidates, + candidate, + sentinel, + outer, + key; + + this.__initialize(root, visitor); + + sentinel = {}; + + // reference + worklist = this.__worklist; + leavelist = this.__leavelist; + + // initialize + outer = { + root: root + }; + element = new Element(root, null, null, new Reference(outer, 'root')); + worklist.push(element); + leavelist.push(element); + + while (worklist.length) { + element = worklist.pop(); + + if (element === sentinel) { + element = leavelist.pop(); + + target = this.__execute(visitor.leave, element); + + // node may be replaced with null, + // so distinguish between undefined and null in this place + if (target !== undefined && target !== BREAK && target !== SKIP) { + // replace + element.ref.replace(target); + } + + if (this.__state === BREAK || target === BREAK) { + return outer.root; + } + continue; + } + + target = this.__execute(visitor.enter, element); + + // node may be replaced with null, + // so distinguish between undefined and null in this place + if (target !== undefined && target !== BREAK && target !== SKIP) { + // replace + element.ref.replace(target); + element.node = target; + } + + if (this.__state === BREAK || target === BREAK) { + return outer.root; + } + + // node may be null + node = element.node; + if (!node) { + continue; + } + + worklist.push(sentinel); + leavelist.push(element); + + if (this.__state === SKIP || target === SKIP) { + continue; + } + + nodeType = element.wrap || node.type; + candidates = VisitorKeys[nodeType]; + + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } + + if (!isArray(candidate)) { + worklist.push(new Element(candidate, key, null, new Reference(node, key))); + continue; + } + + current2 = candidate.length; + while ((current2 -= 1) >= 0) { + if (!candidate[current2]) { + continue; + } + if (nodeType === Syntax.ObjectExpression && 'properties' === candidates[current]) { + element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2)); + } else { + element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2)); + } + worklist.push(element); + } + } + } + + return outer.root; + }; + + function traverse(root, visitor) { + var controller = new Controller(); + return controller.traverse(root, visitor); + } + + function replace(root, visitor) { + var controller = new Controller(); + return controller.replace(root, visitor); + } + + function extendCommentRange(comment, tokens) { + var target; + + target = upperBound(tokens, function search(token) { + return token.range[0] > comment.range[0]; + }); + + comment.extendedRange = [comment.range[0], comment.range[1]]; + + if (target !== tokens.length) { + comment.extendedRange[1] = tokens[target].range[0]; + } + + target -= 1; + if (target >= 0) { + comment.extendedRange[0] = tokens[target].range[1]; + } + + return comment; + } + + function attachComments(tree, providedComments, tokens) { + // At first, we should calculate extended comment ranges. + var comments = [], comment, len, i, cursor; + + if (!tree.range) { + throw new Error('attachComments needs range information'); + } + + // tokens array is empty, we attach comments to tree as 'leadingComments' + if (!tokens.length) { + if (providedComments.length) { + for (i = 0, len = providedComments.length; i < len; i += 1) { + comment = deepCopy(providedComments[i]); + comment.extendedRange = [0, tree.range[0]]; + comments.push(comment); + } + tree.leadingComments = comments; + } + return tree; + } + + for (i = 0, len = providedComments.length; i < len; i += 1) { + comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens)); + } + + // This is based on John Freeman's implementation. + cursor = 0; + traverse(tree, { + enter: function (node) { + var comment; + + while (cursor < comments.length) { + comment = comments[cursor]; + if (comment.extendedRange[1] > node.range[0]) { + break; + } + + if (comment.extendedRange[1] === node.range[0]) { + if (!node.leadingComments) { + node.leadingComments = []; + } + node.leadingComments.push(comment); + comments.splice(cursor, 1); + } else { + cursor += 1; + } + } + + // already out of owned node + if (cursor === comments.length) { + return VisitorOption.Break; + } + + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); + + cursor = 0; + traverse(tree, { + leave: function (node) { + var comment; + + while (cursor < comments.length) { + comment = comments[cursor]; + if (node.range[1] < comment.extendedRange[0]) { + break; + } + + if (node.range[1] === comment.extendedRange[0]) { + if (!node.trailingComments) { + node.trailingComments = []; + } + node.trailingComments.push(comment); + comments.splice(cursor, 1); + } else { + cursor += 1; + } + } + + // already out of owned node + if (cursor === comments.length) { + return VisitorOption.Break; + } + + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); + + return tree; + } + + exports.version = '1.5.1-dev'; + exports.Syntax = Syntax; + exports.traverse = traverse; + exports.replace = replace; + exports.attachComments = attachComments; + exports.VisitorKeys = VisitorKeys; + exports.VisitorOption = VisitorOption; + exports.Controller = Controller; +})); +/* vim: set sw=4 ts=4 et tw=80 : */ + +},{}],8:[function(require,module,exports){ +'use strict'; + +function ToObject(val) { + if (val == null) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } + + return Object(val); +} + +module.exports = Object.assign || function (target, source) { + var pendingException; + var from; + var keys; + var to = ToObject(target); + + for (var s = 1; s < arguments.length; s++) { + from = arguments[s]; + keys = Object.keys(Object(from)); + + for (var i = 0; i < keys.length; i++) { + try { + to[keys[i]] = from[keys[i]]; + } catch (err) { + if (pendingException === undefined) { + pendingException = err; + } + } + } + } + + if (pendingException) { + throw pendingException; + } + + return to; +}; + +},{}],9:[function(require,module,exports){ +/** + * @fileoverview Main ESLint object. + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +var esprima = require("esprima"), + estraverse = require("estraverse"), + escope = require("escope"), + environments = require("../conf/environments.json"), + assign = require("object-assign"), + rules = require("./rules"), + util = require("./util"), + RuleContext = require("./rule-context"), + EventEmitter = require("events").EventEmitter; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +function escapeRegExp(rx) { + return rx.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); +} + +/** + * Parses a list of "name:boolean_value" or/and "name" options divided by comma or + * whitespace. + * @param {string} string The string to parse. + * @returns {Object} Result map object of names and boolean values + */ +function parseBooleanConfig(string) { + var items = {}; + // Collapse whitespace around : to make parsing easier + string = string.replace(/\s*:\s*/g, ":"); + // Collapse whitespace around , + string = string.replace(/\s*,\s*/g, ","); + string.split(/\s|,+/).forEach(function(name) { + if (!name) { + return; + } + var pos = name.indexOf(":"), + value; + if (pos !== -1) { + value = name.substring(pos + 1, name.length); + name = name.substring(0, pos); + } + + items[name] = (value === "true"); + + }); + return items; +} + +/** + * Parses a JSON-like config. + * @param {string} string The string to parse. + * @returns {Object} Result map object + */ +function parseJsonConfig(string) { + var items = {}; + string = string.replace(/([a-z0-9\-\/]+):/g, "\"$1\":").replace(/(\]|[0-9])\s+(?=")/, "$1,"); + try { + items = JSON.parse("{" + string + "}"); + } catch(e) { } + + return items; +} + +/** + * Parses a config of values separated by comma. + * @param {string} string The string to parse. + * @returns {Object} Result map of values and true values + */ +function parseListConfig(string) { + var items = {}; + // Collapse whitespace around , + string = string.replace(/\s*,\s*/g, ","); + string.split(/,+/).forEach(function(name) { + name = name.trim(); + if (!name) { + return; + } + items[name] = true; + }); + return items; +} + +/** + * @param {Scope} scope The scope object to check. + * @param {string} name The name of the variable to look up. + * @returns {Variable} The variable object if found or null if not. + */ +function getVariable(scope, name) { + var variable = null; + scope.variables.some(function(v) { + if (v.name === name) { + variable = v; + return true; + } else { + return false; + } + + }); + return variable; +} + +/** + * Ensures that variables representing built-in properties of the Global Object, + * and any globals declared by special block comments, are present in the global + * scope. + * @param {ASTNode} program The top node of the AST. + * @param {Scope} globalScope The global scope. + * @param {Object} config The existing configuration data. + * @returns {void} + */ +function addDeclaredGlobals(program, globalScope, config) { + var declaredGlobals = {}, + explicitGlobals = {}, + builtin = environments.builtin; + + assign(declaredGlobals, builtin); + + Object.keys(config.env).forEach(function (name) { + if (config.env[name]) { + var environmentGlobals = environments[name] && environments[name].globals; + if (environmentGlobals) { + assign(declaredGlobals, environmentGlobals); + } + } + }); + + assign(declaredGlobals, config.globals); + assign(explicitGlobals, config.astGlobals); + + Object.keys(declaredGlobals).forEach(function(name) { + var variable = getVariable(globalScope, name); + if (!variable) { + variable = new escope.Variable(name, globalScope); + variable.eslintExplicitGlobal = false; + globalScope.variables.push(variable); + } + variable.writeable = declaredGlobals[name]; + }); + + Object.keys(explicitGlobals).forEach(function(name) { + var variable = getVariable(globalScope, name); + if (!variable) { + variable = new escope.Variable(name, globalScope); + variable.eslintExplicitGlobal = true; + globalScope.variables.push(variable); + } + variable.writeable = explicitGlobals[name]; + }); +} + +/** + * Add data to reporting configuration to disable reporting for list of rules + * starting from start location + * @param {Object[]} reportingConfig Current reporting configuration + * @param {Object} start Position to start + * @param {string[]} rules List of rules + * @returns {void} + */ +function disableReporting(reportingConfig, start, rules) { + + if (rules.length) { + rules.forEach(function(rule) { + reportingConfig.push({ + start: start, + end: null, + rule: rule + }); + }); + } else { + reportingConfig.push({ + start: start, + end: null, + rule: null + }); + } +} + +/** + * Add data to reporting configuration to enable reporting for list of rules + * starting from start location + * @param {Object[]} reportingConfig Current reporting configuration + * @param {Object} start Position to start + * @param {string[]} rules List of rules + * @returns {void} + */ +function enableReporting(reportingConfig, start, rules) { + var i; + + if (rules.length) { + rules.forEach(function(rule) { + for (i = reportingConfig.length - 1; i >= 0; i--) { + if (!reportingConfig[i].end && reportingConfig[i].rule === rule ) { + reportingConfig[i].end = start; + break; + } + } + }); + } else { + // find all previous disabled locations if they was started as list of rules + var prevStart; + for (i = reportingConfig.length - 1; i >= 0; i--) { + if (prevStart && prevStart !== reportingConfig[i].start) { + break; + } + + if (!reportingConfig[i].end) { + reportingConfig[i].end = start; + prevStart = reportingConfig[i].start; + } + } + } +} + + +/** + * Parses comments in file to extract file-specific config of rules, globals + * and environments and merges them with global config; also code blocks + * where reporting is disabled or enabled and merges them with reporting config. + * @param {ASTNode} ast The top node of the AST. + * @param {Object} config The existing configuration data. + * @param {Object[]} reportingConfig The existing reporting configuration data. + * @returns {void} + */ +function modifyConfigsFromComments(ast, config, reportingConfig) { + + var commentConfig = { + astGlobals: {}, + rules: {}, + env: {} + }; + var commentRules = {}; + + ast.comments.forEach(function(comment) { + if (comment.type === "Block") { + + var value = comment.value.trim(); + var match = /^(eslint-\w+|eslint|globals?)(\s|$)/.exec(value); + + if (match) { + value = value.substring(match.index + match[1].length); + + switch (match[1]) { + case "globals": + case "global": + util.mixin(commentConfig.astGlobals, parseBooleanConfig(value)); + break; + + case "eslint-env": + util.mixin(commentConfig.env, parseListConfig(value)); + break; + + case "eslint-disable": + disableReporting(reportingConfig, comment.loc.start, Object.keys(parseListConfig(value))); + break; + + case "eslint-enable": + enableReporting(reportingConfig, comment.loc.start, Object.keys(parseListConfig(value))); + break; + + case "eslint": + var items = parseJsonConfig(value); + Object.keys(items).forEach(function(name) { + var ruleValue = items[name]; + if (typeof ruleValue === "number" || (Array.isArray(ruleValue) && typeof ruleValue[0] === "number")) { + commentRules[name] = ruleValue; + } + }); + break; + + // no default + } + } + } + }); + + // apply environment rules before user rules + Object.keys(commentConfig.env).forEach(function (name) { + var environmentRules = environments[name] && environments[name].rules; + if (commentConfig.env[name] && environmentRules) { + util.mixin(commentConfig.rules, environmentRules); + } + }); + util.mixin(commentConfig.rules, commentRules); + + util.mergeConfigs(config, commentConfig); +} + +/** + * Check if message of rule with ruleId should be ignored in location + * @param {Object[]} reportingConfig Collection of ignore records + * @param {string} ruleId Id of rule + * @param {Object} location Location of message + * @returns {boolean} True if message should be ignored, false otherwise + */ +function isDisabledByReportingConfig(reportingConfig, ruleId, location) { + + for (var i = 0, c = reportingConfig.length; i < c; i++) { + + var ignore = reportingConfig[i]; + if ((!ignore.rule || ignore.rule === ruleId) && + (location.line > ignore.start.line || (location.line === ignore.start.line && location.column >= ignore.start.column)) && + (!ignore.end || (location.line < ignore.end.line || (location.line === ignore.end.line && location.column <= ignore.end.column)))) { + return true; + } + } + + return false; +} + +/** + * Process initial config to make it safe to extend by file comment config + * @param {Object} config Initial config + * @returns {Object} Processed config + */ +function prepareConfig(config) { + + config.globals = config.globals || config.global || {}; + delete config.global; + + var copiedRules = {}; + if (typeof config.rules === "object") { + Object.keys(config.rules).forEach(function(k) { + var rule = config.rules[k]; + if (Array.isArray(rule)) { + copiedRules[k] = rule.slice(); + } else { + copiedRules[k] = rule; + } + }); + } + + return { + rules: copiedRules, + globals: util.mergeConfigs({}, config.globals), + env: util.mergeConfigs({}, config.env || {}), + settings: util.mergeConfigs({}, config.settings || {}) + }; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Object that is responsible for verifying JavaScript text + * @name eslint + */ +module.exports = (function() { + + var api = Object.create(new EventEmitter()), + messages = [], + currentText = null, + currentTextLines = [], + currentConfig = null, + currentTokens = null, + currentScopes = null, + scopeMap = null, + currentFilename = null, + controller = null, + reportingConfig = [], + commentLocsEnter = [], + commentLocsExit = []; + + /** + * Parses text into an AST. Moved out here because the try-catch prevents + * optimization of functions, so it's best to keep the try-catch as isolated + * as possible + * @param {string} text The text to parse. + * @returns {ASTNode} The AST if successful or null if not. + * @private + */ + function parse(text) { + /* + * Check for parsing errors first. If there's a parsing error, nothing + * else can happen. However, a parsing error does not throw an error + * from this method - it's just considered a fatal error message, a + * problem that ESLint identified just like any other. + */ + try { + return esprima.parse(text, { + loc: true, + range: true, + raw: true, + tokens: true, + comment: true, + attachComment: true + }); + } catch (ex) { + + messages.push({ + fatal: true, + severity: 2, + + // messages come as "Line X: Unexpected token foo", so strip off leading part + message: ex.message.substring(ex.message.indexOf(":") + 1).trim(), + + line: ex.lineNumber, + column: ex.column + }); + + return null; + } + } + + /** + * Check collection of comments to prevent double event for comment as + * leading and trailing, then emit event if passing + * @param {ASTNode[]} comments Collection of comment nodes + * @param {Object[]} locs List of locations of previous comment nodes + * @param {string} eventName Event name postfix + * @returns {void} + */ + function emitComments(comments, locs, eventName) { + + if (comments.length) { + comments.forEach(function(node) { + if (locs.indexOf(node.loc) >= 0) { + locs.splice(locs.indexOf(node.loc), 1); + } else { + locs.push(node.loc); + api.emit(node.type + eventName, node); + } + }); + } + } + + /** + * Shortcut to check and emit enter of comment nodes + * @param {ASTNode[]} comments Collection of comment nodes + * @returns {void} + */ + function emitCommentsEnter(comments) { + emitComments(comments, commentLocsEnter, "Comment"); + } + + /** + * Shortcut to check and emit exit of comment nodes + * @param {ASTNode[]} comments Collection of comment nodes + * @returns {void} + */ + function emitCommentsExit(comments) { + emitComments(comments, commentLocsExit, "Comment:exit"); + } + + /** + * Get the severity level of a rule (0 - none, 1 - warning, 2 - error) + * Returns 0 if the rule config is not valid (an Array or a number) + * @param {Array|number} ruleConfig rule configuration + * @returns {number} 0, 1, or 2, indicating rule severity + */ + function getRuleSeverity(ruleConfig) { + if (typeof ruleConfig === "number") { + return ruleConfig; + } else if (Array.isArray(ruleConfig)) { + return ruleConfig[0]; + } else { + return 0; + } + } + + /** + * Get the options for a rule (not including severity), if any + * @param {Array|number} ruleConfig rule configuration + * @returns {Array} of rule options, empty Array if none + */ + function getRuleOptions(ruleConfig) { + if (Array.isArray(ruleConfig)) { + return ruleConfig.slice(1); + } else { + return []; + } + } + + // set unlimited listeners (see https://github.com/eslint/eslint/issues/524) + api.setMaxListeners(0); + + /** + * Resets the internal state of the object. + * @returns {void} + */ + api.reset = function() { + this.removeAllListeners(); + messages = []; + currentConfig = null; + currentText = null; + currentTextLines = []; + currentTokens = null; + currentScopes = null; + scopeMap = null; + controller = null; + reportingConfig = []; + commentLocsEnter = []; + commentLocsExit = []; + }; + + /** + * Verifies the text against the rules specified by the second argument. + * @param {string} text The JavaScript text to verify. + * @param {Object} config An object whose keys specify the rules to use. + * @param {string=} filename The optional filename of the file being checked. + * If this is not set, the filename will default to '' in the rule context. + * @param {boolean=} saveState Indicates if the state from the last run should be saved. + * Mostly useful for testing purposes. + * @returns {Object[]} The results as an array of messages or null if no messages. + */ + api.verify = function(text, config, filename, saveState) { + + var ast; + + // set the current parsed filename + currentFilename = filename; + + if (!saveState) { + this.reset(); + } + + ast = parse(text.replace(/^#!([^\r\n]+[\r\n]+)/, "//$1")); + + // if Esprima failed to parse the file, there's no sense in setting up rules + if (ast) { + // process initial config to make it safe to extend + config = prepareConfig(config); + + // parse global comments and modify config + modifyConfigsFromComments(ast, config, reportingConfig); + + // enable appropriate rules + Object.keys(config.rules).filter(function(key) { + return getRuleSeverity(config.rules[key]) > 0; + }).forEach(function(key) { + + var ruleCreator = rules.get(key), + severity = getRuleSeverity(config.rules[key]), + options = getRuleOptions(config.rules[key]), + rule; + + if (ruleCreator) { + try { + rule = ruleCreator(new RuleContext(key, api, severity, options, config.settings)); + + // add all the node types as listeners + Object.keys(rule).forEach(function(nodeType) { + api.on(nodeType, rule[nodeType]); + }); + } catch(ex) { + ex.message = "Error while loading rule '" + key + "': " + ex.message; + throw ex; + } + + } else { + throw new Error("Definition for rule '" + key + "' was not found."); + } + }); + + // save config so rules can access as necessary + currentConfig = config; + currentText = text; + controller = new estraverse.Controller(); + + // gather data that may be needed by the rules + currentScopes = escope.analyze(ast, { ignoreEval: true }).scopes; + + /* + * Index the scopes by the start range of their block for efficient + * lookup in getScope. + */ + scopeMap = []; + currentScopes.forEach(function (scope, index) { + var range = scope.block.range[0]; + + // Sometimes two scopes are returned for a given node. This is + // handled later in a known way, so just don't overwrite here. + if (!scopeMap[range]) { + scopeMap[range] = index; + } + }); + + /* + * Split text here into array of lines so + * it's not being done repeatedly + * by individual rules. + */ + currentTextLines = currentText.split(/\r?\n/g); + + // Freezing so array isn't accidentally changed by a rule. + Object.freeze(currentTextLines); + + /* get all tokens from the ast and store them as a hashtable to + * improve traversal speed when wanting to find tokens for a given + * node + */ + currentTokens = []; + ast.tokens.forEach(function(token) { + currentTokens[token.range[0]] = token; + }); + + // augment global scope with declared global variables + addDeclaredGlobals(ast, currentScopes[0], currentConfig); + + /* + * Each node has a type property. Whenever a particular type of node is found, + * an event is fired. This allows any listeners to automatically be informed + * that this type of node has been found and react accordingly. + */ + controller.traverse(ast, { + enter: function(node, parent) { + + var comments = api.getComments(node); + + emitCommentsEnter(comments.leading); + node.parent = parent; + api.emit(node.type, node); + emitCommentsEnter(comments.trailing); + }, + leave: function(node) { + + var comments = api.getComments(node); + + emitCommentsExit(comments.trailing); + api.emit(node.type + ":exit", node); + emitCommentsExit(comments.leading); + } + }); + + } + + return messages; + }; + + /** + * Reports a message from one of the rules. + * @param {string} ruleId The ID of the rule causing the message. + * @param {number} severity The severity level of the rule as configured. + * @param {ASTNode} node The AST node that the message relates to. + * @param {Object=} location An object containing the error line and column + * numbers. If location is not provided the node's start location will + * be used. + * @param {string} message The actual message. + * @param {Object} opts Optional template data which produces a formatted message + * with symbols being replaced by this object's values. + * @returns {void} + */ + api.report = function(ruleId, severity, node, location, message, opts) { + + if (typeof location === "string") { + opts = message; + message = location; + location = node.loc.start; + } + + Object.keys(opts || {}).forEach(function (key) { + var rx = new RegExp("{{" + escapeRegExp(key) + "}}", "g"); + message = message.replace(rx, opts[key]); + }); + + if (isDisabledByReportingConfig(reportingConfig, ruleId, location)) { + return; + } + + messages.push({ + ruleId: ruleId, + severity: severity, + node: node, + message: message, + line: location.line, + column: location.column, + source: api.getSource(node) + }); + }; + + /** + * Gets the source code for the given node. + * @param {ASTNode=} node The AST node to get the text for. + * @param {int=} beforeCount The number of characters before the node to retrieve. + * @param {int=} afterCount The number of characters after the node to retrieve. + * @returns {string} The text representing the AST node. + */ + api.getSource = function(node, beforeCount, afterCount) { + if (node) { + return (currentText !== null) ? currentText.slice(node.range[0] - (beforeCount || 0), + node.range[1] + (afterCount || 0)) : null; + } else { + return currentText; + } + + }; + + /** + * Gets the entire source text split into an array of lines. + * @returns {Array} The source text as an array of lines. + */ + api.getSourceLines = function() { + return currentTextLines; + }; + + /** + * Gets all comments for the given node. + * @param {ASTNode} node The AST node to get the comments for. + * @returns {Object} The list of comments indexed by their position. + */ + api.getComments = function(node) { + + var leadingComments = node.leadingComments || [], + trailingComments = node.trailingComments || []; + + /* + * Esprima adds a "comments" array on Program nodes rather than + * leadingComments/trailingComments. Comments are only left in the + * Program node comments array if there is no executable code. + */ + if (node.type === "Program") { + if (node.body.length === 0) { + leadingComments = node.comments; + } + } + + return { + leading: leadingComments, + trailing: trailingComments + }; + }; + + /** + * Retrieves the JSDoc comment for a given node. + * @param {ASTNode} node The AST node to get the comment for. + * @returns {ASTNode} The BlockComment node containing the JSDoc for the + * given node or null if not found. + */ + api.getJSDocComment = function(node) { + + var parent = node.parent, + line = node.loc.start.line; + + /** + * Finds a JSDoc comment node in an array of comment nodes. + * @param {ASTNode[]} comments The array of comment nodes to search. + * @returns {ASTNode} The node if found, null if not. + * @private + */ + function findJSDocComment(comments) { + + if (comments) { + for (var i = comments.length - 1; i >= 0; i--) { + if (comments[i].type === "Block" && comments[i].value.charAt(0) === "*") { + + if (line - comments[i].loc.end.line <= 1) { + return comments[i]; + } else { + break; + } + } + } + } + + return null; + } + + switch (node.type) { + case "FunctionDeclaration": + return findJSDocComment(node.leadingComments); + + case "FunctionExpression": + + if (parent.type !== "CallExpression" || parent.callee !== node) { + while (parent && !parent.leadingComments && parent.type !== "FunctionExpression" && parent.type !== "FunctionDeclaration") { + parent = parent.parent; + } + + return parent && (parent.type !== "FunctionDeclaration") ? findJSDocComment(parent.leadingComments) : null; + } + + // falls through + + default: + return null; + } + }; + + /** + * Gets a number of tokens that precede a given node's tokens in the token stream. + * @param {ASTNode} node The AST node. + * @param {int} [beforeCount=0] The number of tokens before the node to retrieve. + * @returns {[Token]} Array of objects representing tokens. + */ + api.getTokensBefore = function(node, beforeCount) { + var beforeTokens = [], cursor = node.range[0] - 1; + while (beforeCount > 0 && cursor >= 0) { + if (currentTokens[cursor]) { + beforeTokens.unshift(currentTokens[cursor]); + --beforeCount; + } + --cursor; + } + return beforeTokens; + }; + + /** + * Gets the token that precedes a given node's tokens in the token stream. + * @param {ASTNode} node The AST node. + * @param {int} [skip=0] A number of tokens to skip before the given node. + * @returns {Token} An object representing the token. + */ + api.getTokenBefore = function(node, skip) { + for (var cursor = node.range[0] - 1; cursor >= 0; --cursor) { + if (currentTokens[cursor]) { + if (skip > 0) { + --skip; + } else { + return currentTokens[cursor]; + } + } + } + }; + + /** + * Gets a number of tokens that precede a given node's tokens in the token stream. + * @param {ASTNode} node The AST node. + * @param {int} [afterCount=0] The number of tokens after the node to retrieve. + * @returns {[Token]} Array of objects representing tokens. + */ + api.getTokensAfter = function(node, afterCount) { + var afterTokens = [], cursor = node.range[1]; + while (afterCount > 0 && cursor < currentTokens.length) { + if (currentTokens[cursor]) { + afterTokens.push(currentTokens[cursor]); + --afterCount; + cursor = currentTokens[cursor].range[1]; + } else { + ++cursor; + } + } + return afterTokens; + }; + + /** + * Gets the token that follows a given node's tokens in the token stream. + * @param {ASTNode} node The AST node. + * @param {int} [skip=0] A number of tokens to skip after the given node. + * @returns {Token} An object representing the token. + */ + api.getTokenAfter = function(node, skip) { + for (var cursor = node.range[1]; cursor < currentTokens.length; ++cursor) { + if (currentTokens[cursor]) { + if (skip > 0) { + --skip; + } else { + return currentTokens[cursor]; + } + } + } + }; + + /** + * Gets all tokens that are related to the given node. + * @param {ASTNode} node The AST node. + * @param {int} [beforeCount=0] The number of tokens before the node to retrieve. + * @param {int} [afterCount=0] The number of tokens after the node to retrieve. + * @returns {[Token]} Array of objects representing tokens. + */ + api.getTokens = function(node, beforeCount, afterCount) { + var beforeTokens = api.getTokensBefore(node, beforeCount), + afterTokens = api.getTokensAfter(node, afterCount), + tokens = [], + cursor = node.range[0]; + while (cursor < node.range[1]) { + if (currentTokens[cursor]) { + tokens.push(currentTokens[cursor]); + cursor = currentTokens[cursor].range[1]; + } else { + ++cursor; + } + } + return beforeTokens.concat(tokens, afterTokens); + }; + + /** + * Gets the first `count` tokens of the given node's token stream. + * @param {ASTNode} node The AST node. + * @param {int} [count=0] The number of tokens of the node to retrieve. + * @returns {[Token]} Array of objects representing tokens. + */ + api.getFirstTokens = function(node, count) { + var tokens = [], cursor = node.range[0]; + while (count > 0 && cursor < node.range[1]) { + if (currentTokens[cursor]) { + tokens.push(currentTokens[cursor]); + --count; + cursor = currentTokens[cursor].range[1]; + } else { + ++cursor; + } + } + return tokens; + }; + + /** + * Gets the first token of the given node's token stream. + * @param {ASTNode} node The AST node. + * @param {int} [skip=0] A number of tokens to skip. + * @returns {Token} An object representing the token. + */ + api.getFirstToken = function(node, skip) { + for (var cursor = node.range[0]; cursor < node.range[1]; ++cursor) { + if (currentTokens[cursor]) { + if (skip > 0) { + --skip; + } else { + return currentTokens[cursor]; + } + } + } + }; + + /** + * Gets the last `count` tokens of the given node. + * @param {ASTNode} node The AST node. + * @param {int} [count=0] The number of tokens of the node to retrieve. + * @returns {[Token]} Array of objects representing tokens. + */ + api.getLastTokens = function(node, count) { + var tokens = [], cursor = node.range[1] - 1; + while (count > 0 && cursor >= node.range[0]) { + if (currentTokens[cursor]) { + tokens.unshift(currentTokens[cursor]); + --count; + } + --cursor; + } + return tokens; + }; + + /** + * Gets the last token of the given node's token stream. + * @param {ASTNode} node The AST node. + * @param {int} [skip=0] A number of tokens to skip. + * @returns {Token} An object representing the token. + */ + api.getLastToken = function(node, skip) { + for (var cursor = node.range[1] - 1; cursor >= node.range[0]; --cursor) { + if (currentTokens[cursor]) { + if (skip > 0) { + --skip; + } else { + return currentTokens[cursor]; + } + } + } + }; + + /** + * Gets nodes that are ancestors of current node. + * @returns {ASTNode[]} Array of objects representing ancestors. + */ + api.getAncestors = function() { + return controller.parents(); + }; + + + /** + * Gets the scope for the current node. + * @returns {Object} An object representing the current node's scope. + */ + api.getScope = function() { + var parents = controller.parents(), + innerBlock = null, + selectedScopeIndex; + + // Don't do this for Program nodes - they have no parents + if (parents.length) { + + // if current node is function declaration, add it to the list + var current = controller.current(); + if (current.type === "FunctionDeclaration" || current.type === "FunctionExpression") { + parents.push(current); + } + + // Ascend the current node's parents + for (var i = parents.length - 1; i >= 0; --i) { + + // The first node that requires a scope is the node that will be + // our current node's innermost scope. + if (escope.Scope.isScopeRequired(parents[i])) { + innerBlock = parents[i]; + break; + } + } + + // Find and return the innermost scope + selectedScopeIndex = scopeMap[innerBlock.range[0]]; + + // Named function expressions create two nested scope objects. The + // outer scope contains only the function expression name. We return + // the inner scope. + if (innerBlock.type === "FunctionExpression" && innerBlock.id && innerBlock.id.name) { + ++selectedScopeIndex; + } + + return currentScopes[selectedScopeIndex]; + } else { + return currentScopes[0]; // global scope + } + }; + + /** + * Gets the filename for the currently parsed source. + * @returns {string} The filename associated with the source being parsed. + * Defaults to "" if no filename info is present. + */ + api.getFilename = function() { + if (typeof currentFilename === "string") { + return currentFilename; + } else { + return ""; + } + }; + + /** + * Defines a new linting rule. + * @param {string} ruleId A unique rule identifier + * @param {Function} ruleModule Function from context to object mapping AST node types to event handlers + * @returns {void} + */ + var defineRule = api.defineRule = function(ruleId, ruleModule) { + rules.define(ruleId, ruleModule); + }; + + /** + * Defines many new linting rules. + * @param {object} rules map from unique rule identifier to rule + * @returns {void} + */ + api.defineRules = function(rules) { + Object.getOwnPropertyNames(rules).forEach(function(ruleId) { + defineRule(ruleId, rules[ruleId]); + }); + }; + + /** + * Gets the default eslint configuration. + * @returns {Object} Object mapping rule IDs to their default configurations + */ + api.defaults = function() { + return require("../conf/eslint.json"); + }; + + return api; + +}()); + +},{"../conf/environments.json":1,"../conf/eslint.json":2,"./rule-context":11,"./rules":12,"./util":150,"escope":5,"esprima":6,"estraverse":7,"events":3,"object-assign":8}],10:[function(require,module,exports){ +module.exports = function() { + var rules = Object.create(null); + rules["block-scoped-var"] = require("./rules/block-scoped-var"); + rules["brace-style"] = require("./rules/brace-style"); + rules["camelcase"] = require("./rules/camelcase"); + rules["comma-spacing"] = require("./rules/comma-spacing"); + rules["comma-style"] = require("./rules/comma-style"); + rules["complexity"] = require("./rules/complexity"); + rules["consistent-return"] = require("./rules/consistent-return"); + rules["consistent-this"] = require("./rules/consistent-this"); + rules["curly"] = require("./rules/curly"); + rules["default-case"] = require("./rules/default-case"); + rules["dot-notation"] = require("./rules/dot-notation"); + rules["eol-last"] = require("./rules/eol-last"); + rules["eqeqeq"] = require("./rules/eqeqeq"); + rules["func-names"] = require("./rules/func-names"); + rules["func-style"] = require("./rules/func-style"); + rules["global-strict"] = require("./rules/global-strict"); + rules["guard-for-in"] = require("./rules/guard-for-in"); + rules["handle-callback-err"] = require("./rules/handle-callback-err"); + rules["key-spacing"] = require("./rules/key-spacing"); + rules["max-depth"] = require("./rules/max-depth"); + rules["max-len"] = require("./rules/max-len"); + rules["max-nested-callbacks"] = require("./rules/max-nested-callbacks"); + rules["max-params"] = require("./rules/max-params"); + rules["max-statements"] = require("./rules/max-statements"); + rules["new-cap"] = require("./rules/new-cap"); + rules["new-parens"] = require("./rules/new-parens"); + rules["no-alert"] = require("./rules/no-alert"); + rules["no-array-constructor"] = require("./rules/no-array-constructor"); + rules["no-bitwise"] = require("./rules/no-bitwise"); + rules["no-caller"] = require("./rules/no-caller"); + rules["no-catch-shadow"] = require("./rules/no-catch-shadow"); + rules["no-comma-dangle"] = require("./rules/no-comma-dangle"); + rules["no-cond-assign"] = require("./rules/no-cond-assign"); + rules["no-console"] = require("./rules/no-console"); + rules["no-constant-condition"] = require("./rules/no-constant-condition"); + rules["no-control-regex"] = require("./rules/no-control-regex"); + rules["no-debugger"] = require("./rules/no-debugger"); + rules["no-delete-var"] = require("./rules/no-delete-var"); + rules["no-div-regex"] = require("./rules/no-div-regex"); + rules["no-dupe-keys"] = require("./rules/no-dupe-keys"); + rules["no-else-return"] = require("./rules/no-else-return"); + rules["no-empty-class"] = require("./rules/no-empty-class"); + rules["no-empty-label"] = require("./rules/no-empty-label"); + rules["no-empty"] = require("./rules/no-empty"); + rules["no-eq-null"] = require("./rules/no-eq-null"); + rules["no-eval"] = require("./rules/no-eval"); + rules["no-ex-assign"] = require("./rules/no-ex-assign"); + rules["no-extend-native"] = require("./rules/no-extend-native"); + rules["no-extra-bind"] = require("./rules/no-extra-bind"); + rules["no-extra-boolean-cast"] = require("./rules/no-extra-boolean-cast"); + rules["no-extra-parens"] = require("./rules/no-extra-parens"); + rules["no-extra-semi"] = require("./rules/no-extra-semi"); + rules["no-extra-strict"] = require("./rules/no-extra-strict"); + rules["no-fallthrough"] = require("./rules/no-fallthrough"); + rules["no-floating-decimal"] = require("./rules/no-floating-decimal"); + rules["no-func-assign"] = require("./rules/no-func-assign"); + rules["no-implied-eval"] = require("./rules/no-implied-eval"); + rules["no-inner-declarations"] = require("./rules/no-inner-declarations"); + rules["no-invalid-regexp"] = require("./rules/no-invalid-regexp"); + rules["no-iterator"] = require("./rules/no-iterator"); + rules["no-label-var"] = require("./rules/no-label-var"); + rules["no-labels"] = require("./rules/no-labels"); + rules["no-lone-blocks"] = require("./rules/no-lone-blocks"); + rules["no-lonely-if"] = require("./rules/no-lonely-if"); + rules["no-loop-func"] = require("./rules/no-loop-func"); + rules["no-mixed-requires"] = require("./rules/no-mixed-requires"); + rules["no-mixed-spaces-and-tabs"] = require("./rules/no-mixed-spaces-and-tabs"); + rules["no-multi-spaces"] = require("./rules/no-multi-spaces"); + rules["no-multi-str"] = require("./rules/no-multi-str"); + rules["no-multiple-empty-lines"] = require("./rules/no-multiple-empty-lines"); + rules["no-native-reassign"] = require("./rules/no-native-reassign"); + rules["no-negated-in-lhs"] = require("./rules/no-negated-in-lhs"); + rules["no-nested-ternary"] = require("./rules/no-nested-ternary"); + rules["no-new-func"] = require("./rules/no-new-func"); + rules["no-new-object"] = require("./rules/no-new-object"); + rules["no-new-require"] = require("./rules/no-new-require"); + rules["no-new-wrappers"] = require("./rules/no-new-wrappers"); + rules["no-new"] = require("./rules/no-new"); + rules["no-obj-calls"] = require("./rules/no-obj-calls"); + rules["no-octal-escape"] = require("./rules/no-octal-escape"); + rules["no-octal"] = require("./rules/no-octal"); + rules["no-path-concat"] = require("./rules/no-path-concat"); + rules["no-plusplus"] = require("./rules/no-plusplus"); + rules["no-process-env"] = require("./rules/no-process-env"); + rules["no-process-exit"] = require("./rules/no-process-exit"); + rules["no-proto"] = require("./rules/no-proto"); + rules["no-redeclare"] = require("./rules/no-redeclare"); + rules["no-regex-spaces"] = require("./rules/no-regex-spaces"); + rules["no-reserved-keys"] = require("./rules/no-reserved-keys"); + rules["no-restricted-modules"] = require("./rules/no-restricted-modules"); + rules["no-return-assign"] = require("./rules/no-return-assign"); + rules["no-script-url"] = require("./rules/no-script-url"); + rules["no-self-compare"] = require("./rules/no-self-compare"); + rules["no-sequences"] = require("./rules/no-sequences"); + rules["no-shadow-restricted-names"] = require("./rules/no-shadow-restricted-names"); + rules["no-shadow"] = require("./rules/no-shadow"); + rules["no-space-before-semi"] = require("./rules/no-space-before-semi"); + rules["no-spaced-func"] = require("./rules/no-spaced-func"); + rules["no-sparse-arrays"] = require("./rules/no-sparse-arrays"); + rules["no-sync"] = require("./rules/no-sync"); + rules["no-ternary"] = require("./rules/no-ternary"); + rules["no-trailing-spaces"] = require("./rules/no-trailing-spaces"); + rules["no-undef-init"] = require("./rules/no-undef-init"); + rules["no-undef"] = require("./rules/no-undef"); + rules["no-undefined"] = require("./rules/no-undefined"); + rules["no-underscore-dangle"] = require("./rules/no-underscore-dangle"); + rules["no-unreachable"] = require("./rules/no-unreachable"); + rules["no-unused-expressions"] = require("./rules/no-unused-expressions"); + rules["no-unused-vars"] = require("./rules/no-unused-vars"); + rules["no-use-before-define"] = require("./rules/no-use-before-define"); + rules["no-void"] = require("./rules/no-void"); + rules["no-warning-comments"] = require("./rules/no-warning-comments"); + rules["no-with"] = require("./rules/no-with"); + rules["no-wrap-func"] = require("./rules/no-wrap-func"); + rules["one-var"] = require("./rules/one-var"); + rules["padded-blocks"] = require("./rules/padded-blocks"); + rules["quote-props"] = require("./rules/quote-props"); + rules["quotes"] = require("./rules/quotes"); + rules["radix"] = require("./rules/radix"); + rules["semi"] = require("./rules/semi"); + rules["sort-vars"] = require("./rules/sort-vars"); + rules["space-after-keywords"] = require("./rules/space-after-keywords"); + rules["space-before-blocks"] = require("./rules/space-before-blocks"); + rules["space-in-brackets"] = require("./rules/space-in-brackets"); + rules["space-in-parens"] = require("./rules/space-in-parens"); + rules["space-infix-ops"] = require("./rules/space-infix-ops"); + rules["space-return-throw-case"] = require("./rules/space-return-throw-case"); + rules["space-unary-word-ops"] = require("./rules/space-unary-word-ops"); + rules["spaced-line-comment"] = require("./rules/spaced-line-comment"); + rules["strict"] = require("./rules/strict"); + rules["use-isnan"] = require("./rules/use-isnan"); + rules["valid-jsdoc"] = require("./rules/valid-jsdoc"); + rules["valid-typeof"] = require("./rules/valid-typeof"); + rules["vars-on-top"] = require("./rules/vars-on-top"); + rules["wrap-iife"] = require("./rules/wrap-iife"); + rules["wrap-regex"] = require("./rules/wrap-regex"); + rules["yoda"] = require("./rules/yoda"); + + return rules; +}; +},{"./rules/block-scoped-var":13,"./rules/brace-style":14,"./rules/camelcase":15,"./rules/comma-spacing":16,"./rules/comma-style":17,"./rules/complexity":18,"./rules/consistent-return":19,"./rules/consistent-this":20,"./rules/curly":21,"./rules/default-case":22,"./rules/dot-notation":23,"./rules/eol-last":24,"./rules/eqeqeq":25,"./rules/func-names":26,"./rules/func-style":27,"./rules/global-strict":28,"./rules/guard-for-in":29,"./rules/handle-callback-err":30,"./rules/key-spacing":31,"./rules/max-depth":32,"./rules/max-len":33,"./rules/max-nested-callbacks":34,"./rules/max-params":35,"./rules/max-statements":36,"./rules/new-cap":37,"./rules/new-parens":38,"./rules/no-alert":39,"./rules/no-array-constructor":40,"./rules/no-bitwise":41,"./rules/no-caller":42,"./rules/no-catch-shadow":43,"./rules/no-comma-dangle":44,"./rules/no-cond-assign":45,"./rules/no-console":46,"./rules/no-constant-condition":47,"./rules/no-control-regex":48,"./rules/no-debugger":49,"./rules/no-delete-var":50,"./rules/no-div-regex":51,"./rules/no-dupe-keys":52,"./rules/no-else-return":53,"./rules/no-empty":56,"./rules/no-empty-class":54,"./rules/no-empty-label":55,"./rules/no-eq-null":57,"./rules/no-eval":58,"./rules/no-ex-assign":59,"./rules/no-extend-native":60,"./rules/no-extra-bind":61,"./rules/no-extra-boolean-cast":62,"./rules/no-extra-parens":63,"./rules/no-extra-semi":64,"./rules/no-extra-strict":65,"./rules/no-fallthrough":66,"./rules/no-floating-decimal":67,"./rules/no-func-assign":68,"./rules/no-implied-eval":69,"./rules/no-inner-declarations":70,"./rules/no-invalid-regexp":71,"./rules/no-iterator":72,"./rules/no-label-var":73,"./rules/no-labels":74,"./rules/no-lone-blocks":75,"./rules/no-lonely-if":76,"./rules/no-loop-func":77,"./rules/no-mixed-requires":78,"./rules/no-mixed-spaces-and-tabs":79,"./rules/no-multi-spaces":80,"./rules/no-multi-str":81,"./rules/no-multiple-empty-lines":82,"./rules/no-native-reassign":83,"./rules/no-negated-in-lhs":84,"./rules/no-nested-ternary":85,"./rules/no-new":90,"./rules/no-new-func":86,"./rules/no-new-object":87,"./rules/no-new-require":88,"./rules/no-new-wrappers":89,"./rules/no-obj-calls":91,"./rules/no-octal":93,"./rules/no-octal-escape":92,"./rules/no-path-concat":94,"./rules/no-plusplus":95,"./rules/no-process-env":96,"./rules/no-process-exit":97,"./rules/no-proto":98,"./rules/no-redeclare":99,"./rules/no-regex-spaces":100,"./rules/no-reserved-keys":101,"./rules/no-restricted-modules":102,"./rules/no-return-assign":103,"./rules/no-script-url":104,"./rules/no-self-compare":105,"./rules/no-sequences":106,"./rules/no-shadow":108,"./rules/no-shadow-restricted-names":107,"./rules/no-space-before-semi":109,"./rules/no-spaced-func":110,"./rules/no-sparse-arrays":111,"./rules/no-sync":112,"./rules/no-ternary":113,"./rules/no-trailing-spaces":114,"./rules/no-undef":116,"./rules/no-undef-init":115,"./rules/no-undefined":117,"./rules/no-underscore-dangle":118,"./rules/no-unreachable":119,"./rules/no-unused-expressions":120,"./rules/no-unused-vars":121,"./rules/no-use-before-define":122,"./rules/no-void":123,"./rules/no-warning-comments":124,"./rules/no-with":125,"./rules/no-wrap-func":126,"./rules/one-var":127,"./rules/padded-blocks":128,"./rules/quote-props":129,"./rules/quotes":130,"./rules/radix":131,"./rules/semi":132,"./rules/sort-vars":133,"./rules/space-after-keywords":134,"./rules/space-before-blocks":135,"./rules/space-in-brackets":136,"./rules/space-in-parens":137,"./rules/space-infix-ops":138,"./rules/space-return-throw-case":139,"./rules/space-unary-word-ops":140,"./rules/spaced-line-comment":141,"./rules/strict":142,"./rules/use-isnan":143,"./rules/valid-jsdoc":144,"./rules/valid-typeof":145,"./rules/vars-on-top":146,"./rules/wrap-iife":147,"./rules/wrap-regex":148,"./rules/yoda":149}],11:[function(require,module,exports){ +/** + * @fileoverview RuleContext utility for rules + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Constants +//------------------------------------------------------------------------------ + +var PASSTHROUGHS = [ + "getSource", + "getSourceLines", + "getTokens", + "getTokensBefore", + "getTokenBefore", + "getTokensAfter", + "getTokenAfter", + "getFirstTokens", + "getFirstToken", + "getLastTokens", + "getLastToken", + "getComments", + "getAncestors", + "getScope", + "getJSDocComment", + "getFilename" + ]; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** + * Acts as an abstraction layer between rules and the main eslint object. + * @constructor + * @param {string} ruleId The ID of the rule using this object. + * @param {eslint} eslint The eslint object. + * @param {number} severity The configured severity level of the rule. + * @param {array} options The configuration information to be added to the rule. + * @param {object} settings The configuration settings passed from the config file. + */ +function RuleContext(ruleId, eslint, severity, options, settings) { + + /** + * The read-only ID of the rule. + */ + Object.defineProperty(this, "id", { + value: ruleId + }); + + /** + * The read-only options of the rule + */ + Object.defineProperty(this, "options", { + value: options + }); + + /** + * The read-only settings shared between all rules + */ + Object.defineProperty(this, "settings", { + value: settings + }); + + // copy over passthrough methods + PASSTHROUGHS.forEach(function(name) { + this[name] = function() { + return eslint[name].apply(eslint, arguments); + }; + }, this); + + /** + * Passthrough to eslint.report() that automatically assigns the rule ID and severity. + * @param {ASTNode} node The AST node related to the message. + * @param {Object=} location The location of the error. + * @param {string} message The message to display to the user. + * @param {Object} opts Optional template data which produces a formatted message + * with symbols being replaced by this object's values. + * @returns {void} + */ + this.report = function(node, location, message, opts) { + eslint.report(ruleId, severity, node, location, message, opts); + }; + +} + +RuleContext.prototype = { + constructor: RuleContext +}; + +module.exports = RuleContext; + +},{}],12:[function(require,module,exports){ +/** + * @fileoverview Defines a storage for rules. + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +var loadRules = require("./load-rules"); + +//------------------------------------------------------------------------------ +// Privates +//------------------------------------------------------------------------------ + +var rules = Object.create(null); + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Registers a rule module for rule id in storage. + * @param {String} ruleId Rule id (file name). + * @param {Function} ruleModule Rule handler. + * @returns {void} + */ +function define(ruleId, ruleModule) { + rules[ruleId] = ruleModule; +} + +exports.define = define; + +/** + * Loads and registers all rules from passed rules directory. + * @param {String} [rulesDir] Path to rules directory, may be relative. Defaults to `lib/rules`. + * @returns {void} + */ +function load(rulesDir) { + var newRules = loadRules(rulesDir); + Object.keys(newRules).forEach(function(ruleId) { + define(ruleId, newRules[ruleId]); + }); +} + +exports.load = load; + +/** + * Registers all given rules of a plugin. + * @param {Object} pluginRules A key/value map of rule definitions. + * @param {String} pluginName The name of the plugin without prefix (`eslint-plugin-`). + * @returns {void} + */ +exports.import = function (pluginRules, pluginName) { + Object.keys(pluginRules).forEach(function (ruleId) { + var qualifiedRuleId = pluginName + "/" + ruleId, + rule = pluginRules[ruleId]; + + define(qualifiedRuleId, rule); + }); +}; + +/** + * Access rule handler by id (file name). + * @param {String} ruleId Rule id (file name). + * @returns {Function} Rule handler. + */ +exports.get = function(ruleId) { + return rules[ruleId]; +}; + +/** + * Reset rules storage. + * Should be used only in tests. + * @returns {void} + */ +exports.testClear = function() { + rules = Object.create(null); +}; + +//------------------------------------------------------------------------------ +// Initialization +//------------------------------------------------------------------------------ + +// loads built-in rules +load(); + +},{"./load-rules":10}],13:[function(require,module,exports){ +/** + * @fileoverview Rule to check for "block scoped" variables by binding context + * @author Matt DuVall + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var scopeStack = []; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Determines whether an identifier is in declaration position or is a non-declaration reference. + * @param {ASTNode} id The identifier. + * @param {ASTNode} parent The identifier's parent AST node. + * @returns {Boolean} true when the identifier is in declaration position. + */ + function isDeclaration(id, parent) { + switch (parent.type) { + case "FunctionDeclaration": + case "FunctionExpression": + return parent.params.indexOf(id) > -1 || id === parent.id; + + case "VariableDeclarator": + return id === parent.id; + + case "CatchClause": + return id === parent.param; + + default: + return false; + } + } + + /** + * Determines whether an identifier is in property position. + * @param {ASTNode} id The identifier. + * @param {ASTNode} parent The identifier's parent AST node. + * @returns {Boolean} true when the identifier is in property position. + */ + function isProperty(id, parent) { + switch (parent.type) { + case "MemberExpression": + return id === parent.property && !parent.computed; + + case "Property": + return id === parent.key; + + default: + return false; + } + } + + /** + * Pushes a new scope object on the scope stack. + * @returns {void} + */ + function pushScope() { + scopeStack.push([]); + } + + /** + * Removes the topmost scope object from the scope stack. + * @returns {void} + */ + function popScope() { + scopeStack.pop(); + } + + /** + * Declares the given names in the topmost scope object. + * @param {[String]} names A list of names to declare. + * @returns {void} + */ + function declare(names) { + [].push.apply(scopeStack[scopeStack.length - 1], names); + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + function functionHandler(node) { + pushScope(); + declare(node.params.map(function(id) { + return id.name; + })); + declare(node.id ? [node.id.name] : []); + declare(["arguments"]); + } + + function variableDeclarationHandler(node) { + declare(node.declarations.map(function(decl) { + return decl.id.name; + })); + } + + return { + "Program": function() { + scopeStack = [context.getScope().variables.map(function(v) { + return v.name; + })]; + }, + + "BlockStatement": function(node) { + var statements = node.body; + pushScope(); + statements.forEach(function(stmt) { + if (stmt.type === "VariableDeclaration") { + variableDeclarationHandler(stmt); + } else if (stmt.type === "FunctionDeclaration") { + declare([stmt.id.name]); + } + }); + }, + + "BlockStatement:exit": popScope, + + "CatchClause": function(node) { + pushScope(); + declare([node.param.name]); + }, + "CatchClause:exit": popScope, + + "FunctionDeclaration": functionHandler, + "FunctionDeclaration:exit": popScope, + + "FunctionExpression": functionHandler, + "FunctionExpression:exit": popScope, + + "ForStatement": function(node) { + pushScope(); + if (node.init && node.init.type === "VariableDeclaration") { + variableDeclarationHandler(node.init); + } + }, + "ForStatement:exit": popScope, + + "ForInStatement": function(node) { + pushScope(); + if (node.left.type === "VariableDeclaration") { + variableDeclarationHandler(node.left); + } + }, + "ForInStatement:exit": popScope, + + "Identifier": function(node) { + var ancestor = context.getAncestors().pop(); + if (isDeclaration(node, ancestor) || isProperty(node, ancestor)) { + return; + } + for (var i = 0, l = scopeStack.length; i < l; i++) { + if (scopeStack[i].indexOf(node.name) > -1) { + return; + } + } + + context.report(node, "\"" + node.name + "\" used outside of binding context."); + } + }; + +}; + +},{}],14:[function(require,module,exports){ +/** + * @fileoverview Rule to flag block statements that do not use the one true brace style + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + var style = context.options[0] || "1tbs"; + var params = context.options[1] || {}; + + var OPEN_MESSAGE = "Opening curly brace does not appear on the same line as controlling statement.", + BODY_MESSAGE = "Statement inside of curly braces should be on next line.", + CLOSE_MESSAGE = "Closing curly brace does not appear on the same line as the subsequent block.", + CLOSE_MESSAGE_SINGLE = "Closing curly brace should be on the same line as opening curly brace or on the line after the previous block.", + CLOSE_MESSAGE_STROUSTRUP = "Closing curly brace appears on the same line as the subsequent block."; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Binds a list of properties to a function that verifies that the opening + * curly brace is on the same line as its controlling statement of a given + * node. + * @param {...string} The properties to check on the node. + * @returns {Function} A function that will perform the check on a node + */ + function checkBlock() { + var blockProperties = arguments; + return function(node) { + [].forEach.call(blockProperties, function(blockProp) { + var block = node[blockProp], previousToken, curlyToken, curlyTokenEnd, curlyTokensOnSameLine; + block = node[blockProp]; + if (block && block.type === "BlockStatement") { + previousToken = context.getTokenBefore(block); + curlyToken = context.getFirstToken(block); + curlyTokenEnd = context.getLastToken(block); + curlyTokensOnSameLine = curlyToken.loc.start.line === curlyTokenEnd.loc.start.line; + + if (previousToken.loc.start.line !== curlyToken.loc.start.line) { + context.report(node, OPEN_MESSAGE); + } else if (block.body.length && params.allowSingleLine) { + if (curlyToken.loc.start.line === block.body[0].loc.start.line && !curlyTokensOnSameLine) { + context.report(block.body[0], BODY_MESSAGE); + } else if (curlyTokenEnd.loc.start.line === block.body[block.body.length - 1].loc.start.line && !curlyTokensOnSameLine) { + context.report(block.body[block.body.length - 1], CLOSE_MESSAGE_SINGLE); + } + } else if (block.body.length && curlyToken.loc.start.line === block.body[0].loc.start.line) { + context.report(block.body[0], BODY_MESSAGE); + } + } + }); + }; + } + + /** + * Enforces the configured brace style on IfStatements + * @param {ASTNode} node An IfStatement node. + * @returns {void} + */ + function checkIfStatement(node) { + var tokens; + + checkBlock("consequent", "alternate")(node); + + if (node.alternate && node.alternate.type === "BlockStatement") { + tokens = context.getTokensBefore(node.alternate, 2); + if (style === "1tbs") { + if (tokens[0].loc.start.line !== tokens[1].loc.start.line) { + context.report(node.alternate, CLOSE_MESSAGE); + } + } else if (style === "stroustrup") { + if (tokens[0].loc.start.line === tokens[1].loc.start.line) { + context.report(node.alternate, CLOSE_MESSAGE_STROUSTRUP); + } + } + } + } + + /** + * Enforces the configured brace style on TryStatements + * @param {ASTNode} node A TryStatement node. + * @returns {void} + */ + function checkTryStatement(node) { + var tokens; + + checkBlock("block", "finalizer")(node); + + if (node.finalizer && node.finalizer.type === "BlockStatement") { + tokens = context.getTokensBefore(node.finalizer, 2); + if (style === "1tbs") { + if (tokens[0].loc.start.line !== tokens[1].loc.start.line) { + context.report(node.finalizer, CLOSE_MESSAGE); + } + } else if (style === "stroustrup") { + if (tokens[0].loc.start.line === tokens[1].loc.start.line) { + context.report(node.finalizer, CLOSE_MESSAGE_STROUSTRUP); + } + } + } + } + + /** + * Enforces the configured brace style on CatchClauses + * @param {ASTNode} node A CatchClause node. + * @returns {void} + */ + function checkCatchClause(node) { + var previousToken = context.getTokenBefore(node), + firstToken = context.getFirstToken(node); + + checkBlock("body")(node); + + if (node.body && node.body.type === "BlockStatement") { + if (style === "1tbs") { + if (previousToken.loc.start.line !== firstToken.loc.start.line) { + context.report(node, CLOSE_MESSAGE); + } + } else if (style === "stroustrup") { + if (previousToken.loc.start.line === firstToken.loc.start.line) { + context.report(node, CLOSE_MESSAGE_STROUSTRUP); + } + } + } + } + + /** + * Enforces the configured brace style on SwitchStatements + * @param {ASTNode} node A SwitchStatement node. + * @returns {void} + */ + function checkSwitchStatement(node) { + var tokens; + if (node.cases && node.cases.length) { + tokens = context.getTokensBefore(node.cases[0], 2); + if (tokens[0].loc.start.line !== tokens[1].loc.start.line) { + context.report(node, OPEN_MESSAGE); + } + } else { + tokens = context.getLastTokens(node, 3); + if (tokens[0].loc.start.line !== tokens[1].loc.start.line) { + context.report(node, OPEN_MESSAGE); + } + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + "FunctionDeclaration": checkBlock("body"), + "FunctionExpression": checkBlock("body"), + "IfStatement": checkIfStatement, + "TryStatement": checkTryStatement, + "CatchClause": checkCatchClause, + "DoWhileStatement": checkBlock("body"), + "WhileStatement": checkBlock("body"), + "WithStatement": checkBlock("body"), + "ForStatement": checkBlock("body"), + "ForInStatement": checkBlock("body"), + "SwitchStatement": checkSwitchStatement + }; + +}; + +},{}],15:[function(require,module,exports){ +/** + * @fileoverview Rule to flag non-camelcased identifiers + * @author Nicholas C. Zakas + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Checks if a string contains an underscore and isn't all upper-case + * @param {String} name The string to check. + * @returns {boolean} if the string is underscored + * @private + */ + function isUnderscored(name) { + + // if there's an underscore, it might be A_CONSTANT, which is okay + return name.indexOf("_") > -1 && name !== name.toUpperCase(); + } + + /** + * Reports an AST node as a rule violation. + * @param {ASTNode} node The node to report. + * @returns {void} + * @private + */ + function report(node) { + context.report(node, "Identifier '{{name}}' is not in camel case.", { name: node.name }); + } + + return { + + "Identifier": function(node) { + + // Leading and trailing underscores are commonly used to flag private/protected identifiers, strip them + var name = node.name.replace(/^_+|_+$/g, ""), + effectiveParent = (node.parent.type === "MemberExpression") ? node.parent.parent : node.parent; + + // MemberExpressions get special rules + if (node.parent.type === "MemberExpression") { + + // Always report underscored object names + if (node.parent.object.type === "Identifier" && + node.parent.object.name === node.name && + isUnderscored(name)) { + report(node); + + // Report AssignmentExpressions only if they are the left side of the assignment + } else if (effectiveParent.type === "AssignmentExpression" && + isUnderscored(name) && + (effectiveParent.right.type !== "MemberExpression" || + effectiveParent.left.type === "MemberExpression" && + effectiveParent.left.property.name === node.name)) { + report(node); + } + + // Report anything that is underscored that isn't a CallExpression + } else if (isUnderscored(name) && effectiveParent.type !== "CallExpression") { + report(node); + } + } + }; + +}; + +},{}],16:[function(require,module,exports){ +/** + * @fileoverview Comma spacing - validates spacing before and after comma + * @author Vignesh Anand aka vegetableman. + * @copyright 2014 Vignesh Anand. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + var options = { + before: context.options[0] ? !!context.options[0].before : false, + after: context.options[0] ? !!context.options[0].after : true + }; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Determines whether two adjacent tokens have whitespace between them. + * @param {Object} left - The left token object. + * @param {Object} right - The right token object. + * @returns {boolean} Whether or not there is space between the tokens. + */ + function isSpaced(left, right) { + return left.range[1] < right.range[0]; + } + + /** + * Run report. + * @param {ASTNode} node The binary expression node to check. + * @param {string} msg The error msg to show. + * @private + * @returns {void} + */ + function report(node, msg) { + context.report(node, msg); + } + + /** + * Show space required message. + * @param {string} dir The location of spacing. + * @private + * @returns {string} The spacing error msg. + */ + function getSpaceReqMsg(dir) { + return "A space is required " + dir + " ','."; + } + + /** + * Show no space message. + * @param {string} dir The location of spacing + * @private + * @returns {string} The spacing error msg. + */ + function getNoSpaceMsg(dir) { + return "There should be no space " + dir + " ','."; + } + + /** + * Validates the spacing before and after commas. + * @param {ASTNode} node The binary expression node to check. + * @param {string} property The property of the node. + * @private + * @returns {void} + */ + function validateCommaSpacing(node, property) { + var items = node[property]; + + if (items && items.length > 1) { + items.forEach(function(item, index) { + var tokenBefore = context.getTokenBefore(item), + itemBefore = items[index - 1], + tokenEndLine; + + if (tokenBefore && tokenBefore.value === ",") { + tokenEndLine = tokenBefore.loc.end.line; + + // single line + if (tokenEndLine === itemBefore.loc.end.line && + tokenEndLine === item.loc.start.line) { + if (options.before && options.after) { + if (!isSpaced(itemBefore, tokenBefore)) { + report(item, getSpaceReqMsg("before")); + } + if (!isSpaced(tokenBefore, item)) { + report(item, getSpaceReqMsg("after")); + } + } else if (options.before) { + if (!isSpaced(itemBefore, tokenBefore)) { + report(item, getSpaceReqMsg("before")); + } + if (isSpaced(tokenBefore, item)) { + report(item, getNoSpaceMsg("after")); + } + } else if (options.after) { + if (!isSpaced(tokenBefore, item)) { + report(item, getSpaceReqMsg("after")); + } + if (isSpaced(itemBefore, tokenBefore)) { + report(item, getNoSpaceMsg("before")); + } + } else { + if (isSpaced(itemBefore, tokenBefore)) { + report(item, getNoSpaceMsg("before")); + } + if (isSpaced(tokenBefore, item)) { + report(item, getNoSpaceMsg("after")); + } + } + } + } + }); + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + "VariableDeclaration": function(node) { + validateCommaSpacing(node, "declarations"); + }, + "ObjectExpression": function(node) { + validateCommaSpacing(node, "properties"); + }, + "ArrayExpression": function(node) { + validateCommaSpacing(node, "elements"); + }, + "SequenceExpression": function(node) { + validateCommaSpacing(node, "expressions"); + }, + "FunctionExpression": function(node) { + validateCommaSpacing(node, "params"); + }, + "FunctionDeclaration": function(node) { + validateCommaSpacing(node, "params"); + } + }; + +}; + +},{}],17:[function(require,module,exports){ +/** + * @fileoverview Comma style - enforces comma styles of two types: last and first + * @author Vignesh Anand aka vegetableman + * @copyright 2014 Vignesh Anand. All rights reserved. + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + var style = context.options[0] || "last"; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Checks the comma placement with regards to a declaration/property/element + * @param {ASTNode} node The binary expression node to check + * @private + * @returns {void} + */ + function validateComma(node) { + var items = node.declarations || node.properties || node.elements; + + if (items.length > 1) { + items.forEach(function(item, index) { + var tokenBefore = context.getTokenBefore(item), + itemBefore = items[index - 1]; + + if (tokenBefore.value === ",") { + // if single line + if (tokenBefore.loc.end.line === item.loc.start.line && + tokenBefore.loc.end.line === itemBefore.loc.end.line) { + return; + } + // lone comma + else if (tokenBefore.loc.end.line !== item.loc.start.line && + tokenBefore.loc.end.line !== itemBefore.loc.end.line) { + context.report(item, { + line: tokenBefore.loc.end.line, + column: tokenBefore.loc.start.column + }, "Bad line breaking before and after ','."); + } + else if (style === "first" && + tokenBefore.loc.start.line !== item.loc.start.line) { + context.report(item, "',' should be placed first."); + } + else if (style === "last" && + tokenBefore.loc.end.line === item.loc.start.line) { + context.report(item, { + line: itemBefore.loc.end.line, + column: itemBefore.loc.end.column + }, "',' should be placed last."); + } + } + }); + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + "VariableDeclaration": validateComma, + "ObjectExpression": validateComma, + "ArrayExpression": validateComma + }; + +}; + +},{}],18:[function(require,module,exports){ +/** + * @fileoverview Counts the cyclomatic complexity of each function of the script. See http://en.wikipedia.org/wiki/Cyclomatic_complexity. + * Counts the number of if, conditional, for, whilte, try, switch/case, + * @author Patrick Brosset + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + var THRESHOLD = context.options[0]; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + // Using a stack to store complexity (handling nested functions) + var fns = []; + + // When parsing a new function, store it in our function stack + function startFunction() { + fns.push(1); + } + + function endFunction(node) { + var complexity = fns.pop(), name = "anonymous"; + + if (node.id) { + name = node.id.name; + } + if (complexity > THRESHOLD) { + context.report(node, "Function '{{name}}' has a complexity of {{complexity}}.", { name: name, complexity: complexity }); + } + } + + function increaseComplexity() { + if (fns.length) { + fns[fns.length - 1] ++; + } + } + + function increaseSwitchComplexity(node) { + // Avoiding `default` + if (node.test) { + increaseComplexity(node); + } + } + + function increaseLogicalComplexity(node) { + // Avoiding && + if (node.operator === "||") { + increaseComplexity(node); + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + "FunctionDeclaration": startFunction, + "FunctionExpression": startFunction, + "FunctionDeclaration:exit": endFunction, + "FunctionExpression:exit": endFunction, + + "CatchClause": increaseComplexity, + "ConditionalExpression": increaseComplexity, + "LogicalExpression": increaseLogicalComplexity, + "ForStatement": increaseComplexity, + "ForInStatement": increaseComplexity, + "IfStatement": increaseComplexity, + "SwitchCase": increaseSwitchComplexity, + "WhileStatement": increaseComplexity, + "DoWhileStatement": increaseComplexity + }; + +}; + +},{}],19:[function(require,module,exports){ +/** + * @fileoverview Rule to flag consistent return values + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var functions = []; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + function enterFunction() { + functions.push({}); + } + + function exitFunction() { + functions.pop(); + } + + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + "FunctionDeclaration": enterFunction, + "FunctionExpression": enterFunction, + "FunctionDeclaration:exit": exitFunction, + "FunctionExpression:exit": exitFunction, + + "ReturnStatement": function(node) { + + var returnInfo = functions[functions.length - 1], + returnTypeDefined = "type" in returnInfo; + + if (returnTypeDefined) { + + if (returnInfo.type !== !!node.argument) { + context.report(node, "Expected " + (returnInfo.type ? "a" : "no") + " return value."); + } + + } else { + returnInfo.type = !!node.argument; + } + + } + }; + +}; + +},{}],20:[function(require,module,exports){ +/** + * @fileoverview Rule to enforce consistent naming of "this" context variables + * @author Raphael Pigulla + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "VariableDeclaration": function(node) { + var alias = context.options[0]; + + node.declarations.forEach(function(declaration) { + if (declaration.id.name === alias && + !(declaration.init && declaration.init.type === "ThisExpression")) { + + context.report( + node, + "Designated 'this' alias '{{alias}}' is not assigned " + + "to the current execution context.", + { alias: declaration.id.name } + ); + } + + if (declaration.init && + declaration.init.type === "ThisExpression" && + declaration.id.name !== alias) { + + context.report( + node, + "Unexpected alias '{{alias}}' for 'this'.", + { alias: declaration.id.name } + ); + } + }); + } + }; + +}; + +},{}],21:[function(require,module,exports){ +/** + * @fileoverview Rule to flag statements without curly braces + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var multiOnly = (context.options[0] === "multi"); + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Checks the body of a node to see if it's a block statement. Depending on + * the rule options, reports the appropriate problems. + * @param {ASTNode} node The node to report if there's a problem. + * @param {ASTNode} body The body node to check for blocks. + * @param {string} name The name to report if there's a problem. + * @param {string} suffix Additional string to add to the end of a report. + * @returns {void} + */ + function checkBody(node, body, name, suffix) { + var hasBlock = (body.type === "BlockStatement"); + + if (multiOnly) { + if (hasBlock && body.body.length === 1) { + context.report(node, "Unnecessary { after '{{name}}'{{suffix}}.", + { + name: name, + suffix: (suffix ? " " + suffix : "") + } + ); + } + } else { + if (!hasBlock) { + context.report(node, "Expected { after '{{name}}'{{suffix}}.", + { + name: name, + suffix: (suffix ? " " + suffix : "") + } + ); + } + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + "IfStatement": function(node) { + + checkBody(node, node.consequent, "if", "condition"); + + if (node.alternate && node.alternate.type !== "IfStatement") { + checkBody(node, node.alternate, "else"); + } + + }, + + "WhileStatement": function(node) { + checkBody(node, node.body, "while", "condition"); + }, + + "DoWhileStatement": function (node) { + checkBody(node, node.body, "do"); + }, + + "ForStatement": function(node) { + checkBody(node, node.body, "for", "condition"); + } + }; + +}; + +},{}],22:[function(require,module,exports){ +/** + * @fileoverview require default case in switch statements + * @author Aliaksei Shytkin + */ +"use strict"; + +var COMMENT_VALUE = "no default"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Shortcut to get last element of array + * @param {*[]} collection Array + * @returns {*} Last element + */ + function last(collection) { + return collection[collection.length - 1]; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + "SwitchStatement": function(node) { + + if (!node.cases.length) { + // skip check of empty switch because there is no easy way + // to extract comments inside it now + return; + } + + var hasDefault = node.cases.some(function(v) { + return v.test === null; + }); + + if (!hasDefault) { + + var comment; + var comments; + + var lastCase = last(node.cases); + comments = context.getComments(lastCase).trailing; + + if (comments.length) { + comment = last(comments); + } + + if (!comment || comment.value.trim() !== COMMENT_VALUE) { + context.report(node, "Expected a default case."); + } + } + } + }; +}; + +},{}],23:[function(require,module,exports){ +/** + * @fileoverview Rule to warn about using dot notation instead of square bracket notation when possible. + * @author Josh Perez + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +var validIdentifier = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/; +var keywords = [ + "this", + "function", + "if", + "return", + "var", + "else", + "for", + "new", + "arguments", + "in", + "typeof", + "while", + "case", + "break", + "try", + "catch", + "delete", + "throw", + "switch", + "continue", + "default", + "instanceof", + "do", + "void", + "finally", + "with", + "debugger", + "eval", + "implements", + "interface", + "package", + "private", + "protected", + "public", + "static", + "yield", + "let", + "class", + "enum", + "export", + "extends", + "import", + "super", + "true", + "false", + "null", + "abstract", + "boolean", + "byte", + "char", + "const", + "double", + "final", + "float", + "goto", + "int", + "long", + "native", + "short", + "synchronized", + "throws", + "transient", + "volatile" +]; + +function canBeWrittenInDotNotation(node) { + return node.computed === true && + node.property.type === "Literal" && + validIdentifier.test(node.property.value) && + keywords.indexOf("" + node.property.value) === -1; +} + +module.exports = function(context) { + return { + "MemberExpression": function(node) { + if (canBeWrittenInDotNotation(node)) { + context.report(node, "['" + node.property.value + "'] is better written in dot notation."); + } + } + }; +}; + +},{}],24:[function(require,module,exports){ +/** + * @fileoverview Require file to end with single newline. + * @author Nodeca Team + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + "Program": function checkBadEOF(node) { + // Get the whole source code, not for node only. + var src = context.getSource(), location = {column: 1}; + + if (src.length === 0) { + return; + } + + if (src[src.length - 1] !== "\n") { + // file is not newline-terminated + location.line = src.split(/\n/g).length; + context.report(node, location, "Newline required at end of file but not found."); + } else if (/\n\s*\n$/.test(src)) { + // last line is empty + location.line = src.split(/\n/g).length - 1; + context.report(node, location, "Unexpected blank line at end of file."); + } + } + + }; + +}; + +},{}],25:[function(require,module,exports){ +/** + * @fileoverview Rule to flag statements that use != and == instead of !== and === + * @author Nicholas C. Zakas + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + /** + * Checks if either operand of a binary expression is a typeof operation + * @param {ASTNode} node The node to check + * @returns {boolean} if one of the operands is typeof + * @private + */ + function isTypeOf(node) { + return [node.left, node.right].some(function(node) { + return node.type === "UnaryExpression" && node.operator === "typeof"; + }); + } + + /** + * Checks if operands are literals of the same type (via typeof) + * @param {ASTNode} node The node to check + * @returns {boolean} if operands are of same type + * @private + */ + function areLiteralsAndSameType(node) { + return node.left.type === "Literal" && node.right.type === "Literal" && + typeof node.left.value === typeof node.right.value; + } + + /** + * Checks if one of the operands is a literal null + * @param {ASTNode} node The node to check + * @returns {boolean} if operands are null + * @private + */ + function isNullCheck(node) { + return (node.right.type === "Literal" && node.right.value === null) || + (node.left.type === "Literal" && node.left.value === null); + } + + /** + * Gets the location (line and column) of the binary expression's operator + * @param {ASTNode} node The binary expression node to check + * @param {String} operator The operator to find + * @returns {Object} { line, column } location of operator + * @private + */ + function getOperatorLocation(node) { + var opToken = context.getTokens(node)[context.getTokens(node.left).length]; + return {line: opToken.loc.start.line, column: opToken.loc.start.column}; + } + + return { + "BinaryExpression": function(node) { + if (node.operator !== "==" && node.operator !== "!=") { + return; + } + + if (context.options[0] === "smart" && (isTypeOf(node) || + areLiteralsAndSameType(node)) || isNullCheck(node)) { + return; + } + + if (context.options[0] === "allow-null" && isNullCheck(node)) { + return; + } + + context.report( + node, getOperatorLocation(node), + "Expected '{{op}}=' and instead saw '{{op}}'.", + {op: node.operator} + ); + } + }; + +}; + +},{}],26:[function(require,module,exports){ +/** + * @fileoverview Rule to warn when a function expression does not have a name. + * @author Kyle T. Nunery + */ + "use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + return { + "FunctionExpression": function(node) { + + var name = node.id && node.id.name; + + if (!name) { + context.report(node, "Missing function expression name."); + } + } + }; +}; + +},{}],27:[function(require,module,exports){ +/** + * @fileoverview Rule to enforce a particular function style + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var style = context.options[0], + enforceDeclarations = (style === "declaration"); + + return { + + "FunctionDeclaration": function(node) { + if (!enforceDeclarations) { + context.report(node, "Expected a function expression."); + } + }, + + "FunctionExpression": function() { + var parent = context.getAncestors().pop(); + + if (enforceDeclarations && parent.type === "VariableDeclarator") { + context.report(parent, "Expected a function declaration."); + } + } + }; + +}; + +},{}],28:[function(require,module,exports){ +/** + * @fileoverview Rule to flag or require global strict mode. + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var mode = context.options[0]; + + if (mode === "always") { + + return { + "Program": function(node) { + if (node.body.length > 0) { + var statement = node.body[0]; + + if (!(statement.type === "ExpressionStatement" && statement.expression.value === "use strict")) { + context.report(node, "Use the global form of \"use strict\"."); + } + } + } + }; + + } else { // mode = "never" + + return { + "ExpressionStatement": function(node) { + var parent = context.getAncestors().pop(); + + if (node.expression.value === "use strict" && parent.type === "Program") { + context.report(node, "Use the function form of \"use strict\"."); + } + } + }; + + } + +}; + +},{}],29:[function(require,module,exports){ +/** + * @fileoverview Rule to flag for-in loops without if statements inside + * @author Nicholas C. Zakas + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + return { + + "ForInStatement": function(node) { + + /* + * If the for-in statement has {}, then the real body is the body + * of the BlockStatement. Otherwise, just use body as provided. + */ + var body = node.body.type === "BlockStatement" ? node.body.body[0] : node.body; + + if (body && body.type !== "IfStatement") { + context.report(node, "The body of a for-in should be wrapped in an if statement to filter unwanted properties from the prototype."); + } + } + }; + +}; + +},{}],30:[function(require,module,exports){ +/** + * @fileoverview Ensure handling of errors when we know they exist. + * @author Jamund Ferguson + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + var errorArgument = context.options[0] || "err"; + var callbacks = []; + var scopes = 0; + + /** + * Checks if the given argument should be interpreted as a regexp pattern. + * @param {string} stringToCheck The string which should be checked. + * @returns {boolean} Whether or not the string should be interpreted as a pattern. + */ + function isPattern(stringToCheck) { + var firstChar = stringToCheck[0]; + return firstChar === "^"; + } + + /** + * Checks if the given name matches the configured error argument. + * @param {string} name The name which should be compared. + * @returns {boolean} Whether or not the given name matches the configured error variable name. + */ + function matchesConfiguredErrorName(name) { + if (isPattern(errorArgument)) { + var regexp = new RegExp(errorArgument); + return regexp.test(name); + } + return name === errorArgument; + } + + /** + * Check the arguments to see if we need to start tracking the error object. + * @param {ASTNode} node The AST node to check. + * @returns {void} + */ + function startFunction(node) { + + // keep track of nested scopes + scopes++; + + // check if the first argument matches our argument name + var firstArg = node.params && node.params[0]; + if (firstArg && matchesConfiguredErrorName(firstArg.name)) { + callbacks.push({handled: false, depth: scopes, errorVariableName: firstArg.name}); + } + } + + /** + * At the end of a function check to see if the error was handled. + * @param {ASTNode} node The AST node to check. + * @returns {void} + */ + function endFunction(node) { + + var callback = callbacks[callbacks.length - 1] || {}; + + // check if a callback is ending, if so pop it off the stack + if (callback.depth === scopes) { + callbacks.pop(); + + // check if there were no handled errors since the last callback + if (!callback.handled) { + context.report(node, "Expected error to be handled."); + } + } + + // less nested functions + scopes--; + + } + + /** + * Check to see if we're handling the error object properly. + * @param {ASTNode} node The AST node to check. + * @returns {void} + */ + function checkForError(node) { + if (callbacks.length > 0) { + var callback = callbacks[callbacks.length - 1] || {}; + + // make sure the node's name matches our error argument name + var isAboutError = node.name === callback.errorVariableName; + + // we don't consider these use cases as "handling" the error + var doNotCount = ["FunctionDeclaration", "FunctionExpression", "CatchClause"]; + + // make sure this identifier isn't used as part of one of them + var isHandled = doNotCount.indexOf(node.parent.type) === -1; + + if (isAboutError && isHandled) { + // record that this callback handled its error + callback.handled = true; + } + } + } + + return { + "FunctionDeclaration": startFunction, + "FunctionExpression": startFunction, + "Identifier": checkForError, + "FunctionDeclaration:exit": endFunction, + "FunctionExpression:exit": endFunction + }; + +}; + +},{}],31:[function(require,module,exports){ +/** + * @fileoverview Rule to specify spacing of object literal keys and values + * @author Brandon Mills + * @copyright 2014 Brandon Mills. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Gets an object literal property's key as the identifier name or string value. + * @param {ASTNode} property Property node whose key to retrieve. + * @returns {string} The property's key. + */ +function getKey(property) { + return property.key.name || property.key.value; +} + +/** + * Gets the number of characters in a key, including quotes around string keys. + * @param {ASTNode} property Property of on object literal. + * @returns {int} Width of the key, including string quotes where present. + */ +function getKeyWidth(property) { + var key = property.key; + return (key.type === "Identifier" ? key.name : key.raw).length; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +var messages = { + key: "{{error}} space after key \"{{key}}\".", + value: "{{error}} space before value for key \"{{key}}\"." +}; + +module.exports = function(context) { + + /** + * OPTIONS + * "key-spacing": [2, { + * beforeColon: false, + * afterColon: true, + * align: "colon" // Optional, or "value" + * } + */ + + var options = context.options[0] || {}, + align = options.align, + beforeColon = +!!options.beforeColon, // Defaults to false + afterColon = +!(options.afterColon === false); // Defaults to true + + /** + * Gets the spacing around the colon in an object literal property + * @param {ASTNode} property Property node from an object literal + * @returns {Object} Spacing before and after the property's colon + */ + function getPropertySpacing(property) { + var whitespace = /^(\s*):(\s*)/.exec(context.getSource().slice( + property.key.range[1], property.value.range[0] + )); + + if (whitespace) { + return { + beforeColon: whitespace[1].length, + afterColon: whitespace[2].length + }; + } + } + + /** + * Reports an appropriately-formatted error if spacing is incorrect on one + * side of the colon. + * @param {ASTNode} property Key-value pair in an object literal. + * @param {string} side Side being verified - either "key" or "value". + * @param {int} diff Difference between actual and expected spacing. + * @returns {void} + */ + function report(property, side, diff) { + if (diff) { + context.report(property[side], messages[side], { + error: diff > 0 ? "Extra" : "Missing", + key: getKey(property) + }); + } + } + + if (align) { // Verify vertical alignment + + return { + "ObjectExpression": function(node) { + var properties = node.properties, + length = properties.length, + widths = properties.map(getKeyWidth), // Width of keys, including quotes + targetWidth = Math.max.apply(null, widths), + i, property, spacing, width; + + // Conditionally include one space before or after colon + targetWidth += (align === "colon" ? beforeColon : afterColon); + + for (i = 0; i < length; i++) { + property = properties[i]; + spacing = getPropertySpacing(property); + + if (!spacing) { + continue; // Object literal getters/setters lack a colon + } + + width = widths[i]; + + if (align === "value") { + report(property, "key", spacing.beforeColon - beforeColon); + report(property, "value", (width + spacing.afterColon) - targetWidth); + } else { // align = "colon" + report(property, "key", (width + spacing.beforeColon) - targetWidth); + report(property, "value", spacing.afterColon - afterColon); + } + } + } + }; + + } else { // Strictly obey beforeColon and afterColon in each property + + return { + "Property": function (node) { + var spacing = getPropertySpacing(node); + if (spacing) { // Object literal getters/setters lack colon spacing + report(node, "key", spacing.beforeColon - beforeColon); + report(node, "value", spacing.afterColon - afterColon); + } + } + }; + + } + +}; + +},{}],32:[function(require,module,exports){ +/** + * @fileoverview A rule to set the maximum depth block can be nested in a function. + * @author Ian Christian Myers + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + var functionStack = [], + maxDepth = context.options[0] || 4; + + function startFunction() { + functionStack.push(0); + } + + function endFunction() { + functionStack.pop(); + } + + function pushBlock(node) { + var len = ++functionStack[functionStack.length - 1]; + + if (len > maxDepth) { + context.report(node, "Blocks are nested too deeply ({{depth}}).", + { depth: len }); + } + } + + function popBlock() { + functionStack[functionStack.length - 1]--; + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + "Program": startFunction, + "FunctionDeclaration": startFunction, + "FunctionExpression": startFunction, + + "IfStatement": pushBlock, + "SwitchStatement": pushBlock, + "TryStatement": pushBlock, + "DoWhileStatement": pushBlock, + "WhileStatement": pushBlock, + "WithStatement": pushBlock, + "ForStatement": pushBlock, + "ForInStatement": pushBlock, + + "IfStatement:exit": popBlock, + "SwitchStatement:exit": popBlock, + "TryStatement:exit": popBlock, + "DoWhileStatement:exit": popBlock, + "WhileStatement:exit": popBlock, + "WithStatement:exit": popBlock, + "ForStatement:exit": popBlock, + "ForInStatement:exit": popBlock, + + "FunctionDeclaration:exit": endFunction, + "FunctionExpression:exit": endFunction, + "Program:exit": endFunction + }; + +}; + +},{}],33:[function(require,module,exports){ +/** + * @fileoverview Rule to check for max length on a line. + * @author Matt DuVall + * @copyright 2013 Matt DuVall. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + /** + * Creates a string that is made up of repeating a given string a certain + * number of times. This uses exponentiation of squares to achieve significant + * performance gains over the more traditional implementation of such + * functionality. + * @param {string} str The string to repeat. + * @param {int} num The number of times to repeat the string. + * @returns {string} The created string. + * @private + */ + function stringRepeat(str, num) { + var result = ""; + for (num |= 0; num > 0; num >>>= 1, str += str) { + if (num & 1) { + result += str; + } + } + return result; + } + + var tabWidth = context.options[1]; + + var maxLength = context.options[0], + tabString = stringRepeat(" ", tabWidth); + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + function checkProgramForMaxLength(node) { + var lines = context.getSourceLines(); + + // Replace the tabs + // Split (honors line-ending) + // Iterate + lines.forEach(function(line, i) { + if (line.replace(/\t/g, tabString).length > maxLength) { + context.report(node, { line: i + 1, col: 1 }, "Line " + (i + 1) + " exceeds the maximum line length of " + maxLength + "."); + } + }); + } + + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + "Program": checkProgramForMaxLength + }; + +}; + +},{}],34:[function(require,module,exports){ +/** + * @fileoverview Rule to enforce a maximum number of nested callbacks. + * @author Ian Christian Myers + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + //-------------------------------------------------------------------------- + // Constants + //-------------------------------------------------------------------------- + + var THRESHOLD = context.options[0]; + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + var callbackStack = []; + + return { + + "FunctionExpression": function (node) { + var parent = context.getAncestors().pop(); + + if (parent.type === "CallExpression") { + callbackStack.push(node); + } + + if (callbackStack.length > THRESHOLD) { + var opts = {num: callbackStack.length, max: THRESHOLD}; + context.report(node, "Too many nested callbacks ({{num}}). Maximum allowed is {{max}}.", opts); + } + }, + + + "FunctionExpression:exit": function() { + callbackStack.pop(); + } + + }; + +}; + +},{}],35:[function(require,module,exports){ +/** + * @fileoverview Rule to flag when a function has too many parameters + * @author Ilya Volodin + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + var numParams = context.options[0] || 3; + + return { + + "FunctionDeclaration": function(node) { + if (node.params.length > numParams) { + context.report(node, "This function has too many parameters ({{count}}). Maximum allowed is {{max}}.", { + count: node.params.length, + max: numParams + }); + } + }, + + "FunctionExpression": function(node) { + if (node.params.length > numParams) { + context.report(node, "This function has too many parameters ({{count}}). Maximum allowed is {{max}}.", { + count: node.params.length, + max: numParams + }); + } + } + }; + +}; + +},{}],36:[function(require,module,exports){ +/** + * @fileoverview A rule to set the maximum number of statements in a function. + * @author Ian Christian Myers + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + var functionStack = [], + maxStatements = context.options[0] || 10; + + function startFunction() { + functionStack.push(0); + } + + function endFunction(node) { + var count = functionStack.pop(); + + if (count > maxStatements) { + context.report(node, "This function has too many statements ({{count}}). Maximum allowed is {{max}}.", + { count: count, max: maxStatements }); + } + } + + function countStatements(node) { + functionStack[functionStack.length - 1] += node.body.length; + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + "FunctionDeclaration": startFunction, + "FunctionExpression": startFunction, + + "BlockStatement": countStatements, + + "FunctionDeclaration:exit": endFunction, + "FunctionExpression:exit": endFunction + }; + +}; + +},{}],37:[function(require,module,exports){ +/** + * @fileoverview Rule to flag use of constructors without capital letters + * @author Nicholas C. Zakas + * @copyright 2013-2014 Nicholas C. Zakas. All rights reserved. + */ + +"use strict"; + +var CAPS_ALLOWED = [ + "Number", + "String", + "Boolean", + "Date", + "Array", + "Symbol", + "RegExp" +]; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var config = context.options[0] || {}; + config.newIsCap = config.newIsCap === false ? false : true; + config.capIsNew = config.capIsNew === false ? false : true; + + var listeners = {}; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Get exact callee name from expression + * @param {ASTNode} node CallExpression or NewExpression node + * @returns {String} name + */ + function extractNameFromExpression(node) { + + var name = "", + property; + + if (node.callee.type === "MemberExpression") { + property = node.callee.property; + + if (property.type === "Literal" && (typeof property.value === "string")) { + name = property.value; + } else if (property.type === "Identifier" && !node.callee.computed) { + name = property.name; + } + } else { + name = node.callee.name; + } + return name; + } + + /** + * Returns the capitalization state of the string - + * Whether the first character is uppercase, lowercase, or non-alphabetic + * @param {String} str String + * @returns {String} capitalization state: "non-alpha", "lower", or "upper" + */ + function getCap(str) { + var firstChar = str.charAt(0); + + var firstCharLower = firstChar.toLowerCase(); + var firstCharUpper = firstChar.toUpperCase(); + + if (firstCharLower === firstCharUpper) { + // char has no uppercase variant, so it's non-alphabetic + return "non-alpha"; + } else if (firstChar === firstCharLower) { + return "lower"; + } else { + return "upper"; + } + } + + /** + * Check if capitalization is allowed for a CallExpression + * @param {ASTNode} node CallExpression node + * @param {String} calleeName Capitalized callee name from a CallExpression + * @returns {Boolean} Returns true if the callee may be capitalized + */ + function isCapAllowed(node, calleeName) { + if (CAPS_ALLOWED.indexOf(calleeName) >= 0) { + return true; + } + if (calleeName === "UTC" && node.callee.type === "MemberExpression") { + // allow if callee is Date.UTC + return node.callee.object.type === "Identifier" && + node.callee.object.name === "Date"; + } + return false; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + if (config.newIsCap) { + listeners.NewExpression = function(node) { + + var constructorName = extractNameFromExpression(node); + if (constructorName && getCap(constructorName) === "lower") { + context.report(node, "A constructor name should not start with a lowercase letter."); + } + }; + } + + if (config.capIsNew) { + listeners.CallExpression = function(node) { + + var calleeName = extractNameFromExpression(node); + if (calleeName && getCap(calleeName) === "upper" && !isCapAllowed(node, calleeName)) { + context.report(node, "A function with a name starting with an uppercase letter should only be used as a constructor."); + } + }; + } + + return listeners; +}; + +},{}],38:[function(require,module,exports){ +/** + * @fileoverview Rule to flag when using constructor without parentheses + * @author Ilya Volodin + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + return { + + "NewExpression": function(node) { + var tokens = context.getTokens(node); + var prenticesTokens = tokens.filter(function(token) { + return token.value === "(" || token.value === ")"; + }); + if (prenticesTokens.length < 2) { + context.report(node, "Missing '()' invoking a constructor"); + } + } + }; + +}; + +},{}],39:[function(require,module,exports){ +/** + * @fileoverview Rule to flag use of alert, confirm, prompt + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +function matchProhibited(name) { + return name.match(/^(alert|confirm|prompt)$/); +} + +function report(context, node, result) { + context.report(node, "Unexpected {{name}}.", { name: result[1] }); +} + + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "CallExpression": function(node) { + + var result; + + // without window. + if (node.callee.type === "Identifier") { + + result = matchProhibited(node.callee.name); + + if (result) { + report(context, node, result); + } + + } else if (node.callee.type === "MemberExpression" && node.callee.property.type === "Identifier") { + + result = matchProhibited(node.callee.property.name); + + if (result && node.callee.object.name === "window") { + report(context, node, result); + } + + } + + } + }; + +}; + +},{}],40:[function(require,module,exports){ +/** + * @fileoverview Disallow construction of dense arrays using the Array constructor + * @author Matt DuVall + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + function check(node) { + if ( + node.arguments.length !== 1 && + node.callee.type === "Identifier" && + node.callee.name === "Array" + ) { + context.report(node, "The array literal notation [] is preferrable."); + } + } + + return { + "CallExpression": check, + "NewExpression": check + }; + +}; + +},{}],41:[function(require,module,exports){ +/** + * @fileoverview Rule to flag bitwise identifiers + * @author Nicholas C. Zakas + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + function report(node) { + context.report(node, "Unexpected use of '{{operator}}'.", { operator: node.operator }); + } + + return { + "BinaryExpression": function(node) { + + // warn for ^ | & ~ << >> >>> + if (node.operator.match(/^(?:[\^&\|~]|<<|>>>?)$/)) { + report(node); + } + + }, + + "UnaryExpression": function(node) { + + // warn for ~ + if (node.operator === "~") { + report(node); + } + + } + }; + +}; + +},{}],42:[function(require,module,exports){ +/** + * @fileoverview Rule to flag use of arguments.callee and arguments.caller. + * @author Nicholas C. Zakas + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + return { + + "MemberExpression": function(node) { + var objectName = node.object.name, + propertyName = node.property.name; + + if (objectName === "arguments" && !node.computed && propertyName && propertyName.match(/^calle[er]$/)) { + context.report(node, "Avoid arguments.{{property}}.", { property: propertyName }); + } + + } + }; + +}; + +},{}],43:[function(require,module,exports){ +/** + * @fileoverview Rule to flag variable leak in CatchClauses in IE 8 and earlier + * @author Ian Christian Myers + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + function paramIsShadowing(scope, name) { + var found = scope.variables.some(function(variable) { + return variable.name === name; + }); + + if (found) { + return true; + } + + if (scope.upper) { + return paramIsShadowing(scope.upper, name); + } + + return false; + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + + "CatchClause": function(node) { + var scope = context.getScope(); + + if (paramIsShadowing(scope, node.param.name)) { + context.report(node, "Value of '{{name}}' may be overwritten in IE 8 and earlier.", + { name: node.param.name }); + } + } + }; + +}; + +},{}],44:[function(require,module,exports){ +/** + * @fileoverview Rule to flag trailing commas in object literals. + * @author Ian Christian Myers + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + //------------------------------------------------------------------------- + // Helpers + //------------------------------------------------------------------------- + + function checkForTrailingComma(node) { + var secondToLastToken = context.getLastTokens(node, 2)[0]; + + var items = node.properties || node.elements, + lastItem = items[items.length - 1]; + // The last token in an object/array literal will always be a closing + // curly, so we check the second to last token for a comma. + if (secondToLastToken.value === "," && items.length && lastItem) { + context.report(lastItem, secondToLastToken.loc.start, "Trailing comma."); + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + "ObjectExpression": checkForTrailingComma, + "ArrayExpression": checkForTrailingComma + }; + +}; + +},{}],45:[function(require,module,exports){ +/** + * @fileoverview Rule to flag assignment in a conditional expression + * @author Stephen Murray + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + function isParenthesised(node) { + var previousToken = context.getTokenBefore(node), + nextToken = context.getTokenAfter(node); + + return previousToken.value === "(" && previousToken.range[1] <= node.range[0] && + nextToken.value === ")" && nextToken.range[0] >= node.range[1]; + } + + function isParenthesisedTwice(node) { + var previousToken = context.getTokenBefore(node, 1), + nextToken = context.getTokenAfter(node, 1); + + return isParenthesised(node) && + previousToken.value === "(" && previousToken.range[1] <= node.range[0] && + nextToken.value === ")" && nextToken.range[0] >= node.range[1]; + } + + function testForAssign(node) { + if (node.test && (node.test.type === "AssignmentExpression") && !isParenthesisedTwice(node.test)) { + context.report(node, "Expected a conditional expression and instead saw an assignment."); + } + } + + return { + "IfStatement": testForAssign, + "WhileStatement": testForAssign, + "DoWhileStatement": testForAssign, + "ForStatement": testForAssign + }; + +}; + +},{}],46:[function(require,module,exports){ +/** + * @fileoverview Rule to flag use of console object + * @author Nicholas C. Zakas + */ + + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + return { + + "MemberExpression": function(node) { + + if (node.object.name === "console") { + context.report(node, "Unexpected console statement."); + } + + } + }; + +}; + +},{}],47:[function(require,module,exports){ +/** + * @fileoverview Rule to flag use constant conditions + * @author Christian Schulz + */ + + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Checks if a node has a constant truthiness value. + * @param {ASTNode} node The AST node to check. + * @returns {Bool} true when node's truthiness is constant + * @private + */ + function isConstant(node) { + switch (node.type) { + case "Literal": + case "FunctionExpression": + case "ObjectExpression": + case "ArrayExpression": + return true; + case "UnaryExpression": + return isConstant(node.argument); + case "BinaryExpression": + case "LogicalExpression": + return isConstant(node.left) && isConstant(node.right); + case "AssignmentExpression": + return isConstant(node.right); + case "SequenceExpression": + return isConstant(node.expressions[node.expressions.length - 1]); + // no default + } + return false; + } + + /** + * Reports when the given node contains a constant condition. + * @param {ASTNode} node The AST node to check. + * @returns {void} + * @private + */ + function checkConstantCondition(node) { + if (node.test && isConstant(node.test)) { + context.report(node, "Unexpected constant condition."); + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + "ConditionalExpression": checkConstantCondition, + "IfStatement": checkConstantCondition, + "WhileStatement": checkConstantCondition, + "DoWhileStatement": checkConstantCondition, + "ForStatement": checkConstantCondition + }; + +}; + +},{}],48:[function(require,module,exports){ +/** + * @fileoverview Rule to forbid control charactes from regular expressions. + * @author Nicholas C. Zakas + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + + function getRegExp(node) { + + if (node.value instanceof RegExp) { + return node.value; + } else if (typeof node.value === "string") { + + var parent = context.getAncestors().pop(); + if ((parent.type === "NewExpression" || parent.type === "CallExpression") && + parent.callee.type === "Identifier" && parent.callee.name === "RegExp") { + + // there could be an invalid regular expression string + try { + return new RegExp(node.value); + } catch (ex) { + return null; + } + + } + } else { + return null; + } + + } + + + + return { + + "Literal": function(node) { + + var computedValue, + regex = getRegExp(node); + + if (regex) { + computedValue = regex.toString(); + if (/[\x00-\x1f]/.test(computedValue)) { + context.report(node, "Unexpected control character in regular expression."); + } + } + } + }; + +}; + +},{}],49:[function(require,module,exports){ +/** + * @fileoverview Rule to flag use of a debugger statement + * @author Nicholas C. Zakas + */ + + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + return { + "DebuggerStatement": function(node) { + context.report(node, "Unexpected 'debugger' statement."); + } + }; + +}; + +},{}],50:[function(require,module,exports){ +/** + * @fileoverview Rule to flag when deleting variables + * @author Ilya Volodin + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + return { + + "UnaryExpression": function(node) { + if (node.operator === "delete" && node.argument.type === "Identifier") { + context.report(node, "Variables should not be deleted."); + } + } + }; + +}; + +},{}],51:[function(require,module,exports){ +/** + * @fileoverview Rule to check for ambiguous div operator in regexes + * @author Matt DuVall + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + return { + + "Literal": function(node) { + var token = context.getFirstTokens(node, 1)[0], + nodeType = token.type, + source; + + if (nodeType === "RegularExpression") { + source = context.getFirstTokens(node, 1)[0].value; + + if (source[1] === "=") { + context.report(node, "A regular expression literal can be confused with '/='."); + } + } + } + }; + +}; + +},{}],52:[function(require,module,exports){ +/** + * @fileoverview Rule to flag use of duplicate keys in an object. + * @author Ian Christian Myers + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + return { + + "ObjectExpression": function(node) { + + // Object that will be a map of properties--safe because we will + // prefix all of the keys. + var nodeProps = {}; + + node.properties.forEach(function(property) { + var keyName = property.key.name || property.key.value; + var key = property.kind + "-" + keyName; + + if (nodeProps[key]) { + context.report(node, "Duplicate key '{{key}}'.", { key: keyName }); + } else { + nodeProps[key] = true; + } + }); + + } + }; + +}; + +},{}],53:[function(require,module,exports){ +/** + * @fileoverview Rule to flag `else` after a `return` in `if` + * @author Ian Christian Myers + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + function checkForReturnStatement(node, alternate) { + if (node.type === "ReturnStatement") { + context.report(alternate, "Unexpected 'else' after 'return'."); + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + + "IfStatement": function(node) { + + // Don't bother finding a ReturnStatement, if there's no `else` + // or if the alternate is also an if (indicating an else if). + if (node.alternate && node.consequent && node.alternate.type !== "IfStatement") { + + // If we have a BlockStatement, check each consequent body node. + if (node.consequent.type === "BlockStatement") { + node.consequent.body.forEach(function (bodyNode) { + checkForReturnStatement(bodyNode, node.alternate); + }); + + // If not a block statement, make sure the consequent isn't a + // ReturnStatement + } else { + checkForReturnStatement(node.consequent, node.alternate); + } + } + } + + }; + +}; + +},{}],54:[function(require,module,exports){ +/** + * @fileoverview Rule to flag the use of empty character classes in regular expressions + * @author Ian Christian Myers + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + return { + + "Literal": function(node) { + var tokens = context.getTokens(node); + tokens.forEach(function (token) { + /* + plain-English description of the following regexp: + 0. `^` fix the match at the beginning of the string + 1. `\/`: the `/` that begins the regexp + 2. `([^\\[]|\\.|\[([^\\\]]|\\.)+\])*`: regexp contents; 0 or more of the following + 2.0. `[^\\[]`: any character that's not a `\` or a `[` (anything but escape sequences and character classes) + 2.1. `\\.`: an escape sequence + 2.2. `\[([^\\\]]|\\.)+\]`: a character class that isn't empty + 3. `\/` the `/` that ends the regexp + 4. `[gimy]*`: optional regexp flags + 5. `$`: fix the match at the end of the string + */ + if (token.type === "RegularExpression" && + !/^\/([^\\[]|\\.|\[([^\\\]]|\\.)+\])*\/[gimy]*$/.test(token.value)) { + context.report(node, "Empty class."); + } + }); + } + + }; + +}; + +},{}],55:[function(require,module,exports){ +/** + * @fileoverview Rule to flag when label is not used for a loop or switch + * @author Ilya Volodin + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + return { + + "LabeledStatement": function(node) { + if (node.body.type !== "ForStatement" && node.body.type !== "WhileStatement" && node.body.type !== "DoWhileStatement" && node.body.type !== "SwitchStatement" && node.body.type !== "ForInStatement") { + context.report(node, "Unexpected label {{l}}", {l: node.label.name}); + } + } + }; + +}; + +},{}],56:[function(require,module,exports){ +/** + * @fileoverview Rule to flag use of an empty block statement + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "BlockStatement": function(node) { + var ancestors = context.getAncestors(), + parent = ancestors[ancestors.length - 1], + parentType = parent.type, + isFinallyBlock = (parentType === "TryStatement") && (parent.finalizer === node); + + if (/FunctionExpression|FunctionDeclaration|CatchClause/.test(parentType) || + (isFinallyBlock && !parent.handlers.length)) { + return; + } + + if (node.body.length === 0) { + context.report(node, "Empty block statement."); + } + }, + + "SwitchStatement": function(node) { + + if (typeof node.cases === "undefined" || node.cases.length === 0) { + context.report(node, "Empty switch statement."); + } + } + }; + +}; + +},{}],57:[function(require,module,exports){ +/** + * @fileoverview Rule to flag comparisons to null without a type-checking + * operator. + * @author Ian Christian Myers + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + "use strict"; + + return { + + "BinaryExpression": function(node) { + var badOperator = node.operator === "==" || node.operator === "!="; + + if (node.right.type === "Literal" && node.right.raw === "null" && badOperator || + node.left.type === "Literal" && node.left.raw === "null" && badOperator) { + context.report(node, "Use ‘===’ to compare with ‘null’."); + } + } + }; + +}; + +},{}],58:[function(require,module,exports){ +/** + * @fileoverview Rule to flag use of eval() statement + * @author Nicholas C. Zakas + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + var IMPLIED_EVAL = /set(?:Timeout|Interval)/; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Determines if a node represents a call to setTimeout/setInterval with + * a string argument. + * @param {ASTNode} node The node to check. + * @returns {boolean} True if the node matches, false if not. + * @private + */ + function isImpliedEval(node) { + + var isMemberExpression = (node.callee.type === "MemberExpression"), + isIdentifier = (node.callee.type === "Identifier"), + isSetMethod = (isIdentifier && IMPLIED_EVAL.test(node.callee.name)) || + (isMemberExpression && node.callee.object.name === "window" && + IMPLIED_EVAL.test(node.callee.property.name)), + hasStringArgument = node.arguments.length && (typeof node.arguments[0].value === "string"); + + return isSetMethod && hasStringArgument; + } + + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + "CallExpression": function(node) { + if (node.callee.name === "eval") { + context.report(node, "eval can be harmful."); + } else if (isImpliedEval(node)) { + if (node.arguments.length && (typeof node.arguments[0].value === "string")) { + context.report(node, "Implied eval can be harmful. Pass a function instead of a string."); + } + } + } + }; + +}; + +},{}],59:[function(require,module,exports){ +/** + * @fileoverview Rule to flag assignment of the exception parameter + * @author Stephen Murray + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + var inCatch = false, + exceptionName = null; + + return { + + "CatchClause": function(node) { + inCatch = true; + exceptionName = node.param.name; + }, + + "CatchClause:exit": function() { + inCatch = false; + exceptionName = null; + }, + + "AssignmentExpression": function(node) { + + if (inCatch) { + + if (node.left.name === exceptionName) { + context.report(node, "Do not assign to the exception parameter."); + } + } + } + + }; + +}; + +},{}],60:[function(require,module,exports){ +/** + * @fileoverview Rule to flag adding properties to native object's prototypes. + * @author David Nelson + */ + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +var BUILTINS = [ + "Object", "Function", "Array", "String", "Boolean", "Number", "Date", + "RegExp", "Error", "EvalError", "RangeError", "ReferenceError", + "SyntaxError", "TypeError", "URIError" +]; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + return { + + // handle the Array.prototype.extra style case + "AssignmentExpression": function(node) { + var lhs = node.left, affectsProto; + + if (lhs.type !== "MemberExpression" || lhs.object.type !== "MemberExpression") { + return; + } + + affectsProto = lhs.object.computed ? + lhs.object.property.type === "Literal" && lhs.object.property.value === "prototype" : + lhs.object.property.name === "prototype"; + + if (!affectsProto) { + return; + } + + BUILTINS.forEach(function(builtin) { + if (lhs.object.object.name === builtin) { + context.report(node, builtin + " prototype is read only, properties should not be added."); + } + }); + }, + + // handle the Object.defineProperty(Array.prototype) case + "CallExpression": function(node) { + + var callee = node.callee, + subject, + object; + + // only worry about Object.defineProperty + if (callee.type === "MemberExpression" && + callee.object.name === "Object" && + callee.property.name === "defineProperty") { + + // verify the object being added to is a native prototype + subject = node.arguments[0]; + object = subject.object; + + if (object && + object.type === "Identifier" && + (BUILTINS.indexOf(object.name) > -1) && + subject.property.name === "prototype") { + + context.report(node, object.name + " prototype is read only, properties should not be added."); + } + } + + } + }; + +}; + +},{}],61:[function(require,module,exports){ +/** + * @fileoverview Rule to flag unnecessary bind calls + * @author Bence Dányi + * @copyright 2014 Bence Dányi. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var scope = [{ + depth: -1, + found: 0 + }]; + + /** + * Get the topmost scope + * @returns {Object} The topmost scope + */ + function getTopScope() { + return scope[scope.length - 1]; + } + + /** + * Increment the depth of the top scope + * @returns {void} + */ + function incrementScopeDepth() { + var top = getTopScope(); + top.depth++; + } + + /** + * Decrement the depth of the top scope + * @returns {void} + */ + function decrementScopeDepth() { + var top = getTopScope(); + top.depth--; + } + + return { + "CallExpression": function(node) { + if (node.arguments.length === 1 && + node.callee.type === "MemberExpression" && + node.callee.property.name === "bind" && + node.callee.object.type === "FunctionExpression") { + scope.push({ + call: node, + depth: -1, + found: 0 + }); + } + }, + "CallExpression:exit": function(node) { + var top = getTopScope(); + if (top.call === node && top.found === 0) { + context.report(node, "The function binding is unnecessary."); + scope.pop(); + } + }, + "FunctionExpression": incrementScopeDepth, + "FunctionExpression:exit": decrementScopeDepth, + "FunctionDeclaration": incrementScopeDepth, + "FunctionDeclaration:exit": decrementScopeDepth, + "ThisExpression": function() { + var top = getTopScope(); + if (top.depth === 0) { + top.found++; + } + } + }; + +}; + +},{}],62:[function(require,module,exports){ +/** + * @fileoverview Rule to flag unnecessary double negation in Boolean contexts + * @author Brandon Mills + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + return { + "UnaryExpression": function (node) { + var ancestors = context.getAncestors(), + parent = ancestors.pop(), + grandparent = ancestors.pop(); + + // Exit early if it's guaranteed not to match + if (node.operator !== "!" || + parent.type !== "UnaryExpression" || + parent.operator !== "!") { + return; + } + + // if () ... + if (grandparent.type === "IfStatement") { + context.report(node, "Redundant double negation in an if statement condition."); + + // do ... while () + } else if (grandparent.type === "DoWhileStatement") { + context.report(node, "Redundant double negation in a do while loop condition."); + + // while () ... + } else if (grandparent.type === "WhileStatement") { + context.report(node, "Redundant double negation in a while loop condition."); + + // ? ... : ... + } else if ((grandparent.type === "ConditionalExpression" && + parent === grandparent.test)) { + context.report(node, "Redundant double negation in a ternary condition."); + + // for (...; ; ...) ... + } else if ((grandparent.type === "ForStatement" && + parent === grandparent.test)) { + context.report(node, "Redundant double negation in a for loop condition."); + + // ! + } else if ((grandparent.type === "UnaryExpression" && + grandparent.operator === "!")) { + context.report(node, "Redundant multiple negation."); + + // Boolean() + } else if ((grandparent.type === "CallExpression" && + grandparent.callee.type === "Identifier" && + grandparent.callee.name === "Boolean")) { + context.report(node, "Redundant double negation in call to Boolean()."); + + // new Boolean() + } else if ((grandparent.type === "NewExpression" && + grandparent.callee.type === "Identifier" && + grandparent.callee.name === "Boolean")) { + context.report(node, "Redundant double negation in Boolean constructor call."); + } + } + }; + +}; + +},{}],63:[function(require,module,exports){ +/** + * @fileoverview Disallow parenthesesisng higher precedence subexpressions. + * @author Michael Ficarra + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + function isParenthesised(node) { + var previousToken = context.getTokenBefore(node), + nextToken = context.getTokenAfter(node); + + return previousToken && nextToken && + previousToken.value === "(" && previousToken.range[1] <= node.range[0] && + nextToken.value === ")" && nextToken.range[0] >= node.range[1]; + } + + function isParenthesisedTwice(node) { + var previousToken = context.getTokenBefore(node, 1), + nextToken = context.getTokenAfter(node, 1); + + return isParenthesised(node) && previousToken && nextToken && + previousToken.value === "(" && previousToken.range[1] <= node.range[0] && + nextToken.value === ")" && nextToken.range[0] >= node.range[1]; + } + + function precedence(node) { + + switch (node.type) { + case "SequenceExpression": + return 0; + + case "AssignmentExpression": + return 1; + + case "ConditionalExpression": + return 3; + + case "LogicalExpression": + switch (node.operator) { + case "||": + return 4; + case "&&": + return 5; + // no default + } + + /* falls through */ + case "BinaryExpression": + switch (node.operator) { + case "|": + return 6; + case "^": + return 7; + case "&": + return 8; + case "==": + case "!=": + case "===": + case "!==": + return 9; + case "<": + case "<=": + case ">": + case ">=": + case "in": + case "instanceof": + return 10; + case "<<": + case ">>": + case ">>>": + return 11; + case "+": + case "-": + return 12; + case "*": + case "/": + case "%": + return 13; + // no default + } + /* falls through */ + case "UnaryExpression": + return 14; + case "UpdateExpression": + return 15; + case "CallExpression": + // IIFE is allowed to have parens in any position (#655) + if (node.callee.type === "FunctionExpression") { + return -1; + } + return 16; + case "NewExpression": + return 17; + // no default + } + return 18; + } + + function report(node) { + context.report(node, "Gratuitous parentheses around expression."); + } + + function dryUnaryUpdate(node) { + if (isParenthesised(node.argument) && precedence(node.argument) >= precedence(node)) { + report(node.argument); + } + } + + function dryCallNew(node) { + if (isParenthesised(node.callee) && precedence(node.callee) >= precedence(node) && + !(node.type === "CallExpression" && node.callee.type === "FunctionExpression")) { + report(node.callee); + } + if (node.arguments.length === 1) { + if (isParenthesisedTwice(node.arguments[0]) && precedence(node.arguments[0]) >= precedence({type: "AssignmentExpression"})) { + report(node.arguments[0]); + } + } else { + [].forEach.call(node.arguments, function(arg) { + if (isParenthesised(arg) && precedence(arg) >= precedence({type: "AssignmentExpression"})) { + report(arg); + } + }); + } + } + + function dryBinaryLogical(node) { + var prec = precedence(node); + if (isParenthesised(node.left) && precedence(node.left) >= prec) { + report(node.left); + } + if (isParenthesised(node.right) && precedence(node.right) > prec) { + report(node.right); + } + } + + return { + "ArrayExpression": function(node) { + [].forEach.call(node.elements, function(e) { + if (e && isParenthesised(e) && precedence(e) >= precedence({type: "AssignmentExpression"})) { + report(e); + } + }); + }, + "AssignmentExpression": function(node) { + if (isParenthesised(node.right) && precedence(node.right) >= precedence(node)) { + report(node.right); + } + }, + "BinaryExpression": dryBinaryLogical, + "CallExpression": dryCallNew, + "ConditionalExpression": function(node) { + if (isParenthesised(node.test) && precedence(node.test) >= precedence({type: "LogicalExpression", operator: "||"})) { + report(node.test); + } + if (isParenthesised(node.consequent) && precedence(node.consequent) >= precedence({type: "AssignmentExpression"})) { + report(node.consequent); + } + if (isParenthesised(node.alternate) && precedence(node.alternate) >= precedence({type: "AssignmentExpression"})) { + report(node.alternate); + } + }, + "DoWhileStatement": function(node) { + if (isParenthesisedTwice(node.test)) { + report(node.test); + } + }, + "ExpressionStatement": function(node) { + var firstToken; + if (isParenthesised(node.expression)) { + firstToken = context.getFirstToken(node.expression); + if (firstToken.value !== "function" && firstToken.value !== "{") { + report(node.expression); + } + } + }, + "ForInStatement": function(node) { + if (isParenthesised(node.right)) { + report(node.right); + } + }, + "ForStatement": function(node) { + if (node.init && isParenthesised(node.init)) { + report(node.init); + } + + if (node.test && isParenthesised(node.test)) { + report(node.test); + } + + if (node.update && isParenthesised(node.update)) { + report(node.update); + } + }, + "IfStatement": function(node) { + if (isParenthesisedTwice(node.test)) { + report(node.test); + } + }, + "LogicalExpression": dryBinaryLogical, + "MemberExpression": function(node) { + if ( + isParenthesised(node.object) && + precedence(node.object) >= precedence(node) && + ( + node.computed || + !( + node.object.type === "Literal" && + typeof node.object.value === "number" && + /^[0-9]+$/.test(context.getFirstToken(node.object).value) + ) + ) + ) { + report(node.object); + } + }, + "NewExpression": dryCallNew, + "ObjectExpression": function(node) { + [].forEach.call(node.properties, function(e) { + var v = e.value; + if (v && isParenthesised(v) && precedence(v) >= precedence({type: "AssignmentExpression"})) { + report(v); + } + }); + }, + "ReturnStatement": function(node) { + if (node.argument && isParenthesised(node.argument)) { + report(node.argument); + } + }, + "SequenceExpression": function(node) { + [].forEach.call(node.expressions, function(e) { + if (isParenthesised(e) && precedence(e) >= precedence(node)) { + report(e); + } + }); + }, + "SwitchCase": function(node) { + if (node.test && isParenthesised(node.test)) { + report(node.test); + } + }, + "SwitchStatement": function(node) { + if (isParenthesisedTwice(node.discriminant)) { + report(node.discriminant); + } + }, + "ThrowStatement": function(node) { + if (isParenthesised(node.argument)) { + report(node.argument); + } + }, + "UnaryExpression": dryUnaryUpdate, + "UpdateExpression": dryUnaryUpdate, + "VariableDeclarator": function(node) { + if (node.init && isParenthesised(node.init) && precedence(node.init) >= precedence({type: "AssignmentExpression"})) { + report(node.init); + } + }, + "WhileStatement": function(node) { + if (isParenthesisedTwice(node.test)) { + report(node.test); + } + }, + "WithStatement": function(node) { + if (isParenthesisedTwice(node.object)) { + report(node.object); + } + } + }; + +}; + +},{}],64:[function(require,module,exports){ +/** + * @fileoverview Rule to flag use of unnecessary semicolons + * @author Nicholas C. Zakas + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + return { + + "EmptyStatement": function(node) { + context.report(node, "Unnecessary semicolon."); + } + }; + +}; + +},{}],65:[function(require,module,exports){ +/** + * @fileoverview Rule to flag unnecessary strict directives. + * @author Ian Christian Myers + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + function directives(block) { + var ds = [], body = block.body, e, i, l; + + for (i = 0, l = body.length; i < l; ++i) { + e = body[i]; + + if ( + e.type === "ExpressionStatement" && + e.expression.type === "Literal" && + typeof e.expression.value === "string" + ) { + ds.push(e.expression); + } else { + break; + } + } + return ds; + } + + function isStrict(directive) { + return directive.value === "use strict"; + } + + function checkForUnnecessaryUseStrict(node) { + var useStrictDirectives, scope, upper; + useStrictDirectives = directives(node).filter(isStrict); + + switch (useStrictDirectives.length) { + case 0: + break; + + case 1: + scope = context.getScope(); + upper = scope.upper; + + if (upper && upper.functionExpressionScope) { + upper = upper.upper; + } + + if (upper && upper.isStrict) { + context.report(useStrictDirectives[0], "Unnecessary 'use strict'."); + } + break; + + default: + context.report(useStrictDirectives[1], "Multiple 'use strict' directives."); + } + } + + return { + + "Program": checkForUnnecessaryUseStrict, + + "FunctionExpression": function(node) { + checkForUnnecessaryUseStrict(node.body); + }, + + "FunctionDeclaration": function(node) { + checkForUnnecessaryUseStrict(node.body); + } + }; + +}; + +},{}],66:[function(require,module,exports){ +/** + * @fileoverview Rule to flag fall-through cases in switch statements. + * @author Matt DuVall + */ +"use strict"; + + +var FALLTHROUGH_COMMENT = /falls\sthrough/; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var switches = []; + + return { + + "SwitchCase": function(node) { + + var consequent = node.consequent, + switchData = switches[switches.length - 1], + i, + comments, + comment; + + /* + * Some developers wrap case bodies in blocks, so if there is just one + * node and it's a block statement, check inside. + */ + if (consequent.length === 1 && consequent[0].type === "BlockStatement") { + consequent = consequent[0]; + } + + // checking on previous case + if (!switchData.lastCaseClosed) { + + // a fall through comment will be the last trailing comment of the last case + comments = context.getComments(switchData.lastCase).trailing; + comment = comments[comments.length - 1]; + + // check for comment + if (!comment || !FALLTHROUGH_COMMENT.test(comment.value)) { + context.report(switchData.lastCase, + "Expected a \"break\" statement before \"{{code}}\".", + { code: node.test ? "case" : "default" }); + } + } + + // now dealing with the current case + switchData.lastCaseClosed = false; + switchData.lastCase = node; + + // try to verify using statements - go backwards as a fast path for the search + if (consequent.length) { + for (i = consequent.length - 1; i >= 0; i--) { + if (/(?:Break|Continue|Return|Throw)Statement/.test(consequent[i].type)) { + switchData.lastCaseClosed = true; + break; + } + } + } else { + // the case statement has no statements, so it must logically fall through + switchData.lastCaseClosed = true; + } + + /* + * Any warnings are triggered when the next SwitchCase occurs. + * There is no need to warn on the last SwitchCase, since it can't + * fall through to anything. + */ + }, + + "SwitchStatement": function(node) { + switches.push({ + node: node, + lastCaseClosed: true, + lastCase: null + }); + }, + + "SwitchStatement:exit": function() { + switches.pop(); + } + }; + +}; + +},{}],67:[function(require,module,exports){ +/** + * @fileoverview Rule to flag use of a leading/trailing decimal point in a numeric literal + * @author James Allardice + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + return { + "Literal": function(node) { + + if (typeof node.value === "number") { + if (node.raw.indexOf(".") === 0) { + context.report(node, "A leading decimal point can be confused with a dot."); + } + if (node.raw.indexOf(".") === node.raw.length - 1) { + context.report(node, "A trailing decimal point can be confused with a dot."); + } + } + } + }; + +}; + +},{}],68:[function(require,module,exports){ +/** + * @fileoverview Rule to flag use of function declaration identifiers as variables. + * @author Ian Christian Myers + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /* + * Walk the scope chain looking for either a FunctionDeclaration or a + * VariableDeclaration with the same name as left-hand side of the + * AssignmentExpression. If we find the FunctionDeclaration first, then we + * warn, because a FunctionDeclaration is trying to become a Variable or a + * FunctionExpression. If we find a VariableDeclaration first, then we have + * a legitimate shadow variable. + */ + function checkIfIdentifierIsFunction(scope, name) { + var variable, + def, + i, + j; + + // Loop over all of the identifiers available in scope. + for (i = 0; i < scope.variables.length; i++) { + variable = scope.variables[i]; + + // For each identifier, see if it was defined in _this_ scope. + for (j = 0; j < variable.defs.length; j++) { + def = variable.defs[j]; + + // Identifier is a function and was declared in this scope + if (def.name.name === name && def.type === "FunctionName") { + return true; + } + + // Identifier is a variable and was declared in this scope. This + // is a legitimate shadow variable. + if (def.name.name === name) { + return false; + } + } + } + + // Check the upper scope. + if (scope.upper) { + return checkIfIdentifierIsFunction(scope.upper, name); + } + + // We've reached the global scope and haven't found anything. + return false; + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + + "AssignmentExpression": function(node) { + var scope = context.getScope(), + name = node.left.name; + + if (checkIfIdentifierIsFunction(scope, name)) { + context.report(node, "'{{name}}' is a function.", { name: name }); + } + + } + + }; + +}; + +},{}],69:[function(require,module,exports){ +/** + * @fileoverview Rule to flag use of implied eval via setTimeout and setInterval + * @author James Allardice + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + return { + "CallExpression": function(node) { + + if (node.callee.type === "Identifier") { + var callee = node.callee.name; + + if (callee === "setTimeout" || callee === "setInterval") { + var argument = node.arguments[0]; + if (argument && argument.type === "Literal" && typeof argument.value === "string") { + context.report(node, "Implied eval. Consider passing a function instead of a string."); + } + } + } + } + }; + +}; + +},{}],70:[function(require,module,exports){ +/** + * @fileoverview Rule to enforce declarations in program or function body root. + * @author Brandon Mills + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + /** + * Find the nearest Program or Function ancestor node. + * @returns {Object} Ancestor's type and distance from node. + */ + function nearestBody() { + var ancestors = context.getAncestors(), + ancestor = ancestors.pop(), + generation = 1; + + while (ancestor && ["Program", "FunctionDeclaration", + "FunctionExpression"].indexOf(ancestor.type) < 0) { + generation += 1; + ancestor = ancestors.pop(); + } + + return { + // Type of containing ancestor + type: ancestor.type, + // Separation between ancestor and node + distance: generation + }; + } + + /** + * Ensure that a given node is at a program or function body's root. + * @param {ASTNode} node Declaration node to check. + * @returns {void} + */ + function check(node) { + var body = nearestBody(node), + valid = ((body.type === "Program" && body.distance === 1) || + body.distance === 2); + + if (!valid) { + context.report(node, "Move {{type}} declaration to {{body}} root.", + { + type: (node.type === "FunctionDeclaration" ? + "function" : "variable"), + body: (body.type === "Program" ? + "program" : "function body") + } + ); + } + } + + return { + + "FunctionDeclaration": check, + "VariableDeclaration": function(node) { + if (context.options[0] === "both") { + check(node); + } + } + + }; + +}; + +},{}],71:[function(require,module,exports){ +/** + * @fileoverview Validate strings passed to the RegExp constructor + * @author Michael Ficarra + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + function isString(node) { + return node && node.type === "Literal" && typeof node.value === "string"; + } + + function check(node) { + if (node.callee.type === "Identifier" && node.callee.name === "RegExp" && isString(node.arguments[0])) { + try { + if (isString(node.arguments[1])) { + void new RegExp(node.arguments[0].value, node.arguments[1].value); + } else { + void new RegExp(node.arguments[0].value); + } + } catch(e) { + context.report(node, e.message); + } + } + } + + return { + "CallExpression": check, + "NewExpression": check + }; + +}; + +},{}],72:[function(require,module,exports){ +/** + * @fileoverview Rule to flag usage of __iterator__ property + * @author Ian Christian Myers + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + return { + + "MemberExpression": function(node) { + + if (node.property && + (node.property.type === "Identifier" && node.property.name === "__iterator__" && !node.computed) || + (node.property.type === "Literal" && node.property.value === "__iterator__")) { + context.report(node, "Reserved name '__iterator__'."); + } + } + }; + +}; + +},{}],73:[function(require,module,exports){ +/** + * @fileoverview Rule to flag labels that are the same as an identifier + * @author Ian Christian Myers + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + function findIdentifier(scope, identifier) { + var found = false; + + scope.variables.forEach(function(variable) { + if (variable.name === identifier) { + found = true; + } + }); + + scope.references.forEach(function(reference) { + if (reference.identifier.name === identifier) { + found = true; + } + }); + + // If we have not found the identifier in this scope, check the parent + // scope. + if (scope.upper && !found) { + return findIdentifier(scope.upper, identifier); + } + + return found; + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + + "LabeledStatement": function(node) { + + // Fetch the innermost scope. + var scope = context.getScope(); + + // Recursively find the identifier walking up the scope, starting + // with the innermost scope. + if (findIdentifier(scope, node.label.name)) { + context.report(node, "Found identifier with same name as label."); + } + } + + }; + +}; + +},{}],74:[function(require,module,exports){ +/** + * @fileoverview Disallow Labeled Statements + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + "LabeledStatement": function(node) { + context.report(node, "Unexpected labeled statement."); + }, + + "BreakStatement": function(node) { + + if (node.label) { + context.report(node, "Unexpected label in break statement."); + } + + }, + + "ContinueStatement": function(node) { + + if (node.label) { + context.report(node, "Unexpected label in continue statement."); + } + + } + + + }; + +}; + +},{}],75:[function(require,module,exports){ +/** + * @fileoverview Rule to flag blocks with no reason to exist + * @author Brandon Mills + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + return { + "BlockStatement": function (node) { + // Check for any occurrence of BlockStatement > BlockStatement or + // Program > BlockStatement + var parent = context.getAncestors().pop(); + if (parent.type === "BlockStatement" || parent.type === "Program") { + context.report(node, "Block is nested inside another block."); + } + } + }; + +}; + +},{}],76:[function(require,module,exports){ +/** + * @fileoverview Rule to disallow if as the only statmenet in an else block + * @author Brandon Mills + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + "IfStatement": function(node) { + var ancestors = context.getAncestors(), + parent = ancestors.pop(), + grandparent = ancestors.pop(); + + if (parent && parent.type === "BlockStatement" && + parent.body.length === 1 && grandparent && + grandparent.type === "IfStatement" && + parent === grandparent.alternate) { + context.report(node, "Unexpected if as the only statement in an else block."); + } + } + }; + +}; + +},{}],77:[function(require,module,exports){ +/** + * @fileoverview Rule to flag creation of function inside a loop + * @author Ilya Volodin + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + function checkForLoops(node) { + var ancestors = context.getAncestors(); + + if (ancestors.some(function(ancestor) { + return ancestor.type === "ForStatement" || ancestor.type === "WhileStatement" || ancestor.type === "DoWhileStatement"; + })) { + context.report(node, "Don't make functions within a loop"); + } + } + + return { + "FunctionExpression": checkForLoops, + "FunctionDeclaration": checkForLoops + }; +}; + +},{}],78:[function(require,module,exports){ +/** + * @fileoverview Rule to enforce grouped require statements for Node.JS + * @author Raphael Pigulla + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + "use strict"; + + /** + * Returns the list of built-in modules. + * + * @returns {string[]} An array of built-in Node.js modules. + */ + function getBuiltinModules() { + // This list is generated using `require("repl")._builtinLibs.concat('repl').sort()` + // This particular list was generated using node v0.11.9 + return [ + "assert", "buffer", "child_process", "cluster", "crypto", + "dgram", "dns", "domain", "events", "fs", "http", "https", + "net", "os", "path", "punycode", "querystring", "readline", + "repl", "smalloc", "stream", "string_decoder", "tls", "tty", + "url", "util", "vm", "zlib" + ]; + } + + var BUILTIN_MODULES = getBuiltinModules(); + + var DECL_REQUIRE = "require", + DECL_UNINITIALIZED = "uninitialized", + DECL_OTHER = "other"; + + var REQ_CORE = "core", + REQ_FILE = "file", + REQ_MODULE = "module", + REQ_COMPUTED = "computed"; + + /** + * Determines the type of a declaration statement. + * @param {ASTNode} initExpression The init node of the VariableDeclarator. + * @returns {string} The type of declaration represented by the expression. + */ + function getDeclarationType(initExpression) { + if (!initExpression) { + // "var x;" + return DECL_UNINITIALIZED; + } + + if (initExpression.type === "CallExpression" && + initExpression.callee.type === "Identifier" && + initExpression.callee.name === "require" + ) { + // "var x = require('util');" + return DECL_REQUIRE; + } else if (initExpression.type === "MemberExpression") { + // "var x = require('glob').Glob;" + return getDeclarationType(initExpression.object); + } + + // "var x = 42;" + return DECL_OTHER; + } + + /** + * Determines the type of module that is loaded via require. + * @param {ASTNode} initExpression The init node of the VariableDeclarator. + * @returns {string} The module type. + */ + function inferModuleType(initExpression) { + if (initExpression.type === "MemberExpression") { + // "var x = require('glob').Glob;" + return inferModuleType(initExpression.object); + } else if (initExpression["arguments"].length === 0) { + // "var x = require();" + return REQ_COMPUTED; + } + + var arg = initExpression["arguments"][0]; + + if (arg.type !== "Literal" || typeof arg.value !== "string") { + // "var x = require(42);" + return REQ_COMPUTED; + } + + if (BUILTIN_MODULES.indexOf(arg.value) !== -1) { + // "var fs = require('fs');" + return REQ_CORE; + } else if (/^\.{0,2}\//.test(arg.value)) { + // "var utils = require('./utils');" + return REQ_FILE; + } else { + // "var async = require('async');" + return REQ_MODULE; + } + } + + /** + * Check if the list of variable declarations is mixed, i.e. whether it + * contains both require and other declarations. + * @param {ASTNode} declarations The list of VariableDeclarators. + * @returns {boolean} True if the declarations are mixed, false if not. + */ + function isMixed(declarations) { + var contains = {}; + + declarations.forEach(function (declaration) { + var type = getDeclarationType(declaration.init); + contains[type] = true; + }); + + return !!( + contains[DECL_REQUIRE] && + (contains[DECL_UNINITIALIZED] || contains[DECL_OTHER]) + ); + } + + /** + * Check if all require declarations in the given list are of the same + * type. + * @param {ASTNode} declarations The list of VariableDeclarators. + * @returns {boolean} True if the declarations are grouped, false if not. + */ + function isGrouped(declarations) { + var found = {}; + + declarations.forEach(function (declaration) { + if (getDeclarationType(declaration.init) === DECL_REQUIRE) { + found[inferModuleType(declaration.init)] = true; + } + }); + + return Object.keys(found).length <= 1; + } + + + return { + + "VariableDeclaration": function(node) { + var grouping = !!context.options[0]; + + if (isMixed(node.declarations)) { + context.report( + node, + "Do not mix 'require' and other declarations." + ); + } else if (grouping && !isGrouped(node.declarations)) { + context.report( + node, + "Do not mix core, module, file and computed requires." + ); + } + } + }; + +}; + +},{}],79:[function(require,module,exports){ +/** + * @fileoverview Disallow mixed spaces and tabs for indentation + * @author Jary Niebur + * @copyright 2014 Nicholas C. Zakas. All rights reserved. + * @copyright 2014 Jary Niebur. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var smartTabs = context.options[0]; + + var COMMENT_START = /^\s*\/\*/, + MAYBE_COMMENT = /^\s*\*/; + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + "Program": function(node) { + /* + * At least one space followed by a tab + * or the reverse before non-tab/-space + * characters begin. + */ + var regex = /^(?=[\t ]*(\t | \t))/, + match, + lines = context.getSourceLines(); + + if (smartTabs) { + /* + * At least one space followed by a tab + * before non-tab/-space characters begin. + */ + regex = /^(?=[\t ]* \t)/; + } + + lines.forEach(function(line, i) { + match = regex.exec(line); + + if (match) { + + if (!MAYBE_COMMENT.test(line) && !COMMENT_START.test(lines[i - 1])) { + context.report(node, { line: i + 1, column: match.index + 1 }, "Mixed spaces and tabs."); + } + + } + }); + } + + }; + +}; + +},{}],80:[function(require,module,exports){ +/** + * @fileoverview Disallow use of multiple spaces. + * @author Vignesh Anand aka vegetableman. + * @copyright 2014 Vignesh Anand. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var OPERATORS = [ + "*", "/", "%", "+", "-", "<<", ">>", ">>>", "<", "<=", ">", ">=", "in", + "instanceof", "==", "!=", "===", "!==", "&", "^", "|", "&&", "||", "=", + "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", "&=", "^=", "|=", + "?", ":", "," + ], errOps = []; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Reports an AST node as a rule violation. + * @param {ASTNode} node The node to report. + * @returns {void} + * @private + */ + function report(node) { + context.report(node, "Multiple spaces found around '" + errOps.shift() + "'."); + } + + /** + * Checks whether the operator is in same line as two adjacent tokens. + * @param {ASTNode} left The token left to the operator. + * @param {ASTNode} right The token right to the operator. + * @param {ASTNode} operator The operator. + * @returns {boolean} Whether the operator is in same line as two adjacent tokens. + * @private + */ + function isSameLine(left, right, operator) { + return operator.loc.end.line === left.loc.end.line && + operator.loc.end.line === right.loc.start.line; + } + + /** + * Check whether there are multiple spaces around the operator. + * @param {ASTNode} left The token left to the operator. + * @param {ASTNode} right The token right to the operator. + * @param {ASTNode} operator The operator. + * @returns {boolean} Whether there are multiple spaces. + * @private + */ + function isMultiSpaced(left, right, operator) { + return operator.range[0] - left.range[1] > 1 || + right.range[0] - operator.range[1] > 1; + } + + /** + * Get tokens and validate the spacing. + * @param {ASTNode} left The token left to the operator. + * @param {ASTNode} right The token right to the operator. + * @returns {boolean} Whether multiple spaces were found. + * @private + */ + function validateSpacing(left, right) { + var tokens = context.getTokens({range: [left.range[1], right.range[0]]}, 1, 1), + operator; + + for (var i = 1, l = tokens.length - 1; i < l; ++i) { + left = tokens[i - 1]; + operator = tokens[i]; + right = tokens[i + 1]; + + if (operator && operator.type === "Punctuator" && OPERATORS.indexOf(operator.value) >= 0 && + isSameLine(left, right, operator) && isMultiSpaced(left, right, operator)) { + errOps.push(operator.value); + return true; + } + } + + return false; + } + + + /** + * Report if there are multiple spaces on the expression. + * @param {ASTNode} node The node to check. + * @returns {void} + * @private + */ + function checkExpression(node) { + if (validateSpacing(node.left, node.right)) { + report(node); + } + } + + /** + * Report if there are multiple spaces around conditional ternary operators. + * @param {ASTNode} node The node to check. + * @returns {void} + * @private + */ + function checkConditional(node) { + if (validateSpacing(node.test, node.consequent)) { + report(node); + } + if (validateSpacing(node.consequent, node.alternate)) { + report(node); + } + } + + /** + * Report if there are multiple spaces around equal operator in variable declaration. + * @param {ASTNode} node The node to check. + * @returns {void} + * @private + */ + function checkVar(node) { + if (node.init && validateSpacing(node.id, node.init)) { + report(node); + } + } + + /** + * Report if there are multiple spaces around list of items in objects, arrays, + * function parameters, sequences and declarations. + * @param {ASTNode} node The node to check. + * @param {string} property The property of node. + * @returns {void} + * @private + */ + function checkList(node, property) { + var items = node[property]; + + for (var i = 0, l = items.length; i < l; i++) { + var left = items[i - 1], + right = items[i], + operator = context.getTokenBefore(right); + + if (operator && operator.type === "Punctuator" && operator.value === ",") { + if (isSameLine(left, right, operator) && isMultiSpaced(left, right, operator)) { + errOps.push(operator.value); + report(right); + } + } + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + "AssignmentExpression": checkExpression, + "BinaryExpression": checkExpression, + "LogicalExpression": checkExpression, + "ConditionalExpression": checkConditional, + "VariableDeclarator": checkVar, + "ArrayExpression": function(node) { + checkList(node, "elements"); + }, + "ObjectExpression": function(node) { + checkList(node, "properties"); + }, + "SequenceExpression": function(node) { + checkList(node, "expressions"); + }, + "FunctionExpression": function(node) { + checkList(node, "params"); + }, + "FunctionDeclaration": function(node) { + checkList(node, "params"); + }, + "VariableDeclaration": function(node) { + checkList(node, "declarations"); + } + }; + +}; + +},{}],81:[function(require,module,exports){ +/** + * @fileoverview Rule to flag when using multiline strings + * @author Ilya Volodin + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + "use strict"; + + return { + + "Literal": function(node) { + var lineBreak = /\n/; + if (lineBreak.test(node.raw)) { + context.report(node, "Multiline support is limited to browsers supporting ES5 only."); + } + } + }; + +}; + +},{}],82:[function(require,module,exports){ +/** + * @fileoverview Disallows multiple blank lines. + * implementation adapted from the no-trailing-spaces rule. + * @author Greg Cochard + * @copyright 2014 Greg Cochard. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + // Use options.max or 2 as default + var numLines = 2; + + if (context.options.length) { + numLines = context.options[0].max; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + "Program": function checkBlankLines(node) { + var lines = context.getSourceLines(), + currentLocation = -1, + lastLocation, + blankCounter = 0, + location, + trimmedLines = lines.map(function(str) { + return str.trim(); + }); + + // Aggregate and count blank lines + do { + lastLocation = currentLocation; + currentLocation = trimmedLines.indexOf("",currentLocation + 1); + if (lastLocation === currentLocation - 1) { + blankCounter++; + } else { + if (blankCounter >= numLines) { + location = { + line: lastLocation + 1, + column: lines[lastLocation].length + }; + context.report(node, location, "Multiple blank lines not allowed."); + } + + // Finally, reset the blank counter + blankCounter = 0; + } + } while (currentLocation !== -1); + } + }; + +}; + +},{}],83:[function(require,module,exports){ +/** + * @fileoverview Rule to flag when re-assigning native objects + * @author Ilya Volodin + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + var nativeObjects = ["Array", "Boolean", "Date", "decodeURI", + "decodeURIComponent", "encodeURI", "encodeURIComponent", + "Error", "eval", "EvalError", "Function", "isFinite", + "isNaN", "JSON", "Math", "Number", "Object", "parseInt", + "parseFloat", "RangeError", "ReferenceError", "RegExp", + "String", "SyntaxError", "TypeError", "URIError", + "Map", "NaN", "Set", "WeakMap", "Infinity", "undefined"]; + + return { + + "AssignmentExpression": function(node) { + if (nativeObjects.indexOf(node.left.name) >= 0) { + context.report(node, node.left.name + " is a read-only native object."); + } + }, + + "VariableDeclarator": function(node) { + if (nativeObjects.indexOf(node.id.name) >= 0) { + context.report(node, "Redefinition of '{{nativeObject}}'.", { nativeObject: node.id.name }); + } + } + }; + +}; + +},{}],84:[function(require,module,exports){ +/** + * @fileoverview A rule to disallow negated left operands of the `in` operator + * @author Michael Ficarra + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + return { + + "BinaryExpression": function(node) { + if (node.operator === "in" && node.left.type === "UnaryExpression" && node.left.operator === "!") { + context.report(node, "The `in` expression's left operand is negated"); + } + } + }; + +}; + +},{}],85:[function(require,module,exports){ +/** + * @fileoverview Rule to flag nested ternary expressions + * @author Ian Christian Myers + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + return { + "ConditionalExpression": function(node) { + if (node.alternate.type === "ConditionalExpression" || + node.consequent.type === "ConditionalExpression") { + context.report(node, "Do not nest ternary expressions"); + } + } + }; +}; + +},{}],86:[function(require,module,exports){ +/** + * @fileoverview Rule to flag when using new Function + * @author Ilya Volodin + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + return { + + "NewExpression": function(node) { + if (node.callee.name === "Function") { + context.report(node, "The Function constructor is eval."); + } + } + }; + +}; + +},{}],87:[function(require,module,exports){ +/** + * @fileoverview A rule to disallow calls to the Object constructor + * @author Matt DuVall + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + return { + + "NewExpression": function(node) { + if (node.callee.name === "Object") { + context.report(node, "The object literal notation {} is preferrable."); + } + } + }; + +}; + +},{}],88:[function(require,module,exports){ +/** + * @fileoverview Rule to disallow use of new operator with the `require` function + * @author Wil Moore III + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + return { + + "NewExpression": function(node) { + if (node.callee.type === "Identifier" && node.callee.name === "require") { + context.report(node, "Unexpected use of new with require."); + } + } + }; + +}; + +},{}],89:[function(require,module,exports){ +/** + * @fileoverview Rule to flag when using constructor for wrapper objects + * @author Ilya Volodin + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + return { + + "NewExpression": function(node) { + var wrapperObjects = ["String", "Number", "Boolean", "Math", "JSON"]; + if (wrapperObjects.indexOf(node.callee.name) > -1) { + context.report(node, "Do not use {{fn}} as a constructor.", { fn: node.callee.name }); + } + } + }; + +}; + +},{}],90:[function(require,module,exports){ +/** + * @fileoverview Rule to flag statements with function invocation preceded by + * "new" and not part of assignment + * @author Ilya Volodin + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + return { + + "ExpressionStatement": function(node) { + + if (node.expression.type === "NewExpression") { + context.report(node, "Do not use 'new' for side effects."); + } + } + }; + +}; + +},{}],91:[function(require,module,exports){ +/** + * @fileoverview Rule to flag use of an object property of the global object (Math and JSON) as a function + * @author James Allardice + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + return { + "CallExpression": function(node) { + + if (node.callee.type === "Identifier") { + var name = node.callee.name; + if (name === "Math" || name === "JSON") { + context.report(node, "'{{name}}' is not a function.", { name: name }); + } + } + } + }; + +}; + +},{}],92:[function(require,module,exports){ +/** + * @fileoverview Rule to flag octal escape sequences in string literals. + * @author Ian Christian Myers + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + return { + + "Literal": function(node) { + if (typeof node.value !== "string") { + return; + } + var match = node.raw.match(/^([^\\]|\\[^0-7])*\\([0-7])/), + octalDigit; + + if (match) { + octalDigit = match[2]; + context.report(node, "Don't use octal: '\\{{octalDigit}}'. Use '\\u....' instead.", + { octalDigit: octalDigit }); + } + } + + }; + +}; + +},{}],93:[function(require,module,exports){ +/** + * @fileoverview Rule to flag when initializing octal literal + * @author Ilya Volodin + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + return { + + "Literal": function(node) { + if (typeof node.value === "number" && /^0[0-7]/.test(node.raw)) { + context.report(node, "Octal literals should not be used."); + } + } + }; + +}; + +},{}],94:[function(require,module,exports){ +/** + * @fileoverview Disallow string concatenation when using __dirname and __filename + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var MATCHER = /^__(?:dir|file)name$/; + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + "BinaryExpression": function(node) { + + var left = node.left, + right = node.right; + + if (node.operator === "+" && + ((left.type === "Identifier" && MATCHER.test(left.name)) || + (right.type === "Identifier" && MATCHER.test(right.name))) + ) { + + context.report(node, "Use path.join() or path.resolve() instead of + to create paths."); + } + } + + }; + +}; + +},{}],95:[function(require,module,exports){ +/** + * @fileoverview Rule to flag use of unary increment and decrement operators. + * @author Ian Christian Myers + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + return { + + "UpdateExpression": function(node) { + context.report(node, "Unary operator '" + node.operator + "' used."); + } + + }; + +}; + +},{}],96:[function(require,module,exports){ +/** + * @fileoverview Disallow the use of process.env() + * @author Vignesh Anand + * @copyright 2014 Vignesh Anand. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "MemberExpression": function(node) { + var objectName = node.object.name, + propertyName = node.property.name; + + if (objectName === "process" && !node.computed && propertyName && propertyName === "env") { + context.report(node, "Unexpected use of process.env."); + } + + } + + }; + +}; + +},{}],97:[function(require,module,exports){ +/** + * @fileoverview Disallow the use of process.exit() + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + "CallExpression": function(node) { + var callee = node.callee; + + if (callee.type === "MemberExpression" && callee.object.name === "process" && + callee.property.name === "exit" + ) { + context.report(node, "Don't use process.exit(); throw an error instead."); + } + } + + }; + +}; + +},{}],98:[function(require,module,exports){ +/** + * @fileoverview Rule to flag usage of __proto__ property + * @author Ilya Volodin + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + return { + + "MemberExpression": function(node) { + + if (node.property && + (node.property.type === "Identifier" && node.property.name === "__proto__" && !node.computed) || + (node.property.type === "Literal" && node.property.value === "__proto__")) { + context.report(node, "The '__proto__' property is deprecated."); + } + } + }; + +}; + +},{}],99:[function(require,module,exports){ +/** + * @fileoverview Rule to flag when the same variable is declared more then once. + * @author Ilya Volodin + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + function findVariables() { + var scope = context.getScope(); + + scope.variables.forEach(function(variable) { + if (variable.identifiers && variable.identifiers.length > 1) { + variable.identifiers.sort(function(a, b) { + return a.range[1] - b.range[1]; + }); + + for (var i = 1, l = variable.identifiers.length; i < l; i++) { + context.report(variable.identifiers[i], "{{a}} is already defined", {a: variable.name}); + } + } + }); + } + + return { + "Program": findVariables, + "FunctionExpression": findVariables, + "FunctionDeclaration": findVariables + }; +}; + +},{}],100:[function(require,module,exports){ +/** + * @fileoverview Rule to count multiple spaces in regular expressions + * @author Matt DuVall + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + return { + + "Literal": function(node) { + var token = context.getFirstTokens(node, 1)[0], + nodeType = token.type, + nodeValue = token.value, + multipleSpacesRegex = /( {2,})+?/, + regexResults; + + if (nodeType === "RegularExpression") { + regexResults = multipleSpacesRegex.exec(nodeValue); + + if (regexResults !== null) { + context.report(node, "Spaces are hard to count. Use {" + regexResults[0].length + "}."); + } + } + } + }; + +}; + +},{}],101:[function(require,module,exports){ +/** + * @fileoverview Rule to disallow reserved words being used as keys + * @author Emil Bay + * @copyright 2014 Emil Bay. All rights reserved. + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + var MESSAGE = "Reserved word '{{key}}' used as key."; + + var reservedWords = [ + "abstract", + "boolean", "break", "byte", + "case", "catch", "char", "class", "const", "continue", + "debugger", "default", "delete", "do", "double", + "else", "enum", "export", "extends", + "final", "finally", "float", "for", "function", + "goto", + "if", "implements", "import", "in", "instanceof", "int", "interface", + "long", + "native", "new", + "package", "private", "protected", "public", + "return", + "short", "static", "super", "switch", "synchronized", + "this", "throw", "throws", "transient", "try", "typeof", + "var", "void", "volatile", + "while", "with" + ]; + + return { + + "ObjectExpression": function(node) { + node.properties.forEach(function(property) { + + if (property.key.type === "Identifier") { + var keyName = property.key.name; + + if (reservedWords.indexOf("" + keyName) !== -1) { + context.report(node, MESSAGE, { key: keyName }); + } + } + + }); + + } + }; + +}; + +},{}],102:[function(require,module,exports){ +/** + * @fileoverview Restrict usage of specified node modules. + * @author Christian Schulz + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function (context) { + // trim restricted module names + var restrictedModules = context.options; + + // if no modules are restricted we don't need to check the CallExpressions + if (restrictedModules.length === 0) { + return {}; + } + + /** + * Function to check if a node is a string literal. + * @param {ASTNode} node The node to check. + * @returns {boolean} If the node is a string literal. + */ + function isString(node) { + return node && node.type === "Literal" && typeof node.value === "string"; + } + + /** + * Function to check if a node is a require call. + * @param {ASTNode} node The node to check. + * @returns {boolean} If the node is a require call. + */ + function isRequireCall(node) { + return node.callee.type === "Identifier" && node.callee.name === "require"; + } + + /** + * Function to check if a node has an argument that is an restricted module and return its name. + * @param {ASTNode} node The node to check + * @returns {undefined|String} restricted module name or undefined if node argument isn't restricted. + */ + function getRestrictedModuleName(node) { + var moduleName; + + // node has arguments and first argument is string + if (node.arguments.length && isString(node.arguments[0])) { + var argumentValue = node.arguments[0].value.trim(); + + // check if argument value is in restricted modules array + if (restrictedModules.indexOf(argumentValue) !== -1) { + moduleName = argumentValue; + } + } + + return moduleName; + } + + return { + "CallExpression": function (node) { + if (isRequireCall(node)) { + var restrictedModuleName = getRestrictedModuleName(node); + + if (restrictedModuleName) { + context.report(node, "'{{moduleName}}' module is restricted from being used.", { + moduleName: restrictedModuleName + }); + } + } + } + }; +}; + +},{}],103:[function(require,module,exports){ +/** + * @fileoverview Rule to flag when return statement contains assignment + * @author Ilya Volodin + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "ReturnStatement": function(node) { + if (node.argument && node.argument.type === "AssignmentExpression") { + context.report(node, "Return statement should not contain assignment."); + } + } + }; + +}; + +},{}],104:[function(require,module,exports){ +/** + * @fileoverview Rule to flag when using javascript: urls + * @author Ilya Volodin + */ +/*jshint scripturl: true */ +/*eslint no-script-url: 0*/ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "Literal": function(node) { + + var value; + + if (node.value && typeof(node.value) === "string") { + value = node.value.toLowerCase(); + + if (value.indexOf("javascript:") === 0) { + context.report(node, "Script URL is a form of eval."); + } + } + } + }; + +}; + +},{}],105:[function(require,module,exports){ +/** + * @fileoverview Rule to flag comparison where left part is the same as the right + * part. + * @author Ilya Volodin + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + "use strict"; + + return { + + "BinaryExpression": function(node) { + var operators = ["===", "==", "!==", "!=", ">", "<", ">=", "<="]; + if (operators.indexOf(node.operator) > -1 && + (node.left.type === "Identifier" && node.right.type === "Identifier" && node.left.name === node.right.name || + node.left.type === "Literal" && node.right.type === "Literal" && node.left.value === node.right.value)) { + context.report(node, "Comparing to itself is potentially pointless."); + } + } + }; + +}; + +},{}],106:[function(require,module,exports){ +/** + * @fileoverview Rule to flag use of comma operator + * @author Brandon Mills + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + /** + * Parts of the grammar that are required to have parens. + */ + var parenthesized = { + "DoWhileStatement": "test", + "IfStatement": "test", + "SwitchStatement": "discriminant", + "WhileStatement": "test", + "WithStatement": "object" + + // Omitting CallExpression - commas are parsed as argument separators + // Omitting NewExpression - commas are parsed as argument separators + // Omitting ForInStatement - parts aren't individually parenthesised + // Omitting ForStatement - parts aren't individually parenthesised + }; + + /** + * Determines whether a node is required by the grammar to be wrapped in + * parens, e.g. the test of an if statement. + * @param {ASTNode} node - The AST node + * @returns {boolean} True if parens around node belong to parent node. + */ + function requiresExtraParens(node) { + return node.parent && parenthesized[node.parent.type] != null && + node === node.parent[parenthesized[node.parent.type]]; + } + + /** + * Check if a node is wrapped in parens. + * @param {ASTNode} node - The AST node + * @returns {boolean} True if the node has a paren on each side. + */ + function isParenthesised(node) { + var previousToken = context.getTokenBefore(node), + nextToken = context.getTokenAfter(node); + + return previousToken && nextToken && + previousToken.value === "(" && previousToken.range[1] <= node.range[0] && + nextToken.value === ")" && nextToken.range[0] >= node.range[1]; + } + + /** + * Check if a node is wrapped in two levels of parens. + * @param {ASTNode} node - The AST node + * @returns {boolean} True if two parens surround the node on each side. + */ + function isParenthesisedTwice(node) { + var previousToken = context.getTokenBefore(node, 1), + nextToken = context.getTokenAfter(node, 1); + + return isParenthesised(node) && previousToken && nextToken && + previousToken.value === "(" && previousToken.range[1] <= node.range[0] && + nextToken.value === ")" && nextToken.range[0] >= node.range[1]; + } + + return { + "SequenceExpression": function(node) { + // Always allow sequences in for statement update + if (node.parent.type === "ForStatement" && + (node === node.parent.init || node === node.parent.update)) { + return; + } + + // Wrapping a sequence in extra parens indicates intent + if (requiresExtraParens(node)) { + if (isParenthesisedTwice(node)) { + return; + } + } else { + if (isParenthesised(node)) { + return; + } + } + + context.report(node, "Unexpected use of comma operator."); + } + }; + +}; + +},{}],107:[function(require,module,exports){ +/** + * @fileoverview Disallow shadowing of NaN, undefined, and Infinity (ES5 section 15.1.1) + * @author Michael Ficarra + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var RESTRICTED = ["undefined", "NaN", "Infinity", "arguments", "eval"]; + + function checkForViolation(id) { + if (RESTRICTED.indexOf(id.name) > -1) { + context.report(id, "Shadowing of global property \"" + id.name + "\"."); + } + } + + return { + "VariableDeclarator": function(node) { + checkForViolation(node.id); + }, + "FunctionExpression": function(node) { + if (node.id) { + checkForViolation(node.id); + } + [].map.call(node.params, checkForViolation); + }, + "FunctionDeclaration": function(node) { + checkForViolation(node.id); + [].map.call(node.params, checkForViolation); + }, + "CatchClause": function(node) { + checkForViolation(node.param); + } + }; + +}; + +},{}],108:[function(require,module,exports){ +/** + * @fileoverview Rule to flag on declaring variables already declared in the outer scope + * @author Ilya Volodin + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + /** + * Checks if a variable is contained in the list of given scope variables. + * @param {Object} variable The variable to check. + * @param {Array} scopeVars The scope variables to look for. + * @returns {boolean} Whether or not the variable is contains in the list of scope variables. + */ + function isContainedInScopeVars(variable, scopeVars) { + return scopeVars.some(function (scopeVar) { + if (scopeVar.identifiers.length > 0) { + return variable.name === scopeVar.name; + } + return false; + }); + } + + /** + * Checks if the given variables are shadowed in the given scope. + * @param {Array} variables The variables to look for + * @param {Object} scope The scope to be checked. + * @returns {void} + */ + function checkShadowsInScope(variables, scope) { + variables.forEach(function (variable) { + if (isContainedInScopeVars(variable, scope.variables)) { + context.report(variable.identifiers[0], "{{a}} is already declared in the upper scope.", {a: variable.name}); + } + }); + } + + /** + * Filters all variables of a list which already occur in another list. + * @param {Array} variableListA List of variables which should be filtered. + * @param {Array} variableListB List of variables which should no occur in variableListA. + * @returns {Array} Filtered list of variables. + */ + function filterVariableList(variableListA, variableListB) { + return variableListA.filter(function (variableA) { + return !variableListB.some(function (variableB) { + return variableA.name === variableB.name; + }); + }); + } + + /** + * Checks the given node for shadowed variables. + * @param {ASTNode} node The AST node of a FunctionDeclaration or FunctionExpression. + * @returns {void} + */ + function checkForShadows(node) { + var scope = context.getScope(), + args = node.params, + variables = filterVariableList(scope.variables, args); + + // iterate through the array of variables and find duplicates with the upper scope + var upper = scope.upper; + while (upper) { + checkShadowsInScope(variables, upper); + upper = upper.upper; + } + } + + return { + "FunctionDeclaration": checkForShadows, + "FunctionExpression": checkForShadows + }; + +}; + +},{}],109:[function(require,module,exports){ +/** + * @fileoverview Rule to require variables declared without whitespace before the lines semicolon + * @author Jonathan Kingston + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + var semicolonWhitespace = /\s;$/; + + return { + "VariableDeclaration": function(node) { + var source = context.getSource(node); + if (semicolonWhitespace.test(source)) { + context.report(node, "Variable declared with trailing whitespace before semicolon"); + } + }, + "ExpressionStatement": function(node) { + var source = context.getSource(node); + if (semicolonWhitespace.test(source)) { + context.report(node, "Expression called with trailing whitespace before semicolon"); + } + } + }; +}; + +},{}],110:[function(require,module,exports){ +/** + * @fileoverview Rule to check that spaced function application + * @author Matt DuVall + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + function detectOpenSpaces(node) { + var lastCalleeToken = context.getLastToken(node.callee); + var tokens = context.getTokens(node); + var i = tokens.indexOf(lastCalleeToken), l = tokens.length; + while (i < l && tokens[i].value !== "(") { + ++i; + } + if (i >= l) { + return; + } + // look for a space between the callee and the open paren + if (tokens[i - 1].range[1] !== tokens[i].range[0]) { + context.report(node, "Unexpected space between function name and paren."); + } + } + + return { + "CallExpression": detectOpenSpaces, + "NewExpression": detectOpenSpaces + }; + +}; + +},{}],111:[function(require,module,exports){ +/** + * @fileoverview Disallow sparse arrays + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + "ArrayExpression": function(node) { + + var emptySpot = node.elements.indexOf(null) > -1; + + if (emptySpot) { + context.report(node, "Unexpected comma in middle of array."); + } + } + + }; + +}; + +},{}],112:[function(require,module,exports){ +/** + * @fileoverview Rule to check for properties whose identifier ends with the string Sync + * @author Matt DuVall + */ + +/*jshint node:true*/ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + return { + + "MemberExpression": function(node) { + var propertyName = node.property.name, + syncRegex = /.*Sync$/; + + if (syncRegex.exec(propertyName) !== null) { + context.report(node, "Unexpected sync method: '" + propertyName + "'."); + } + } + }; + +}; + +},{}],113:[function(require,module,exports){ +/** + * @fileoverview Rule to flag use of ternary operators. + * @author Ian Christian Myers + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + return { + + "ConditionalExpression": function(node) { + context.report(node, "Ternary operator used."); + } + + }; + +}; + +},{}],114:[function(require,module,exports){ +/** + * @fileoverview Disallow trailing spaces at the end of lines. + * @author Nodeca Team + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var TRAILER = "[ \t\u00a0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000]+$"; + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + "Program": function checkTrailingSpaces(node) { + + // Let's hack. Since Esprima does not return whitespace nodes, + // fetch the source code and do black magic via regexps. + + var src = context.getSource(), + re = new RegExp(TRAILER, "mg"), + match, lines, location; + + while ((match = re.exec(src)) !== null) { + lines = src.slice(0, re.lastIndex).split(/\r?\n/g); + + location = { + line: lines.length, + column: lines[lines.length - 1].length - match[0].length + 1 + }; + + // Passing node is a bit dirty, because message data will contain + // big text in `source`. But... who cares :) ? + // One more kludge will not make worse the bloody wizardry of this plugin. + context.report(node, location, "Trailing spaces not allowed."); + } + } + + }; +}; + +},{}],115:[function(require,module,exports){ +/** + * @fileoverview Rule to flag when initializing to undefined + * @author Ilya Volodin + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + return { + + "VariableDeclarator": function(node) { + var name = node.id.name; + var init = node.init && node.init.name; + + if (init === "undefined") { + context.report(node, "It's not necessary to initialize '{{name}}' to undefined.", { name: name }); + } + } + }; + +}; + +},{}],116:[function(require,module,exports){ +/** + * @fileoverview Rule to flag references to undeclared variables. + * @author Mark Macdonald + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +function isImplicitGlobal(variable) { + return variable.defs.every(function(def) { + return def.type === "ImplicitGlobalVariable"; + }); +} + +/** + * Gets the declared variable, defined in `scope`, that `ref` refers to. + * @param {Scope} scope The scope in which to search. + * @param {Reference} ref The reference to find in the scope. + * @returns {Variable} The variable, or null if ref refers to an undeclared variable. + */ +function getDeclaredGlobalVariable(scope, ref) { + var declaredGlobal = null; + scope.variables.some(function(variable) { + if (variable.name === ref.identifier.name) { + // If it's an implicit global, it must have a `writeable` field (indicating it was declared) + if (!isImplicitGlobal(variable) || {}.hasOwnProperty.call(variable, "writeable")) { + declaredGlobal = variable; + return true; + } + } + return false; + }); + return declaredGlobal; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "Program": function(/*node*/) { + + var globalScope = context.getScope(); + + globalScope.through.forEach(function(ref) { + var variable = getDeclaredGlobalVariable(globalScope, ref), + name = ref.identifier.name; + if (!variable) { + context.report(ref.identifier, "'{{name}}' is not defined.", { name: name }); + } else if (ref.isWrite() && variable.writeable === false) { + context.report(ref.identifier, "'{{name}}' is read only.", { name: name }); + } + }); + } + }; + +}; + +},{}],117:[function(require,module,exports){ +/** + * @fileoverview Rule to flag references to the undefined variable. + * @author Michael Ficarra + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "Identifier": function(node) { + if (node.name === "undefined") { + var parent = context.getAncestors().pop(); + if (!parent || parent.type !== "MemberExpression" || node !== parent.property || parent.computed) { + context.report(node, "Unexpected use of undefined."); + } + } + } + }; + +}; + +},{}],118:[function(require,module,exports){ +/** + * @fileoverview Rule to flag trailing underscores in variable declarations. + * @author Matt DuVall + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + //------------------------------------------------------------------------- + // Helpers + //------------------------------------------------------------------------- + + function hasTrailingUnderscore(identifier) { + var len = identifier.length; + + return identifier !== "_" && (identifier[0] === "_" || identifier[len - 1] === "_"); + } + + function isSpecialCaseIdentifierForMemberExpression(identifier) { + return identifier === "__proto__"; + } + + function isSpecialCaseIdentifierInVariableExpression(identifier) { + // Checks for the underscore library usage here + return identifier === "_"; + } + + function checkForTrailingUnderscoreInFunctionDeclaration(node) { + var identifier = node.id.name; + + if (typeof identifier !== "undefined" && hasTrailingUnderscore(identifier)) { + context.report(node, "Unexpected dangling '_' in '" + identifier + "'."); + } + } + + function checkForTrailingUnderscoreInVariableExpression(node) { + var identifier = node.id.name; + + if (typeof identifier !== "undefined" && hasTrailingUnderscore(identifier) && + !isSpecialCaseIdentifierInVariableExpression(identifier)) { + context.report(node, "Unexpected dangling '_' in '" + identifier + "'."); + } + } + + function checkForTrailingUnderscoreInMemberExpression(node) { + var identifier = node.property.name; + + if (typeof identifier !== "undefined" && hasTrailingUnderscore(identifier) && + !isSpecialCaseIdentifierForMemberExpression(identifier)) { + context.report(node, "Unexpected dangling '_' in '" + identifier + "'."); + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + "FunctionDeclaration": checkForTrailingUnderscoreInFunctionDeclaration, + "VariableDeclarator": checkForTrailingUnderscoreInVariableExpression, + "MemberExpression": checkForTrailingUnderscoreInMemberExpression + }; + +}; + +},{}],119:[function(require,module,exports){ +/** + * @fileoverview Checks for unreachable code due to return, throws, break, and continue. + * @author Joel Feenstra + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + + +function report(context, node, unreachableType) { + var keyword; + switch (unreachableType) { + case "BreakStatement": + keyword = "break"; + break; + case "ContinueStatement": + keyword = "continue"; + break; + case "ReturnStatement": + keyword = "return"; + break; + case "ThrowStatement": + keyword = "throw"; + break; + default: + return; + } + context.report(node, "Found unexpected statement after a {{type}}.", { type: keyword }); +} + + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + /** + * Checks if a node is an exception for no-unreachable because of variable/function hoisting + * @param {ASTNode} node The AST node to check. + * @returns {boolean} if the node doesn't trigger unreachable + * @private + */ + function isUnreachableAllowed(node) { + return node.type === "FunctionDeclaration" || + node.type === "VariableDeclaration" && + node.declarations.every(function(declaration) { + return declaration.type === "VariableDeclarator" && declaration.init === null; + }); + } + + /* + * Verifies that the given node is the last node or followed exclusively by + * hoisted declarations + * @param {ASTNode} node Node that should be the last node + * @returns {void} + * @private + */ + function checkNode(node) { + var parent = context.getAncestors().pop(); + var field, i, sibling; + + switch (parent.type) { + case "SwitchCase": + field = "consequent"; + break; + case "Program": + case "BlockStatement": + field = "body"; + break; + default: + return; + } + + for (i = parent[field].length - 1; i >= 0; i--) { + sibling = parent[field][i]; + if (sibling === node) { + return; // Found the last reachable statement, all done + } + + if (!isUnreachableAllowed(sibling)) { + report(context, sibling, node.type); + } + } + } + + return { + "ReturnStatement": checkNode, + "ThrowStatement": checkNode, + "ContinueStatement": checkNode, + "BreakStatement": checkNode + }; + +}; + +},{}],120:[function(require,module,exports){ +/** + * @fileoverview Flag expressions in statement position that do not side effect + * @author Michael Ficarra + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + /** + * @param {ASTNode} node - any node + * @returns {Boolean} whether the given node structurally represents a directive + */ + function looksLikeDirective(node) { + return node.type === "ExpressionStatement" && + node.expression.type === "Literal" && typeof node.expression.value === "string"; + } + + /** + * @param {Function} predicate - ([a] -> Boolean) the function used to make the determination + * @param {a[]} list - the input list + * @returns {a[]} the leading sequence of members in the given list that pass the given predicate + */ + function takeWhile(predicate, list) { + for (var i = 0, l = list.length; i < l; ++i) { + if (!predicate(list[i])) { + break; + } + } + return [].slice.call(list, 0, i); + } + + /** + * @param {ASTNode} node - a Program or BlockStatement node + * @returns {ASTNode[]} the leading sequence of directive nodes in the given node's body + */ + function directives(node) { + return takeWhile(looksLikeDirective, node.body); + } + + /** + * @param {ASTNode} node - any node + * @param {ASTNode[]} ancestors - the given node's ancestors + * @returns {Boolean} whether the given node is considered a directive in its current position + */ + function isDirective(node, ancestors) { + var parent = ancestors[ancestors.length - 1], + grandparent = ancestors[ancestors.length - 2]; + return (parent.type === "Program" || parent.type === "BlockStatement" && (grandparent.type === "FunctionExpression" || grandparent.type === "FunctionDeclaration")) && + directives(parent).indexOf(node) >= 0; + } + + return { + "ExpressionStatement": function(node) { + + var type = node.expression.type, + ancestors = context.getAncestors(); + + if ( + !/^(?:Assignment|Call|New|Update)Expression$/.test(type) && + (type !== "UnaryExpression" || ["delete", "void"].indexOf(node.expression.operator) < 0) && + !isDirective(node, ancestors) + ) { + context.report(node, "Expected an assignment or function call and instead saw an expression."); + } + } + }; + +}; + +},{}],121:[function(require,module,exports){ +/** + * @fileoverview Rule to flag declared but unused variables + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var config = { + vars: "all", + args: "after-used" + }; + + if (context.options[0]) { + if (typeof(context.options[0]) === "string") { + config.vars = context.options[0]; + } else { + config.vars = context.options[0].vars || config.vars; + config.args = context.options[0].args || config.args; + } + } + + var MESSAGE = "{{name}} is defined but never used"; + + /** + * @param {Reference} ref - an escope Reference + * @returns {Boolean} whether the given reference represents a read operation + */ + function isReadRef(ref) { + return ref.isRead(); + } + + /** + * @param {Scope} scope - an escope Scope object + * @returns {Variable[]} most of the local variables with no read references + */ + function unusedLocals(scope) { + var unused = []; + var variables = scope.variables; + if (scope.type !== "global") { + for (var i = 0, l = variables.length; i < l; ++i) { + // skip function expression names + if (scope.functionExpressionScope) { + continue; + } + // skip implicit "arguments" variable + if (scope.type === "function" && variables[i].name === "arguments" && variables[i].identifiers.length === 0) { + continue; + } + var type = variables[i].defs[0].type; + // skip catch variables + if (type === "CatchClause") { + continue; + } + // if "args" option is "none", skip any parameter + if (config.args === "none" && type === "Parameter") { + continue; + } + // if "args" option is "after-used", skip all but the last parameter + if (config.args === "after-used" && type === "Parameter" && variables[i].defs[0].index < variables[i].defs[0].node.params.length - 1) { + continue; + } + if (variables[i].references.filter(isReadRef).length === 0) { + unused.push(variables[i]); + } + } + } + return [].concat.apply(unused, [].map.call(scope.childScopes, unusedLocals)); + } + + return { + "Program": function(programNode) { + var globalScope = context.getScope(); + var unused = unusedLocals(globalScope); + var i, l; + + // determine unused globals + if (config.vars === "all") { + var unresolvedRefs = globalScope.through.filter(isReadRef).map(function(ref) { + return ref.identifier.name; + }); + for (i = 0, l = globalScope.variables.length; i < l; ++i) { + if (unresolvedRefs.indexOf(globalScope.variables[i].name) < 0) { + unused.push(globalScope.variables[i]); + } + } + } + + for (i = 0, l = unused.length; i < l; ++i) { + if (unused[i].eslintExplicitGlobal) { + context.report(programNode, MESSAGE, unused[i]); + } else if (unused[i].defs.length > 0) { + context.report(unused[i].identifiers[0], MESSAGE, unused[i]); + } + } + } + }; + +}; + +},{}],122:[function(require,module,exports){ +/** + * @fileoverview Rule to flag use of variables before they are defined + * @author Ilya Volodin + */ + +//------------------------------------------------------------------------------ +// Constants +//------------------------------------------------------------------------------ + +var NO_FUNC = "nofunc"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + function findDeclaration(name, scope) { + // try searching in the current scope first + for (var i = 0, l = scope.variables.length; i < l; i++) { + if (scope.variables[i].name === name) { + return scope.variables[i]; + } + } + // check if there's upper scope and call recursivly till we find the variable + if (scope.upper) { + return findDeclaration(name, scope.upper); + } + } + + function findVariables() { + var scope = context.getScope(); + var typeOption = context.options[0]; + + function checkLocationAndReport(reference, declaration) { + if (typeOption !== NO_FUNC || declaration.defs[0].type !== "FunctionName") { + if (declaration.identifiers[0].range[1] > reference.identifier.range[1]) { + context.report(reference.identifier, "{{a}} was used before it was defined", {a: reference.identifier.name}); + } + } + } + + scope.references.forEach(function(reference) { + // if the reference is resolved check for declaration location + // if not, it could be function invocation, try to find manually + if (reference.resolved && reference.resolved.identifiers.length > 0) { + checkLocationAndReport(reference, reference.resolved); + } else { + var declaration = findDeclaration(reference.identifier.name, scope); + // if there're no identifiers, this is a global environment variable + if (declaration && declaration.identifiers.length !== 0) { + checkLocationAndReport(reference, declaration); + } + } + }); + } + + return { + "Program": findVariables, + "FunctionExpression": findVariables, + "FunctionDeclaration": findVariables + }; +}; + +},{}],123:[function(require,module,exports){ +/** + * @fileoverview Rule to disallow use of void operator. + * @author Mike Sidorov + * @copyright 2014 Mike Sidorov. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + "UnaryExpression": function(node) { + if (node.operator === "void") { + context.report(node, "Expected 'undefined' and instead saw 'void'."); + } + } + }; + +}; + +},{}],124:[function(require,module,exports){ +/** + * @fileoverview Rule that warns about used warning comments + * @author Alexander Schmidt + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function (context) { + "use strict"; + + var configuration = context.options[0] || {}, + warningTerms = configuration.terms || ["todo", "fixme", "xxx"], + location = configuration.location || "start"; + + /** + * Prepares a specified comment for being checked. + * @param {String} comment The comment to prepare. + * @returns {String} The specified comment prepared for being checked. + */ + function prepareCommentForChecking(comment) { + var commentToCheck; + + commentToCheck = comment.toLowerCase(); + commentToCheck = commentToCheck.trim(); + + return commentToCheck; + } + + /** + * Checks if the specified comment starts with a specified term. + * @param {String} commentToCheck The comment to check. + * @param {String} lowerCaseTerm The term to search for. + * @returns {Boolean} True if the comment started with the specified term, else false. + */ + function commentStartsWithTerm(commentToCheck, lowerCaseTerm) { + return commentToCheck.indexOf(lowerCaseTerm) === 0; + } + + /** + * Checks if the specified comment contains a specified term at any location. + * @param {String} commentToCheck The comment to check. + * @param {String} lowerCaseTerm The term to search for. + * @returns {Boolean} True if the term was contained in the comment, else false. + */ + function commentContainsTerm(commentToCheck, lowerCaseTerm) { + return commentToCheck.indexOf(lowerCaseTerm) !== -1; + } + + + /** + * Checks the specified comment for matches of the configured warning terms and returns the matches. + * @param {String} comment The comment which is checked. + * @returns {Array} All matched warning terms for this comment. + */ + function commentContainsWarningTerm(comment) { + var matches = []; + + warningTerms.forEach(function (term) { + var lowerCaseTerm = term.toLowerCase(), + commentToCheck = prepareCommentForChecking(comment); + + if (location === "start") { + if (commentStartsWithTerm(commentToCheck, lowerCaseTerm)) { + matches.push(term); + } + } else if (location === "anywhere") { + if (commentContainsTerm(commentToCheck, lowerCaseTerm)) { + matches.push(term); + } + } + }); + + return matches; + } + + /** + * Checks the specified node for matching warning comments and reports them. + * @param {ASTNode} node The AST node being checked. + * @returns {void} undefined. + */ + function checkComment(node) { + var matches = commentContainsWarningTerm(node.value); + + matches.forEach(function (matchedTerm) { + context.report(node, "Unexpected " + matchedTerm + " comment."); + }); + } + + return { + "BlockComment": checkComment, + "LineComment": checkComment + }; +}; + +},{}],125:[function(require,module,exports){ +/** + * @fileoverview Rule to flag use of with statement + * @author Nicholas C. Zakas + */ + + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + return { + "WithStatement": function(node) { + context.report(node, "Unexpected use of 'with' statement."); + } + }; + +}; + +},{}],126:[function(require,module,exports){ +/** + * @fileoverview Rule to flag wrapping none-iffe in parens + * @author Ilya Volodin + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + return { + + "FunctionExpression": function(node) { + var ancestors = context.getAncestors(), + previousToken, nextToken; + + if (!/CallExpression|NewExpression/.test(ancestors.pop().type)) { + previousToken = context.getTokenBefore(node); + nextToken = context.getTokenAfter(node); + if (previousToken.value === "(" && nextToken.value === ")") { + context.report(node, "Wrapping non-IIFE function literals in parens is unnecessary."); + } + } + } + }; + +}; + +},{}],127:[function(require,module,exports){ +/** + * @fileoverview A rule to ensure the use of a single variable declaration. + * @author Ian Christian Myers + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + var functionStack = []; + + function startFunction() { + functionStack.push(false); + } + + function endFunction() { + functionStack.pop(); + } + + function checkDeclarations(node) { + if (functionStack[functionStack.length - 1]) { + context.report(node, "Combine this with the previous 'var' statement."); + } else { + functionStack[functionStack.length - 1] = true; + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + "Program": startFunction, + "FunctionDeclaration": startFunction, + "FunctionExpression": startFunction, + + "VariableDeclaration": checkDeclarations, + + "Program:exit": endFunction, + "FunctionDeclaration:exit": endFunction, + "FunctionExpression:exit": endFunction + }; + +}; + +},{}],128:[function(require,module,exports){ +/** + * @fileoverview A rule to ensure blank lines within blocks. + * @author Mathias Schreck + * @copyright 2014 Mathias Schreck. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function (context) { + var requirePadding = context.options[0] !== "never"; + + /** + * Checks if the given non empty block node has a blank line before its first child node. + * @param {ASTNode} node The AST node of a BlockStatement. + * @returns {boolean} Whether or not the block starts with a blank line. + */ + function isNonEmptyBlockTopPadded(node) { + var blockStart = node.loc.start.line, + first = node.body[0], + firstLine = first.loc.start.line, + expectedFirstLine = blockStart + 2, + leadingComments = context.getComments(first).leading; + + if (leadingComments.length > 0) { + firstLine = leadingComments[0].loc.start.line; + } + + return expectedFirstLine <= firstLine; + } + + /** + * Checks if the given non empty block node has a blank line after its last child node. + * @param {ASTNode} node The AST node of a BlockStatement. + * @returns {boolean} Whether or not the block ends with a blank line. + */ + function isNonEmptyBlockBottomPadded(node) { + var blockEnd = node.loc.end.line, + last = node.body[node.body.length - 1], + lastLine = last.loc.end.line, + expectedLastLine = blockEnd - 2, + trailingComments = context.getComments(last).trailing; + + if (trailingComments.length > 0) { + lastLine = trailingComments[trailingComments.length - 1].loc.end.line; + } + + return lastLine <= expectedLastLine; + } + + /** + * Checks if the given non empty block node starts AND ends with a blank line. + * @param {ASTNode} node The AST node of a BlockStatement. + * @returns {boolean} Whether or not the block starts and ends with a blank line. + */ + function isNonEmptyBlockPadded(node) { + return isNonEmptyBlockTopPadded(node) && isNonEmptyBlockBottomPadded(node); + } + + /** + * Checks if the given non empty block node starts OR ends with a blank line. + * @param {ASTNode} node The AST node of a BlockStatement. + * @returns {boolean} Whether or not the block starts and ends with a blank line. + */ + function hasNonEmptyBlockExtraPadding(node) { + return isNonEmptyBlockTopPadded(node) || isNonEmptyBlockBottomPadded(node); + } + + /** + * Checks the given BlockStatement node to be padded if the block is not empty. + * @param {ASTNode} node The AST node of a BlockStatement. + * @returns {void} undefined. + */ + function checkPadding(node) { + if (node.body.length > 0) { + if (requirePadding) { + if (!isNonEmptyBlockPadded(node)) { + context.report(node, "Block must be padded by blank lines."); + } + } else { + if (hasNonEmptyBlockExtraPadding(node)) { + context.report(node, "Block must not be padded by blank lines."); + } + } + } + } + + return { + "BlockStatement": checkPadding + }; + +}; + +},{}],129:[function(require,module,exports){ +/** + * @fileoverview Rule to flag non-quoted property names in object literals. + * @author Mathias Bynens + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +var esprima = require("esprima"); + +module.exports = function(context) { + + "use strict"; + + var MODE = context.options[0]; + + switch (MODE) { + + case "as-needed": + return { + Property: function(node) { + var key = node.key; + // Ensure that any quoted property names required quoting + if (key.type === "Literal" && typeof key.value === "string") { + try { + var tokens = esprima.tokenize(key.value); + if (tokens.length !== 1) { + return; + } + var t = tokens[0]; + } catch(e) { + return; + } + if (t.type === "Identifier" || t.type === "Null" || t.type === "Boolean" || t.type === "Numeric" && "" + +t.value === t.value) { + context.report(node, "Unnecessarily quoted property `{{name}}` found.", key); + } + } + } + }; + + default: + return { + Property: function(node) { + var key = node.key; + // Ensure all property names are quoted + if (key.type !== "Literal" || typeof key.value !== "string") { + context.report(node, "Unquoted property `{{name}}` found.", key); + } + } + }; + + } + +}; + +},{"esprima":6}],130:[function(require,module,exports){ +/** + * @fileoverview A rule to choose between single and double quote marks + * @author Matt DuVall , Brandon Payton + */ + +//------------------------------------------------------------------------------ +// Constants +//------------------------------------------------------------------------------ + +var QUOTE_SETTINGS = { + "double": { + quote: "\"", + alternateQuote: "'", + description: "doublequote" + }, + "single": { + quote: "'", + alternateQuote: "\"", + description: "singlequote" + } +}; + +var AVOID_ESCAPE = "avoid-escape"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + /** + * Validate that a string passed in is surrounded by the specified character + * @param {string} val The text to check. + * @param {string} character The character to see if it's surrounded by. + * @returns {boolean} True if the text is surrounded by the character, false if not. + */ + function isSurroundedBy(val, character) { + return val[0] === character && val[val.length - 1] === character; + } + + return { + + "Literal": function(node) { + var val = node.value, + rawVal = node.raw, + quoteOption = context.options[0], + settings = QUOTE_SETTINGS[quoteOption], + avoidEscape = context.options[1] === AVOID_ESCAPE, + isValid; + + if (settings && typeof val === "string") { + isValid = isSurroundedBy(rawVal, settings.quote); + + if (!isValid && avoidEscape) { + isValid = isSurroundedBy(rawVal, settings.alternateQuote) && rawVal.indexOf(settings.quote) >= 0; + } + + if (!isValid) { + context.report(node, "Strings must use " + settings.description + "."); + } + } + } + }; + +}; + +},{}],131:[function(require,module,exports){ +/** + * @fileoverview Rule to flag use of parseInt without a radix argument + * @author James Allardice + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + return { + "CallExpression": function(node) { + + var radix; + + if (node.callee.name === "parseInt") { + + if (node.arguments.length < 2) { + context.report(node, "Missing radix parameter."); + } else { + + radix = node.arguments[1]; + + // don't allow non-numeric literals or undefined + if ((radix.type === "Literal" && typeof radix.value !== "number") || + (radix.type === "Identifier" && radix.name === "undefined") + ) { + context.report(node, "Invalid radix parameter."); + } + } + + } + } + }; + +}; + +},{}],132:[function(require,module,exports){ +/** + * @fileoverview Rule to flag missing semicolons. + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ +module.exports = function(context) { + + var OPT_OUT_PATTERN = /[\[\(\/\+\-]/; + + var always = context.options[0] !== "never"; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Checks a node to see if it's followed by a semicolon. + * @param {ASTNode} node The node to check. + * @returns {void} + */ + function checkForSemicolon(node) { + var lastToken = context.getLastToken(node), + nextToken = context.getTokenAfter(node); + + if (always) { + if (lastToken.type !== "Punctuator" || lastToken.value !== ";") { + context.report(node, lastToken.loc.end, "Missing semicolon."); + } + } else { + if (lastToken.type === "Punctuator" && lastToken.value === ";") { + + if (!nextToken || !(OPT_OUT_PATTERN.test(nextToken.value))) { + context.report(node, node.loc.end, "Extra semicolon."); + } + + } + } + } + + /** + * Checks to see if there's a semicolon after a variable declaration. + * @param {ASTNode} node The node to check. + * @returns {void} + */ + function checkForSemicolonForVariableDeclaration(node) { + + var ancestors = context.getAncestors(), + parentIndex = ancestors.length - 1, + parent = ancestors[parentIndex]; + + if ((parent.type !== "ForStatement" || parent.init !== node) && + (parent.type !== "ForInStatement" || parent.left !== node) + ) { + checkForSemicolon(node); + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + + "VariableDeclaration": checkForSemicolonForVariableDeclaration, + "ExpressionStatement": checkForSemicolon, + "ReturnStatement": checkForSemicolon, + "DebuggerStatement": checkForSemicolon, + "BreakStatement": checkForSemicolon, + "ContinueStatement": checkForSemicolon, + "EmptyStatement": function (node) { + var nextToken; + + if (!always) { + nextToken = context.getTokenAfter(node) || context.getLastToken(node); + + if (!(OPT_OUT_PATTERN.test(nextToken.value))) { + context.report(node, "Extra semicolon."); + } + } + + + } + }; + +}; + +},{}],133:[function(require,module,exports){ +/** + * @fileoverview Rule to require sorting of variables within a single Variable Declaration block + * @author Ilya Volodin + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + var configuration = context.options[0] || {}, + ignoreCase = configuration.ignoreCase || false; + + return { + "VariableDeclaration": function(node) { + node.declarations.reduce(function(memo, decl) { + var lastVariableName = memo.id.name, + currenVariableName = decl.id.name; + + if (ignoreCase) { + lastVariableName = lastVariableName.toLowerCase(); + currenVariableName = currenVariableName.toLowerCase(); + } + + if (currenVariableName < lastVariableName) { + context.report(decl, "Variables within the same declaration block should be sorted alphabetically"); + return memo; + } else { + return decl; + } + }, node.declarations[0]); + } + }; +}; + +},{}],134:[function(require,module,exports){ +/** + * @fileoverview Rule to enforce the number of spaces after certain keywords + * @author Nick Fisher + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + // unless the first option is `"never"`, then a space is required + var requiresSpace = context.options[0] !== "never", + config = context.options[1] || { checkFunctionKeyword: false }; + + /** + * Check if the separation of two adjacent tokens meets the spacing rules, and report a problem if not. + * + * @param {ASTNode} node The node to which the potential problem belongs. + * @param {Token} left The first token. + * @param {Token} right The second token + * @returns {void} + */ + function checkTokens(node, left, right) { + var hasSpace = left.range[1] < right.range[0], + value = left.value; + + if (hasSpace !== requiresSpace) { + context.report(node, "Keyword \"{{value}}\" must {{not}}be followed by whitespace.", { + value: value, + not: requiresSpace ? "" : "not " + }); + } + } + + /** + * Check if the given node (`if`, `for`, `while`, etc), has the correct spacing after it. + * @param {ASTNode} node The node to check. + * @returns {void} + */ + function check(node) { + var tokens = context.getFirstTokens(node, 2); + checkTokens(node, tokens[0], tokens[1]); + } + + return { + "IfStatement": function (node) { + check(node); + // check the `else` + if (node.alternate && node.alternate.type !== "IfStatement") { + checkTokens(node.alternate, context.getTokenBefore(node.alternate), context.getFirstToken(node.alternate)); + } + }, + "ForStatement": check, + "ForOfStatement": check, + "ForInStatement": check, + "WhileStatement": check, + "DoWhileStatement": function (node) { + check(node); + // check the `while` + var whileTokens = context.getTokensBefore(node.test, 2); + checkTokens(node, whileTokens[0], whileTokens[1]); + }, + "SwitchStatement": check, + "TryStatement": function (node) { + check(node); + // check the `finally` + if (node.finalizer) { + checkTokens(node.finalizer, context.getTokenBefore(node.finalizer), context.getFirstToken(node.finalizer)); + } + }, + "CatchStatement": check, + "WithStatement": check, + "FunctionExpression": function (node) { + if (config.checkFunctionKeyword) { + check(node); + } + } + }; +}; + +},{}],135:[function(require,module,exports){ +/** + * @fileoverview A rule to ensure whitespace before blocks. + * @author Mathias Schreck + * @copyright 2014 Mathias Schreck. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function (context) { + var requireSpace = context.options[0] !== "never"; + + /** + * Determines whether two adjacent tokens are have whitespace between them. + * @param {Object} left - The left token object. + * @param {Object} right - The right token object. + * @returns {boolean} Whether or not there is space between the tokens. + */ + function isSpaced(left, right) { + return left.range[1] < right.range[0]; + } + + /** + * Determines whether two adjacent tokens are on the same line. + * @param {Object} left - The left token object. + * @param {Object} right - The right token object. + * @returns {boolean} Whether or not the tokens are on the same line. + */ + function isSameLine(left, right) { + return left.loc.start.line === right.loc.start.line; + } + + /** + * Checks the given BlockStatement node has a preceding space if it doesn’t start on a new line. + * @param {ASTNode} node The AST node of a BlockStatement. + * @returns {void} undefined. + */ + function checkPrecedingSpace(node) { + var precedingToken = context.getTokenBefore(node), + hasSpace; + + if (precedingToken && isSameLine(precedingToken, node)) { + hasSpace = isSpaced(precedingToken, node); + + if (requireSpace) { + if (!hasSpace) { + context.report(node, "Missing space before opening brace."); + } + } else { + if (hasSpace) { + context.report(node, "Unexpected space before opening brace."); + } + } + } + } + + return { + "BlockStatement": checkPrecedingSpace + }; + +}; + +},{}],136:[function(require,module,exports){ +/** + * @fileoverview Disallows or enforces spaces inside of brackets. + * @author Ian Christian Myers + * @copyright 2014 Brandyn Bennett. All rights reserved. + * @copyright 2014 Michael Ficarra. No rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var options = { + spaced: context.options[0] === "always", + singleElementException: context.options[1] != null && !!context.options[1].singleValue, + objectsInArraysException: context.options[1] != null && !!context.options[1].objectsInArrays, + arraysInArraysException: context.options[1] != null && !!context.options[1].arraysInArrays, + propertyName: context.options[1] == null || context.options[1].propertyName == null || !!context.options[1].propertyName + }; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Determines whether two adjacent tokens are have whitespace between them. + * @param {Object} left - The left token object. + * @param {Object} right - The right token object. + * @returns {boolean} Whether or not there is space between the tokens. + */ + function isSpaced(left, right) { + return left.range[1] < right.range[0]; + } + + /** + * Determines whether two adjacent tokens are on the same line. + * @param {Object} left - The left token object. + * @param {Object} right - The right token object. + * @returns {boolean} Whether or not the tokens are on the same line. + */ + function isSameLine(left, right) { + return left.loc.start.line === right.loc.start.line; + } + + /** + * Reports that there shouldn't be a space after the first token + * @param {ASTNode} node - The node to report in the event of an error. + * @param {Object[]} tokens - The tokens to be checked for spacing. + * @returns {void} + */ + function reportNoBeginningSpace(node, tokens) { + context.report(node, tokens[0].loc.start, + "There should be no space after '" + tokens[0].value + "'"); + } + + /** + * Reports that there shouldn't be a space before the last token + * @param {ASTNode} node - The node to report in the event of an error. + * @param {Object[]} tokens - The tokens to be checked for spacing. + * @returns {void} + */ + function reportNoEndingSpace(node, tokens) { + context.report(node, tokens[tokens.length - 1].loc.start, + "There should be no space before '" + tokens[tokens.length - 1].value + "'"); + } + + /** + * Reports that there should be a space after the first token + * @param {ASTNode} node - The node to report in the event of an error. + * @param {Object[]} tokens - The tokens to be checked for spacing. + * @returns {void} + */ + function reportRequiredBeginningSpace(node, tokens) { + context.report(node, tokens[0].loc.start, + "A space is required after '" + tokens[0].value + "'"); + } + + /** + * Reports that there should be a space before the last token + * @param {ASTNode} node - The node to report in the event of an error. + * @param {Object[]} tokens - The tokens to be checked for spacing. + * @returns {void} + */ + function reportRequiredEndingSpace(node, tokens) { + context.report(node, tokens[tokens.length - 1].loc.start, + "A space is required before '" + tokens[tokens.length - 1].value + "'"); + } + + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + MemberExpression: options.propertyName ? function checkMember(node) { + if (node.computed) { + var tokens = context.getTokens(node.property, 1, 1); + var tokenA = tokens[0], tokenB = tokens[1], + tokenC = tokens[tokens.length - 2], tokenD = tokens[tokens.length - 1]; + if (isSameLine(tokenA, tokenB) || isSameLine(tokenC, tokenD)) { + if (options.spaced) { + if (!isSpaced(tokenA, tokenB) && isSameLine(tokenA, tokenB)) { + reportRequiredBeginningSpace(node, tokens); + } + if (!isSpaced(tokenC, tokenD) && isSameLine(tokenC, tokenD)) { + reportRequiredEndingSpace(node, tokens); + } + } else { + if (isSpaced(tokenA, tokenB)) { + reportNoBeginningSpace(node, tokens); + } + if (isSpaced(tokenC, tokenD)) { + reportNoEndingSpace(node, tokens); + } + } + } + } + } : function() {}, + + ArrayExpression: function(node) { + if (node.elements.length === 0) { + return; + } + var tokens = context.getTokens(node); + var tokenA = tokens[0], tokenB = tokens[1], + tokenC = tokens[tokens.length - 2], tokenD = tokens[tokens.length - 1]; + + var openingBracketMustBeSpaced = + options.objectsInArraysException && tokenB.value === "{" || + options.arraysInArraysException && tokenB.value === "[" || + options.singleElementException && node.elements.length === 1 + ? !options.spaced : options.spaced; + + var closingBracketMustBeSpaced = + options.objectsInArraysException && tokenC.value === "}" || + options.arraysInArraysException && tokenC.value === "]" || + options.singleElementException && node.elements.length === 1 + ? !options.spaced : options.spaced; + + if (isSameLine(tokenA, tokenB) || isSameLine(tokenC, tokenD)) { + if (openingBracketMustBeSpaced && !isSpaced(tokenA, tokenB)) { + reportRequiredBeginningSpace(node, tokens); + } else if (!openingBracketMustBeSpaced && isSpaced(tokenA, tokenB)) { + reportNoBeginningSpace(node, tokens); + } + if (closingBracketMustBeSpaced && !isSpaced(tokenC, tokenD)) { + reportRequiredEndingSpace(node, tokens); + } else if (!closingBracketMustBeSpaced && isSpaced(tokenC, tokenD)) { + reportNoEndingSpace(node, tokens); + } + } + }, + + ObjectExpression: function(node) { + if (node.properties.length === 0) { + return; + } + var tokens = context.getTokens(node); + var tokenA = tokens[0], tokenB = tokens[1], + tokenC = tokens[tokens.length - 2], tokenD = tokens[tokens.length - 1]; + if (isSameLine(tokenA, tokenB) || isSameLine(tokenC, tokenD)) { + if (options.spaced) { + if (!isSpaced(tokenA, tokenB)) { + reportRequiredBeginningSpace(node, tokens); + } + if (!isSpaced(tokenC, tokenD)) { + reportRequiredEndingSpace(node, tokens); + } + } else { + if (isSpaced(tokenA, tokenB)) { + reportNoBeginningSpace(node, tokens); + } + if (isSpaced(tokenC, tokenD)) { + reportNoEndingSpace(node, tokens); + } + } + } + } + + }; + +}; + +},{}],137:[function(require,module,exports){ +/** + * @fileoverview Disallows or enforces spaces inside of parentheses. + * @author Jonathan Rajavuori + * @copyright 2014 Jonathan Rajavuori. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var RE, MESSAGE; + + if (context.options[0] === "always") { + RE = /\([^ \)]|[^ \(]\)/mg; + MESSAGE = "There must be a space inside this paren."; + } else { + RE = /\( | \)/mg; + MESSAGE = "There should be no spaces inside this paren."; + } + + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + var skipRanges = []; + + /** + * Adds the range of a node to the set to be skipped when checking parens + * @param {ASTNode} node The node to skip + * @returns {void} + * @private + */ + function addSkipRange(node) { + skipRanges.push(node.range); + } + + /** + * Sorts the skipRanges array. Must be called before shouldSkip + * @returns {void} + * @private + */ + function sortSkipRanges() { + skipRanges.sort(function (a, b) { + return a[0] - b[0]; + }); + } + + /** + * Checks if a certain position in the source should be skipped + * @param {Number} pos The 0-based index in the source + * @returns {boolean} whether the position should be skipped + * @private + */ + function shouldSkip(pos) { + var i, len, range; + for (i = 0, len = skipRanges.length; i < len; i += 1) { + range = skipRanges[i]; + if (pos < range[0]) { + break; + } else if (pos < range[1]) { + return true; + } + } + return false; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + "Program:exit": function checkParenSpaces(node) { + + var match, + nextLine, + column, + line = 1, + source = context.getSource(), + pos = 0; + + sortSkipRanges(); + + while ((match = RE.exec(source)) !== null) { + if (source.charAt(match.index) !== "(") { + // Matched a closing paren pattern + match.index += 1; + } + + if (!shouldSkip(match.index)) { + while ((nextLine = source.indexOf("\n", pos)) !== -1 && nextLine < match.index) { + pos = nextLine + 1; + line += 1; + } + column = match.index - pos; + + context.report(node, { line: line, column: column }, MESSAGE); + } + } + + }, + + + // These nodes can contain parentheses that this rule doesn't care about + + LineComment: addSkipRange, + + BlockComment: addSkipRange, + + Literal: addSkipRange + + }; + +}; + +},{}],138:[function(require,module,exports){ +/** + * @fileoverview Require spaces around infix operators + * @author Michael Ficarra + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var OPERATORS = [ + "*", "/", "%", "+", "-", "<<", ">>", ">>>", "<", "<=", ">", ">=", "in", + "instanceof", "==", "!=", "===", "!==", "&", "^", "|", "&&", "||", "=", + "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", "&=", "^=", "|=", + "?", ":", "," + ]; + + function isSpaced(left, right) { + var op, tokens = context.getTokens({range: [left.range[1], right.range[0]]}, 1, 1); + for (var i = 1, l = tokens.length - 1; i < l; ++i) { + op = tokens[i]; + if ( + op.type === "Punctuator" && + OPERATORS.indexOf(op.value) >= 0 && + (tokens[i - 1].range[1] >= op.range[0] || op.range[1] >= tokens[i + 1].range[0]) + ) { + return false; + } + } + return true; + } + + function isRightSpaced(left, right) { + var op, tokens = context.getTokens({range: [left.range[1], right.range[0]]}, 1, 1); + for (var i = 1, l = tokens.length - 1; i < l; ++i) { + op = tokens[i]; + if ( + op.type === "Punctuator" && + OPERATORS.indexOf(op.value) >= 0 && + op.range[1] >= tokens[i + 1].range[0] + ) { + return false; + } + } + return true; + } + + function report(node) { + context.report(node, "Infix operators must be spaced."); + } + + function checkBinary(node) { + if (!isSpaced(node.left, node.right)) { + report(node); + } + } + + function checkSequence(node) { + for (var i = 0, l = node.expressions.length - 1; i < l; ++i) { + if (!isRightSpaced(node.expressions[i], node.expressions[i + 1])) { + report(node); + break; + } + } + } + + function checkConditional(node) { + if (!isSpaced(node.test, node.consequent) || !isSpaced(node.consequent, node.alternate)) { + report(node); + } + } + + function checkVar(node) { + if (node.init && !isSpaced(node.id, node.init)) { + report(node); + } + } + + return { + "AssignmentExpression": checkBinary, + "BinaryExpression": checkBinary, + "LogicalExpression": checkBinary, + "ConditionalExpression": checkConditional, + "SequenceExpression": checkSequence, + "VariableDeclarator": checkVar + }; + +}; + +},{}],139:[function(require,module,exports){ +/** + * @fileoverview Require spaces following return, throw, and case + * @author Michael Ficarra + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + function check(node) { + var tokens = context.getFirstTokens(node, 2), + value = tokens[0].value; + + if (tokens[0].range[1] >= tokens[1].range[0]) { + context.report(node, "Keyword \"" + value + "\" must be followed by whitespace."); + } + } + + return { + "ReturnStatement": function(node) { + if (node.argument) { + check(node); + } + }, + "SwitchCase": function(node) { + if (node.test) { + check(node); + } + }, + "ThrowStatement": check + }; + +}; + +},{}],140:[function(require,module,exports){ +/** + * @fileoverview Require spaces following unary word operators + * @author Michael Ficarra + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + function check(node) { + var tokens; + tokens = context.getFirstTokens(node, 2); + if (tokens[0].range[1] >= tokens[1].range[0]) { + switch (tokens[0].value) { + case "delete": + case "new": + case "typeof": + case "void": + context.report(node, "Unary word operator \"" + tokens[0].value + "\" must be followed by whitespace."); + break; + // no default + } + } + } + + return { + "NewExpression": check, + "UnaryExpression": check + }; + +}; + +},{}],141:[function(require,module,exports){ +/** + * @fileoverview Enforces or disallows a space beginning a single-line comment. + * @author Greg Cochard + * @copyright 2014 Greg Cochard. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + // Unless the first option is never, require a space + var requireSpace = context.options[0] !== "never"; + + // Default to match anything, so all will fail if there are no exceptions + var exceptionMatcher = new RegExp(" "); + + // Grab the exceptions array and build a RegExp matcher for it + var hasExceptions = context.options.length === 2; + var unescapedExceptions = hasExceptions ? context.options[1].exceptions : []; + var exceptions; + + if (unescapedExceptions.length) { + exceptions = unescapedExceptions.map(function(s) { + return s.replace(/([.*+?${}()|\^\[\]\/\\])/g, "\\$1"); + }); + exceptionMatcher = new RegExp("(^(" + exceptions.join(")+$)|(^(") + ")+$)"); + } + + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + "LineComment": function checkCommentForSpace(node) { + + if (node.loc.start.line === 1 && /^#!/.test(context.getSourceLines()[0])) { + + /* + * HACK: return if we are on the first line and + * encounter a shebang at the beginning. + * It seems the parser will return this as a + * comment and filter out the # so we must fetch + * the actual source line. Is this being caused + * by esprima or eslint? Something else? + */ + return; + } + + if (requireSpace) { + + // Space expected and not found + if (node.value.indexOf(" ") !== 0) { + + /* + * Do two tests; one for space starting the line, + * and one for a comment comprised only of exceptions + */ + if (hasExceptions && !exceptionMatcher.test(node.value)) { + context.report(node, "Expected exception block or space after // in comment."); + } else if (!hasExceptions) { + context.report(node, "Expected space after // in comment."); + } + } + + } else { + + if (node.value.indexOf(" ") === 0) { + context.report(node, "Unexpected space after // in comment."); + } + } + } + + }; +}; + +},{}],142:[function(require,module,exports){ +/** + * @fileoverview Rule to ensure code is running in strict mode. + * @author Nicholas C. Zakas + * @copyright 2013-2014 Nicholas C. Zakas. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var scopes = []; + + /** + * Determines if a given node is "use strict". + * @param {ASTNode} node The node to check. + * @returns {boolean} True if the node is a strict pragma, false if not. + * @void + */ + function isStrictPragma(node) { + return (node && node.type === "ExpressionStatement" && + node.expression.value === "use strict"); + } + + /** + * When you enter a scope, push the strict value from the previous scope + * onto the stack. + * @param {ASTNode} node The AST node being checked. + * @returns {void} + * @private + */ + function enterScope(node) { + + var isStrict = false, + isProgram = (node.type === "Program"), + isParentGlobal = scopes.length === 1, + isParentStrict = scopes.length ? scopes[scopes.length - 1] : false; + + // look for the "use strict" pragma + if (isProgram) { + isStrict = isStrictPragma(node.body[0]) || isParentStrict; + } else { + isStrict = isStrictPragma(node.body.body[0]) || isParentStrict; + } + + scopes.push(isStrict); + + // never warn if the parent is strict or the function is strict + if (!isParentStrict && !isStrict && isParentGlobal) { + context.report(node, "Missing \"use strict\" statement."); + } + } + + /** + * When you exit a scope, pop off the top scope and see if it's true or + * false. + * @returns {void} + * @private + */ + function exitScope() { + scopes.pop(); + } + + return { + + "Program": enterScope, + "FunctionDeclaration": enterScope, + "FunctionExpression": enterScope, + + "Program:exit": exitScope, + "FunctionDeclaration:exit": exitScope, + "FunctionExpression:exit": exitScope + }; + +}; + +},{}],143:[function(require,module,exports){ +/** + * @fileoverview Rule to flag comparisons to the value NaN + * @author James Allardice + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + return { + "BinaryExpression": function(node) { + + if (!/^[|&^]$/.test(node.operator) && node.left.name === "NaN" || node.right.name === "NaN") { + context.report(node, "Use the isNaN function to compare with NaN."); + } + } + }; + +}; + +},{}],144:[function(require,module,exports){ +/** + * @fileoverview Validates JSDoc comments are syntactically correct + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +var doctrine = require("doctrine"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var options = context.options[0] || {}, + prefer = options.prefer || {}, + + // these both default to true, so you have to explicitly make them false + requireReturn = options.requireReturn === false ? false : true, + requireParamDescription = options.requireParamDescription === false ? false : true; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + // Using a stack to store if a function returns or not (handling nested functions) + var fns = []; + + /** + * When parsing a new function, store it in our function stack. + * @returns {void} + * @private + */ + function startFunction() { + fns.push({returnPresent: false}); + } + + /** + * Indicate that return has been found in the current function. + * @param {ASTNode} node The return node. + * @returns {void} + * @private + */ + function addReturn(node) { + var functionState = fns[fns.length - 1]; + + if (functionState && node.argument !== null) { + functionState.returnPresent = true; + } + } + + /** + * Validate the JSDoc node and output warnings if anything is wrong. + * @param {ASTNode} node The AST node to check. + * @returns {void} + * @private + */ + function checkJSDoc(node) { + var jsdocNode = context.getJSDocComment(node), + functionData = fns.pop(), + hasReturns = false, + hasConstructor = false, + params = Object.create(null), + jsdoc; + + // make sure only to validate JSDoc comments + if (jsdocNode) { + + try { + jsdoc = doctrine.parse(jsdocNode.value, { + strict: true, + unwrap: true, + sloppy: true + }); + } catch (ex) { + + if (/braces/i.test(ex.message)) { + context.report(jsdocNode, "JSDoc type missing brace."); + } else { + context.report(jsdocNode, "JSDoc syntax error."); + } + + return; + } + + jsdoc.tags.forEach(function(tag) { + + switch (tag.title) { + + case "param": + if (!tag.type) { + context.report(jsdocNode, "Missing JSDoc parameter type for '{{name}}'.", { name: tag.name }); + } + + if (!tag.description && requireParamDescription) { + context.report(jsdocNode, "Missing JSDoc parameter description for '{{name}}'.", { name: tag.name }); + } + + if (params[tag.name]) { + context.report(jsdocNode, "Duplicate JSDoc parameter '{{name}}'.", { name: tag.name }); + } else if (tag.name.indexOf(".") === - 1) { + params[tag.name] = 1; + } + break; + + case "return": + case "returns": + hasReturns = true; + + if (!requireReturn && !functionData.returnPresent && tag.type.name !== "void" && tag.type.name !== "undefined") { + context.report(jsdocNode, "Unexpected @" + tag.title + " tag; function has no return statement."); + } else { + if (!tag.type) { + context.report(jsdocNode, "Missing JSDoc return type."); + } + + if (tag.type.name !== "void" && !tag.description) { + context.report(jsdocNode, "Missing JSDoc return description."); + } + } + + break; + + case "constructor": + hasConstructor = true; + break; + + // no default + } + + // check tag preferences + if (prefer.hasOwnProperty(tag.title)) { + context.report(jsdocNode, "Use @{{name}} instead.", { name: prefer[tag.title] }); + } + + }); + + // check for functions missing @returns + if (!hasReturns && !hasConstructor) { + if (requireReturn || functionData.returnPresent) { + context.report(jsdocNode, "Missing JSDoc @returns for function."); + } + } + + // check the parameters + var jsdocParams = Object.keys(params); + + node.params.forEach(function(param, i) { + var name = param.name; + + if (jsdocParams[i] && (name !== jsdocParams[i])) { + context.report(jsdocNode, "Expected JSDoc for '{{name}}' but found '{{jsdocName}}'.", { + name: name, + jsdocName: jsdocParams[i] + }); + } else if (!params[name]) { + context.report(jsdocNode, "Missing JSDoc for parameter '{{name}}'.", { + name: name + }); + } + }); + + } + + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + "FunctionExpression": startFunction, + "FunctionDeclaration": startFunction, + "FunctionExpression:exit": checkJSDoc, + "FunctionDeclaration:exit": checkJSDoc, + "ReturnStatement": addReturn + }; + +}; + +},{"doctrine":4}],145:[function(require,module,exports){ +/** + * @fileoverview Ensures that the results of typeof are compared against a valid string + * @author Ian Christian Myers + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var VALID_TYPES = ["symbol", "undefined", "object", "boolean", "number", "string", "function"], + OPERATORS = ["==", "===", "!=", "!=="]; + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + "UnaryExpression": function (node) { + var parent, sibling; + + if (node.operator === "typeof") { + parent = context.getAncestors().pop(); + + if (parent.type === "BinaryExpression" && OPERATORS.indexOf(parent.operator) !== -1) { + sibling = parent.left === node ? parent.right : parent.left; + + if (sibling.type === "Literal" && VALID_TYPES.indexOf(sibling.value) === -1) { + context.report(sibling, "Invalid typeof comparison value"); + } + } + } + } + + }; + +}; + +},{}],146:[function(require,module,exports){ +/** + * @fileoverview Rule to enforce var declarations are only at the top of a function. + * @author Danny Fritz + * @author Gyandeep Singh + * @copyright 2014 Danny Fritz. All rights reserved. + * @copyright 2014 Gyandeep Singh. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function (context) { + var errorMessage = "All \"var\" declarations must be at the top of the function scope."; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * @param {ASTNode} node - any node + * @returns {Boolean} whether the given node structurally represents a directive + */ + function looksLikeDirective(node) { + return node.type === "ExpressionStatement" && + node.expression.type === "Literal" && typeof node.expression.value === "string"; + } + + /** + * Checks whether this variable is on top of the block body + * @param {ASTNode} node - The node to check + * @param {ASTNode[]} statements - collection of ASTNodes for the parent node block + * @returns {Boolean} True if var is on top otherwise false + */ + function isVarOnTop (node, statements) { + var i = 0, l = statements.length; + + // skip over directives + for (; i < l; ++i) { + if (!looksLikeDirective(statements[i])) { + break; + } + } + + for (; i < l; ++i) { + if (statements[i].type !== "VariableDeclaration") { + return false; + } + if (statements[i] === node) { + return true; + } + } + } + + /** + * Checks whether variable is on top at the global level + * @param {ASTNode} node - The node to check + * @param {ASTNode} parent - Parent of the node + * @returns {void} + */ + function globalVarCheck (node, parent) { + if (!isVarOnTop(node, parent.body)) { + context.report(node, errorMessage); + } + } + + /** + * Checks whether variable is on top at functional block scope level + * @param {ASTNode} node - The node to check + * @param {ASTNode} parent - Parent of the node + * @param {ASTNode} grandParent - Parent of the node's parent + * @returns {void} + */ + function blockScopeVarCheck (node, parent, grandParent) { + if (!((grandParent.type === "FunctionDeclaration" + || grandParent.type === "FunctionExpression") + && parent.type === "BlockStatement" + && isVarOnTop(node, parent.body))) { + context.report(node, errorMessage); + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + "VariableDeclaration": function (node) { + var ancestors = context.getAncestors(); + var parent = ancestors.pop(); + var grandParent = ancestors.pop(); + + if (node.kind === "var") {// check variable is `var` type and not `let` or `const` + if (parent.type === "Program") {// That means its a global variable + globalVarCheck(node, parent); + } else { + blockScopeVarCheck(node, parent, grandParent); + } + } + } + }; + +}; + +},{}],147:[function(require,module,exports){ +/** + * @fileoverview Rule to flag when IIFE is not wrapped in parens + * @author Ilya Volodin + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + var style = context.options[0] || "outside"; + + function wrapped(node) { + var previousToken = context.getTokenBefore(node), + nextToken = context.getTokenAfter(node); + return previousToken && previousToken.value === "(" && + nextToken && nextToken.value === ")"; + } + + return { + + "CallExpression": function(node) { + if (node.callee.type === "FunctionExpression") { + var callExpressionWrapped = wrapped(node), + functionExpressionWrapped = wrapped(node.callee); + + if (!callExpressionWrapped && !functionExpressionWrapped) { + context.report(node, "Wrap an immediate function invocation in parentheses."); + } else if (style === "inside" && !functionExpressionWrapped) { + context.report(node, "Wrap only the function expression in parens."); + } else if (style === "outside" && !callExpressionWrapped) { + context.report(node, "Move the invocation into the parens that contain the function."); + } + } + } + }; + +}; + +},{}],148:[function(require,module,exports){ +/** + * @fileoverview Rule to flag when regex literals are not wrapped in parens + * @author Matt DuVall + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + "use strict"; + + return { + + "Literal": function(node) { + var token = context.getFirstToken(node), + nodeType = token.type, + source, + grandparent, + ancestors; + + if (nodeType === "RegularExpression") { + source = context.getTokenBefore(node); + ancestors = context.getAncestors(); + grandparent = ancestors[ancestors.length - 1]; + + if (grandparent.type === "MemberExpression" && grandparent.object === node && + (!source || source.value !== "(")) { + context.report(node, "Wrap the regexp literal in parens to disambiguate the slash."); + } + } + } + }; + +}; + +},{}],149:[function(require,module,exports){ +/** + * @fileoverview Rule to require or disallow yoda comparisons + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function (context) { + + // Default to "never" (!always) if no option + + var always = (context.options[0] === "always"); + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Determines whether an operator is a comparison operator. + * @param {String} operator The operator to check. + * @returns {Boolean} Whether or not it is a comparison operator. + */ + function isComparisonOperator(operator) { + return (/^(==|===|!=|!==|<|>|<=|>=)$/).test(operator); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + "BinaryExpression": function (node) { + + if (always) { + + // Comparisons must always be yoda-style: if ("blue" === color) + + if (node.right.type === "Literal" && isComparisonOperator(node.operator)) { + context.report(node, "Expected literal to be on the left side of " + node.operator + "."); + } + + } else { + + // Comparisons must never be yoda-style (default) + + if (node.left.type === "Literal" && isComparisonOperator(node.operator)) { + context.report(node, "Expected literal to be on the right side of " + node.operator + "."); + } + + } + + } + + }; + +}; + +},{}],150:[function(require,module,exports){ +/** + * @fileoverview Common utilities. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ +/** + * Merges two objects together and assigns the result to the initial object. Can be used for shallow cloning. + * @param {Object} target of the cloning operation + * @param {Object} source object + * @returns {void} + */ +exports.mixin = function(target, source) { + Object.keys(source).forEach(function(key) { + target[key] = source[key]; + }); +}; + +/** + * Merges two config objects. This will not only add missing keys, but will also modify values to match. + * @param {Object} base config object + * @param {Object} custom config object. Overrides in this config object will take priority over base. + * @returns {Object} merged config object. + */ +exports.mergeConfigs = function mergeConfigs(base, custom) { + + Object.keys(custom).forEach(function (key) { + var property = custom[key]; + + if (key === "plugins") { + if (!base[key]) { + base[key] = []; + } + + property.forEach(function (plugin) { + // skip duplicates + if (base[key].indexOf(plugin) === -1) { + base[key].push(plugin); + } + }); + return; + } + + if (Array.isArray(base[key]) && !Array.isArray(property) && typeof property === "number") { + // assume that we are just overriding first attribute + base[key][0] = custom[key]; + return; + } + + if (typeof property === "object" && !Array.isArray(property)) { + // base[key] might not exist, so be careful with recursion here + base[key] = mergeConfigs(base[key] || {}, custom[key]); + } else { + base[key] = custom[key]; + } + }); + + return base; +}; + +},{}]},{},[9])(9) +}); \ No newline at end of file diff --git a/Source/WebInspectorUI/UserInterface/External/Esprima/LICENSE b/Source/WebInspectorUI/UserInterface/External/Esprima/LICENSE new file mode 100644 index 000000000..7a55160f5 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/External/Esprima/LICENSE @@ -0,0 +1,21 @@ +Copyright JS Foundation and other contributors, https://js.foundation/ + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/Source/WebInspectorUI/UserInterface/External/Esprima/esprima.js b/Source/WebInspectorUI/UserInterface/External/Esprima/esprima.js new file mode 100644 index 000000000..67e39265e --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/External/Esprima/esprima.js @@ -0,0 +1,6768 @@ +(function webpackUniversalModuleDefinition(root, factory) { +/* istanbul ignore next */ + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); +/* istanbul ignore next */ + else if(typeof exports === 'object') + exports["esprima"] = factory(); + else + root["esprima"] = factory(); +})(this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; + +/******/ // The require function +/******/ function __webpack_require__(moduleId) { + +/******/ // Check if module is in cache +/* istanbul ignore if */ +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; + +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; + +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + +/******/ // Flag the module as loaded +/******/ module.loaded = true; + +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } + + +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; + +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; + +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; + +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ function(module, exports, __webpack_require__) { + + /* + Copyright JS Foundation and other contributors, https://js.foundation/ + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + "use strict"; + var comment_handler_1 = __webpack_require__(1); + var jsx_parser_1 = __webpack_require__(3); + var parser_1 = __webpack_require__(8); + var tokenizer_1 = __webpack_require__(15); + function parse(code, options, delegate) { + var commentHandler = null; + var proxyDelegate = function (node, metadata) { + if (delegate) { + delegate(node, metadata); + } + if (commentHandler) { + commentHandler.visit(node, metadata); + } + }; + var parserDelegate = (typeof delegate === 'function') ? proxyDelegate : null; + var collectComment = false; + if (options) { + collectComment = (typeof options.comment === 'boolean' && options.comment); + var attachComment = (typeof options.attachComment === 'boolean' && options.attachComment); + if (collectComment || attachComment) { + commentHandler = new comment_handler_1.CommentHandler(); + commentHandler.attach = attachComment; + options.comment = true; + parserDelegate = proxyDelegate; + } + } + var isModule = false; + if (options && typeof options.sourceType === 'string') { + isModule = (options.sourceType === 'module'); + } + var parser; + if (options && typeof options.jsx === 'boolean' && options.jsx) { + parser = new jsx_parser_1.JSXParser(code, options, parserDelegate); + } + else { + parser = new parser_1.Parser(code, options, parserDelegate); + } + var program = isModule ? parser.parseModule() : parser.parseScript(); + var ast = program; + if (collectComment && commentHandler) { + ast.comments = commentHandler.comments; + } + if (parser.config.tokens) { + ast.tokens = parser.tokens; + } + if (parser.config.tolerant) { + ast.errors = parser.errorHandler.errors; + } + return ast; + } + exports.parse = parse; + function parseModule(code, options, delegate) { + var parsingOptions = options || {}; + parsingOptions.sourceType = 'module'; + return parse(code, parsingOptions, delegate); + } + exports.parseModule = parseModule; + function parseScript(code, options, delegate) { + var parsingOptions = options || {}; + parsingOptions.sourceType = 'script'; + return parse(code, parsingOptions, delegate); + } + exports.parseScript = parseScript; + function tokenize(code, options, delegate) { + var tokenizer = new tokenizer_1.Tokenizer(code, options); + var tokens; + tokens = []; + try { + while (true) { + var token = tokenizer.getNextToken(); + if (!token) { + break; + } + if (delegate) { + token = delegate(token); + } + tokens.push(token); + } + } + catch (e) { + tokenizer.errorHandler.tolerate(e); + } + if (tokenizer.errorHandler.tolerant) { + tokens.errors = tokenizer.errors(); + } + return tokens; + } + exports.tokenize = tokenize; + var syntax_1 = __webpack_require__(2); + exports.Syntax = syntax_1.Syntax; + // Sync with *.json manifests. + exports.version = '4.0.0-dev'; + + +/***/ }, +/* 1 */ +/***/ function(module, exports, __webpack_require__) { + + "use strict"; + var syntax_1 = __webpack_require__(2); + var CommentHandler = (function () { + function CommentHandler() { + this.attach = false; + this.comments = []; + this.stack = []; + this.leading = []; + this.trailing = []; + } + CommentHandler.prototype.insertInnerComments = function (node, metadata) { + // innnerComments for properties empty block + // `function a() {/** comments **\/}` + if (node.type === syntax_1.Syntax.BlockStatement && node.body.length === 0) { + var innerComments = []; + for (var i = this.leading.length - 1; i >= 0; --i) { + var entry = this.leading[i]; + if (metadata.end.offset >= entry.start) { + innerComments.unshift(entry.comment); + this.leading.splice(i, 1); + this.trailing.splice(i, 1); + } + } + if (innerComments.length) { + node.innerComments = innerComments; + } + } + }; + CommentHandler.prototype.findTrailingComments = function (metadata) { + var trailingComments = []; + if (this.trailing.length > 0) { + for (var i = this.trailing.length - 1; i >= 0; --i) { + var entry_1 = this.trailing[i]; + if (entry_1.start >= metadata.end.offset) { + trailingComments.unshift(entry_1.comment); + } + } + this.trailing.length = 0; + return trailingComments; + } + var entry = this.stack[this.stack.length - 1]; + if (entry && entry.node.trailingComments) { + var firstComment = entry.node.trailingComments[0]; + if (firstComment && firstComment.range[0] >= metadata.end.offset) { + trailingComments = entry.node.trailingComments; + delete entry.node.trailingComments; + } + } + return trailingComments; + }; + CommentHandler.prototype.findLeadingComments = function (metadata) { + var leadingComments = []; + var target; + while (this.stack.length > 0) { + var entry = this.stack[this.stack.length - 1]; + if (entry && entry.start >= metadata.start.offset) { + target = entry.node; + this.stack.pop(); + } + else { + break; + } + } + if (target) { + var count = target.leadingComments ? target.leadingComments.length : 0; + for (var i = count - 1; i >= 0; --i) { + var comment = target.leadingComments[i]; + if (comment.range[1] <= metadata.start.offset) { + leadingComments.unshift(comment); + target.leadingComments.splice(i, 1); + } + } + if (target.leadingComments && target.leadingComments.length === 0) { + delete target.leadingComments; + } + return leadingComments; + } + for (var i = this.leading.length - 1; i >= 0; --i) { + var entry = this.leading[i]; + if (entry.start <= metadata.start.offset) { + leadingComments.unshift(entry.comment); + this.leading.splice(i, 1); + } + } + return leadingComments; + }; + CommentHandler.prototype.visitNode = function (node, metadata) { + if (node.type === syntax_1.Syntax.Program && node.body.length > 0) { + return; + } + this.insertInnerComments(node, metadata); + var trailingComments = this.findTrailingComments(metadata); + var leadingComments = this.findLeadingComments(metadata); + if (leadingComments.length > 0) { + node.leadingComments = leadingComments; + } + if (trailingComments.length > 0) { + node.trailingComments = trailingComments; + } + this.stack.push({ + node: node, + start: metadata.start.offset + }); + }; + CommentHandler.prototype.visitComment = function (node, metadata) { + var type = (node.type[0] === 'L') ? 'Line' : 'Block'; + var comment = { + type: type, + value: node.value + }; + if (node.range) { + comment.range = node.range; + } + if (node.loc) { + comment.loc = node.loc; + } + this.comments.push(comment); + if (this.attach) { + var entry = { + comment: { + type: type, + value: node.value, + range: [metadata.start.offset, metadata.end.offset] + }, + start: metadata.start.offset + }; + if (node.loc) { + entry.comment.loc = node.loc; + } + node.type = type; + this.leading.push(entry); + this.trailing.push(entry); + } + }; + CommentHandler.prototype.visit = function (node, metadata) { + if (node.type === 'LineComment') { + this.visitComment(node, metadata); + } + else if (node.type === 'BlockComment') { + this.visitComment(node, metadata); + } + else if (this.attach) { + this.visitNode(node, metadata); + } + }; + return CommentHandler; + }()); + exports.CommentHandler = CommentHandler; + + +/***/ }, +/* 2 */ +/***/ function(module, exports) { + + "use strict"; + exports.Syntax = { + AssignmentExpression: 'AssignmentExpression', + AssignmentPattern: 'AssignmentPattern', + ArrayExpression: 'ArrayExpression', + ArrayPattern: 'ArrayPattern', + ArrowFunctionExpression: 'ArrowFunctionExpression', + AwaitExpression: 'AwaitExpression', + BlockStatement: 'BlockStatement', + BinaryExpression: 'BinaryExpression', + BreakStatement: 'BreakStatement', + CallExpression: 'CallExpression', + CatchClause: 'CatchClause', + ClassBody: 'ClassBody', + ClassDeclaration: 'ClassDeclaration', + ClassExpression: 'ClassExpression', + ConditionalExpression: 'ConditionalExpression', + ContinueStatement: 'ContinueStatement', + DoWhileStatement: 'DoWhileStatement', + DebuggerStatement: 'DebuggerStatement', + EmptyStatement: 'EmptyStatement', + ExportAllDeclaration: 'ExportAllDeclaration', + ExportDefaultDeclaration: 'ExportDefaultDeclaration', + ExportNamedDeclaration: 'ExportNamedDeclaration', + ExportSpecifier: 'ExportSpecifier', + ExpressionStatement: 'ExpressionStatement', + ForStatement: 'ForStatement', + ForOfStatement: 'ForOfStatement', + ForInStatement: 'ForInStatement', + FunctionDeclaration: 'FunctionDeclaration', + FunctionExpression: 'FunctionExpression', + Identifier: 'Identifier', + IfStatement: 'IfStatement', + Import: 'Import', + ImportDeclaration: 'ImportDeclaration', + ImportDefaultSpecifier: 'ImportDefaultSpecifier', + ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', + ImportSpecifier: 'ImportSpecifier', + Literal: 'Literal', + LabeledStatement: 'LabeledStatement', + LogicalExpression: 'LogicalExpression', + MemberExpression: 'MemberExpression', + MetaProperty: 'MetaProperty', + MethodDefinition: 'MethodDefinition', + NewExpression: 'NewExpression', + ObjectExpression: 'ObjectExpression', + ObjectPattern: 'ObjectPattern', + Program: 'Program', + Property: 'Property', + RestElement: 'RestElement', + RestProperty: 'RestProperty', + ReturnStatement: 'ReturnStatement', + SequenceExpression: 'SequenceExpression', + SpreadElement: 'SpreadElement', + SpreadProperty: 'SpreadProperty', + Super: 'Super', + SwitchCase: 'SwitchCase', + SwitchStatement: 'SwitchStatement', + TaggedTemplateExpression: 'TaggedTemplateExpression', + TemplateElement: 'TemplateElement', + TemplateLiteral: 'TemplateLiteral', + ThisExpression: 'ThisExpression', + ThrowStatement: 'ThrowStatement', + TryStatement: 'TryStatement', + UnaryExpression: 'UnaryExpression', + UpdateExpression: 'UpdateExpression', + VariableDeclaration: 'VariableDeclaration', + VariableDeclarator: 'VariableDeclarator', + WhileStatement: 'WhileStatement', + WithStatement: 'WithStatement', + YieldExpression: 'YieldExpression' + }; + + +/***/ }, +/* 3 */ +/***/ function(module, exports, __webpack_require__) { + + "use strict"; +/* istanbul ignore next */ + var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var character_1 = __webpack_require__(4); + var JSXNode = __webpack_require__(5); + var jsx_syntax_1 = __webpack_require__(6); + var Node = __webpack_require__(7); + var parser_1 = __webpack_require__(8); + var token_1 = __webpack_require__(13); + var xhtml_entities_1 = __webpack_require__(14); + token_1.TokenName[100 /* Identifier */] = 'JSXIdentifier'; + token_1.TokenName[101 /* Text */] = 'JSXText'; + // Fully qualified element name, e.g. returns "svg:path" + function getQualifiedElementName(elementName) { + var qualifiedName; + switch (elementName.type) { + case jsx_syntax_1.JSXSyntax.JSXIdentifier: + var id = elementName; + qualifiedName = id.name; + break; + case jsx_syntax_1.JSXSyntax.JSXNamespacedName: + var ns = elementName; + qualifiedName = getQualifiedElementName(ns.namespace) + ':' + + getQualifiedElementName(ns.name); + break; + case jsx_syntax_1.JSXSyntax.JSXMemberExpression: + var expr = elementName; + qualifiedName = getQualifiedElementName(expr.object) + '.' + + getQualifiedElementName(expr.property); + break; + /* istanbul ignore next */ + default: + break; + } + return qualifiedName; + } + var JSXParser = (function (_super) { + __extends(JSXParser, _super); + function JSXParser(code, options, delegate) { + return _super.call(this, code, options, delegate) || this; + } + JSXParser.prototype.parsePrimaryExpression = function () { + return this.match('<') ? this.parseJSXRoot() : _super.prototype.parsePrimaryExpression.call(this); + }; + JSXParser.prototype.startJSX = function () { + // Unwind the scanner before the lookahead token. + this.scanner.index = this.startMarker.index; + this.scanner.lineNumber = this.startMarker.line; + this.scanner.lineStart = this.startMarker.index - this.startMarker.column; + }; + JSXParser.prototype.finishJSX = function () { + // Prime the next lookahead. + this.nextToken(); + }; + JSXParser.prototype.reenterJSX = function () { + this.startJSX(); + this.expectJSX('}'); + // Pop the closing '}' added from the lookahead. + if (this.config.tokens) { + this.tokens.pop(); + } + }; + JSXParser.prototype.createJSXNode = function () { + this.collectComments(); + return { + index: this.scanner.index, + line: this.scanner.lineNumber, + column: this.scanner.index - this.scanner.lineStart + }; + }; + JSXParser.prototype.createJSXChildNode = function () { + return { + index: this.scanner.index, + line: this.scanner.lineNumber, + column: this.scanner.index - this.scanner.lineStart + }; + }; + JSXParser.prototype.scanXHTMLEntity = function (quote) { + var result = '&'; + var valid = true; + var terminated = false; + var numeric = false; + var hex = false; + while (!this.scanner.eof() && valid && !terminated) { + var ch = this.scanner.source[this.scanner.index]; + if (ch === quote) { + break; + } + terminated = (ch === ';'); + result += ch; + ++this.scanner.index; + if (!terminated) { + switch (result.length) { + case 2: + // e.g. '{' + numeric = (ch === '#'); + break; + case 3: + if (numeric) { + // e.g. 'A' + hex = (ch === 'x'); + valid = hex || character_1.Character.isDecimalDigit(ch.charCodeAt(0)); + numeric = numeric && !hex; + } + break; + default: + valid = valid && !(numeric && !character_1.Character.isDecimalDigit(ch.charCodeAt(0))); + valid = valid && !(hex && !character_1.Character.isHexDigit(ch.charCodeAt(0))); + break; + } + } + } + if (valid && terminated && result.length > 2) { + // e.g. 'A' becomes just '#x41' + var str = result.substr(1, result.length - 2); + if (numeric && str.length > 1) { + result = String.fromCharCode(parseInt(str.substr(1), 10)); + } + else if (hex && str.length > 2) { + result = String.fromCharCode(parseInt('0' + str.substr(1), 16)); + } + else if (!numeric && !hex && xhtml_entities_1.XHTMLEntities[str]) { + result = xhtml_entities_1.XHTMLEntities[str]; + } + } + return result; + }; + // Scan the next JSX token. This replaces Scanner#lex when in JSX mode. + JSXParser.prototype.lexJSX = function () { + var cp = this.scanner.source.charCodeAt(this.scanner.index); + // < > / : = { } + if (cp === 60 || cp === 62 || cp === 47 || cp === 58 || cp === 61 || cp === 123 || cp === 125) { + var value = this.scanner.source[this.scanner.index++]; + return { + type: 7 /* Punctuator */, + value: value, + lineNumber: this.scanner.lineNumber, + lineStart: this.scanner.lineStart, + start: this.scanner.index - 1, + end: this.scanner.index + }; + } + // " ' + if (cp === 34 || cp === 39) { + var start = this.scanner.index; + var quote = this.scanner.source[this.scanner.index++]; + var str = ''; + while (!this.scanner.eof()) { + var ch = this.scanner.source[this.scanner.index++]; + if (ch === quote) { + break; + } + else if (ch === '&') { + str += this.scanXHTMLEntity(quote); + } + else { + str += ch; + } + } + return { + type: 8 /* StringLiteral */, + value: str, + lineNumber: this.scanner.lineNumber, + lineStart: this.scanner.lineStart, + start: start, + end: this.scanner.index + }; + } + // ... or . + if (cp === 46) { + var n1 = this.scanner.source.charCodeAt(this.scanner.index + 1); + var n2 = this.scanner.source.charCodeAt(this.scanner.index + 2); + var value = (n1 === 46 && n2 === 46) ? '...' : '.'; + var start = this.scanner.index; + this.scanner.index += value.length; + return { + type: 7 /* Punctuator */, + value: value, + lineNumber: this.scanner.lineNumber, + lineStart: this.scanner.lineStart, + start: start, + end: this.scanner.index + }; + } + // ` + if (cp === 96) { + // Only placeholder, since it will be rescanned as a real assignment expression. + return { + type: 10 /* Template */, + value: '', + lineNumber: this.scanner.lineNumber, + lineStart: this.scanner.lineStart, + start: this.scanner.index, + end: this.scanner.index + }; + } + // Identifer can not contain backslash (char code 92). + if (character_1.Character.isIdentifierStart(cp) && (cp !== 92)) { + var start = this.scanner.index; + ++this.scanner.index; + while (!this.scanner.eof()) { + var ch = this.scanner.source.charCodeAt(this.scanner.index); + if (character_1.Character.isIdentifierPart(ch) && (ch !== 92)) { + ++this.scanner.index; + } + else if (ch === 45) { + // Hyphen (char code 45) can be part of an identifier. + ++this.scanner.index; + } + else { + break; + } + } + var id = this.scanner.source.slice(start, this.scanner.index); + return { + type: 100 /* Identifier */, + value: id, + lineNumber: this.scanner.lineNumber, + lineStart: this.scanner.lineStart, + start: start, + end: this.scanner.index + }; + } + return this.scanner.throwUnexpectedToken(); + }; + JSXParser.prototype.nextJSXToken = function () { + this.collectComments(); + this.startMarker.index = this.scanner.index; + this.startMarker.line = this.scanner.lineNumber; + this.startMarker.column = this.scanner.index - this.scanner.lineStart; + var token = this.lexJSX(); + this.lastMarker.index = this.scanner.index; + this.lastMarker.line = this.scanner.lineNumber; + this.lastMarker.column = this.scanner.index - this.scanner.lineStart; + if (this.config.tokens) { + this.tokens.push(this.convertToken(token)); + } + return token; + }; + JSXParser.prototype.nextJSXText = function () { + this.startMarker.index = this.scanner.index; + this.startMarker.line = this.scanner.lineNumber; + this.startMarker.column = this.scanner.index - this.scanner.lineStart; + var start = this.scanner.index; + var text = ''; + while (!this.scanner.eof()) { + var ch = this.scanner.source[this.scanner.index]; + if (ch === '{' || ch === '<') { + break; + } + ++this.scanner.index; + text += ch; + if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) { + ++this.scanner.lineNumber; + if (ch === '\r' && this.scanner.source[this.scanner.index] === '\n') { + ++this.scanner.index; + } + this.scanner.lineStart = this.scanner.index; + } + } + this.lastMarker.index = this.scanner.index; + this.lastMarker.line = this.scanner.lineNumber; + this.lastMarker.column = this.scanner.index - this.scanner.lineStart; + var token = { + type: 101 /* Text */, + value: text, + lineNumber: this.scanner.lineNumber, + lineStart: this.scanner.lineStart, + start: start, + end: this.scanner.index + }; + if ((text.length > 0) && this.config.tokens) { + this.tokens.push(this.convertToken(token)); + } + return token; + }; + JSXParser.prototype.peekJSXToken = function () { + var state = this.scanner.saveState(); + this.scanner.scanComments(); + var next = this.lexJSX(); + this.scanner.restoreState(state); + return next; + }; + // Expect the next JSX token to match the specified punctuator. + // If not, an exception will be thrown. + JSXParser.prototype.expectJSX = function (value) { + var token = this.nextJSXToken(); + if (token.type !== 7 /* Punctuator */ || token.value !== value) { + this.throwUnexpectedToken(token); + } + }; + // Return true if the next JSX token matches the specified punctuator. + JSXParser.prototype.matchJSX = function (value) { + var next = this.peekJSXToken(); + return next.type === 7 /* Punctuator */ && next.value === value; + }; + JSXParser.prototype.parseJSXIdentifier = function () { + var node = this.createJSXNode(); + var token = this.nextJSXToken(); + if (token.type !== 100 /* Identifier */) { + this.throwUnexpectedToken(token); + } + return this.finalize(node, new JSXNode.JSXIdentifier(token.value)); + }; + JSXParser.prototype.parseJSXElementName = function () { + var node = this.createJSXNode(); + var elementName = this.parseJSXIdentifier(); + if (this.matchJSX(':')) { + var namespace = elementName; + this.expectJSX(':'); + var name_1 = this.parseJSXIdentifier(); + elementName = this.finalize(node, new JSXNode.JSXNamespacedName(namespace, name_1)); + } + else if (this.matchJSX('.')) { + while (this.matchJSX('.')) { + var object = elementName; + this.expectJSX('.'); + var property = this.parseJSXIdentifier(); + elementName = this.finalize(node, new JSXNode.JSXMemberExpression(object, property)); + } + } + return elementName; + }; + JSXParser.prototype.parseJSXAttributeName = function () { + var node = this.createJSXNode(); + var attributeName; + var identifier = this.parseJSXIdentifier(); + if (this.matchJSX(':')) { + var namespace = identifier; + this.expectJSX(':'); + var name_2 = this.parseJSXIdentifier(); + attributeName = this.finalize(node, new JSXNode.JSXNamespacedName(namespace, name_2)); + } + else { + attributeName = identifier; + } + return attributeName; + }; + JSXParser.prototype.parseJSXStringLiteralAttribute = function () { + var node = this.createJSXNode(); + var token = this.nextJSXToken(); + if (token.type !== 8 /* StringLiteral */) { + this.throwUnexpectedToken(token); + } + var raw = this.getTokenRaw(token); + return this.finalize(node, new Node.Literal(token.value, raw)); + }; + JSXParser.prototype.parseJSXExpressionAttribute = function () { + var node = this.createJSXNode(); + this.expectJSX('{'); + this.finishJSX(); + if (this.match('}')) { + this.tolerateError('JSX attributes must only be assigned a non-empty expression'); + } + var expression = this.parseAssignmentExpression(); + this.reenterJSX(); + return this.finalize(node, new JSXNode.JSXExpressionContainer(expression)); + }; + JSXParser.prototype.parseJSXAttributeValue = function () { + return this.matchJSX('{') ? this.parseJSXExpressionAttribute() : + this.matchJSX('<') ? this.parseJSXElement() : this.parseJSXStringLiteralAttribute(); + }; + JSXParser.prototype.parseJSXNameValueAttribute = function () { + var node = this.createJSXNode(); + var name = this.parseJSXAttributeName(); + var value = null; + if (this.matchJSX('=')) { + this.expectJSX('='); + value = this.parseJSXAttributeValue(); + } + return this.finalize(node, new JSXNode.JSXAttribute(name, value)); + }; + JSXParser.prototype.parseJSXSpreadAttribute = function () { + var node = this.createJSXNode(); + this.expectJSX('{'); + this.expectJSX('...'); + this.finishJSX(); + var argument = this.parseAssignmentExpression(); + this.reenterJSX(); + return this.finalize(node, new JSXNode.JSXSpreadAttribute(argument)); + }; + JSXParser.prototype.parseJSXAttributes = function () { + var attributes = []; + while (!this.matchJSX('/') && !this.matchJSX('>')) { + var attribute = this.matchJSX('{') ? this.parseJSXSpreadAttribute() : + this.parseJSXNameValueAttribute(); + attributes.push(attribute); + } + return attributes; + }; + JSXParser.prototype.parseJSXOpeningElement = function () { + var node = this.createJSXNode(); + this.expectJSX('<'); + var name = this.parseJSXElementName(); + var attributes = this.parseJSXAttributes(); + var selfClosing = this.matchJSX('/'); + if (selfClosing) { + this.expectJSX('/'); + } + this.expectJSX('>'); + return this.finalize(node, new JSXNode.JSXOpeningElement(name, selfClosing, attributes)); + }; + JSXParser.prototype.parseJSXBoundaryElement = function () { + var node = this.createJSXNode(); + this.expectJSX('<'); + if (this.matchJSX('/')) { + this.expectJSX('/'); + var name_3 = this.parseJSXElementName(); + this.expectJSX('>'); + return this.finalize(node, new JSXNode.JSXClosingElement(name_3)); + } + var name = this.parseJSXElementName(); + var attributes = this.parseJSXAttributes(); + var selfClosing = this.matchJSX('/'); + if (selfClosing) { + this.expectJSX('/'); + } + this.expectJSX('>'); + return this.finalize(node, new JSXNode.JSXOpeningElement(name, selfClosing, attributes)); + }; + JSXParser.prototype.parseJSXEmptyExpression = function () { + var node = this.createJSXChildNode(); + this.collectComments(); + this.lastMarker.index = this.scanner.index; + this.lastMarker.line = this.scanner.lineNumber; + this.lastMarker.column = this.scanner.index - this.scanner.lineStart; + return this.finalize(node, new JSXNode.JSXEmptyExpression()); + }; + JSXParser.prototype.parseJSXExpressionContainer = function () { + var node = this.createJSXNode(); + this.expectJSX('{'); + var expression; + if (this.matchJSX('}')) { + expression = this.parseJSXEmptyExpression(); + this.expectJSX('}'); + } + else { + this.finishJSX(); + expression = this.parseAssignmentExpression(); + this.reenterJSX(); + } + return this.finalize(node, new JSXNode.JSXExpressionContainer(expression)); + }; + JSXParser.prototype.parseJSXChildren = function () { + var children = []; + while (!this.scanner.eof()) { + var node = this.createJSXChildNode(); + var token = this.nextJSXText(); + if (token.start < token.end) { + var raw = this.getTokenRaw(token); + var child = this.finalize(node, new JSXNode.JSXText(token.value, raw)); + children.push(child); + } + if (this.scanner.source[this.scanner.index] === '{') { + var container = this.parseJSXExpressionContainer(); + children.push(container); + } + else { + break; + } + } + return children; + }; + JSXParser.prototype.parseComplexJSXElement = function (el) { + var stack = []; + while (!this.scanner.eof()) { + el.children = el.children.concat(this.parseJSXChildren()); + var node = this.createJSXChildNode(); + var element = this.parseJSXBoundaryElement(); + if (element.type === jsx_syntax_1.JSXSyntax.JSXOpeningElement) { + var opening = element; + if (opening.selfClosing) { + var child = this.finalize(node, new JSXNode.JSXElement(opening, [], null)); + el.children.push(child); + } + else { + stack.push(el); + el = { node: node, opening: opening, closing: null, children: [] }; + } + } + if (element.type === jsx_syntax_1.JSXSyntax.JSXClosingElement) { + el.closing = element; + var open_1 = getQualifiedElementName(el.opening.name); + var close_1 = getQualifiedElementName(el.closing.name); + if (open_1 !== close_1) { + this.tolerateError('Expected corresponding JSX closing tag for %0', open_1); + } + if (stack.length > 0) { + var child = this.finalize(el.node, new JSXNode.JSXElement(el.opening, el.children, el.closing)); + el = stack[stack.length - 1]; + el.children.push(child); + stack.pop(); + } + else { + break; + } + } + } + return el; + }; + JSXParser.prototype.parseJSXElement = function () { + var node = this.createJSXNode(); + var opening = this.parseJSXOpeningElement(); + var children = []; + var closing = null; + if (!opening.selfClosing) { + var el = this.parseComplexJSXElement({ node: node, opening: opening, closing: closing, children: children }); + children = el.children; + closing = el.closing; + } + return this.finalize(node, new JSXNode.JSXElement(opening, children, closing)); + }; + JSXParser.prototype.parseJSXRoot = function () { + // Pop the opening '<' added from the lookahead. + if (this.config.tokens) { + this.tokens.pop(); + } + this.startJSX(); + var element = this.parseJSXElement(); + this.finishJSX(); + return element; + }; + return JSXParser; + }(parser_1.Parser)); + exports.JSXParser = JSXParser; + + +/***/ }, +/* 4 */ +/***/ function(module, exports) { + + "use strict"; + // See also tools/generate-unicode-regex.js. + var Regex = { + // Unicode v8.0.0 NonAsciiIdentifierStart: + NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/, + // Unicode v8.0.0 NonAsciiIdentifierPart: + NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/ + }; + exports.Character = { + /* tslint:disable:no-bitwise */ + fromCodePoint: function (cp) { + return (cp < 0x10000) ? String.fromCharCode(cp) : + String.fromCharCode(0xD800 + ((cp - 0x10000) >> 10)) + + String.fromCharCode(0xDC00 + ((cp - 0x10000) & 1023)); + }, + // https://tc39.github.io/ecma262/#sec-white-space + isWhiteSpace: function (cp) { + return (cp === 0x20) || (cp === 0x09) || (cp === 0x0B) || (cp === 0x0C) || (cp === 0xA0) || + (cp >= 0x1680 && [0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(cp) >= 0); + }, + // https://tc39.github.io/ecma262/#sec-line-terminators + isLineTerminator: function (cp) { + return (cp === 0x0A) || (cp === 0x0D) || (cp === 0x2028) || (cp === 0x2029); + }, + // https://tc39.github.io/ecma262/#sec-names-and-keywords + isIdentifierStart: function (cp) { + return (cp === 0x24) || (cp === 0x5F) || + (cp >= 0x41 && cp <= 0x5A) || + (cp >= 0x61 && cp <= 0x7A) || + (cp === 0x5C) || + ((cp >= 0x80) && Regex.NonAsciiIdentifierStart.test(exports.Character.fromCodePoint(cp))); + }, + isIdentifierPart: function (cp) { + return (cp === 0x24) || (cp === 0x5F) || + (cp >= 0x41 && cp <= 0x5A) || + (cp >= 0x61 && cp <= 0x7A) || + (cp >= 0x30 && cp <= 0x39) || + (cp === 0x5C) || + ((cp >= 0x80) && Regex.NonAsciiIdentifierPart.test(exports.Character.fromCodePoint(cp))); + }, + // https://tc39.github.io/ecma262/#sec-literals-numeric-literals + isDecimalDigit: function (cp) { + return (cp >= 0x30 && cp <= 0x39); // 0..9 + }, + isHexDigit: function (cp) { + return (cp >= 0x30 && cp <= 0x39) || + (cp >= 0x41 && cp <= 0x46) || + (cp >= 0x61 && cp <= 0x66); // a..f + }, + isOctalDigit: function (cp) { + return (cp >= 0x30 && cp <= 0x37); // 0..7 + } + }; + + +/***/ }, +/* 5 */ +/***/ function(module, exports, __webpack_require__) { + + "use strict"; + var jsx_syntax_1 = __webpack_require__(6); + /* tslint:disable:max-classes-per-file */ + var JSXClosingElement = (function () { + function JSXClosingElement(name) { + this.type = jsx_syntax_1.JSXSyntax.JSXClosingElement; + this.name = name; + } + return JSXClosingElement; + }()); + exports.JSXClosingElement = JSXClosingElement; + var JSXElement = (function () { + function JSXElement(openingElement, children, closingElement) { + this.type = jsx_syntax_1.JSXSyntax.JSXElement; + this.openingElement = openingElement; + this.children = children; + this.closingElement = closingElement; + } + return JSXElement; + }()); + exports.JSXElement = JSXElement; + var JSXEmptyExpression = (function () { + function JSXEmptyExpression() { + this.type = jsx_syntax_1.JSXSyntax.JSXEmptyExpression; + } + return JSXEmptyExpression; + }()); + exports.JSXEmptyExpression = JSXEmptyExpression; + var JSXExpressionContainer = (function () { + function JSXExpressionContainer(expression) { + this.type = jsx_syntax_1.JSXSyntax.JSXExpressionContainer; + this.expression = expression; + } + return JSXExpressionContainer; + }()); + exports.JSXExpressionContainer = JSXExpressionContainer; + var JSXIdentifier = (function () { + function JSXIdentifier(name) { + this.type = jsx_syntax_1.JSXSyntax.JSXIdentifier; + this.name = name; + } + return JSXIdentifier; + }()); + exports.JSXIdentifier = JSXIdentifier; + var JSXMemberExpression = (function () { + function JSXMemberExpression(object, property) { + this.type = jsx_syntax_1.JSXSyntax.JSXMemberExpression; + this.object = object; + this.property = property; + } + return JSXMemberExpression; + }()); + exports.JSXMemberExpression = JSXMemberExpression; + var JSXAttribute = (function () { + function JSXAttribute(name, value) { + this.type = jsx_syntax_1.JSXSyntax.JSXAttribute; + this.name = name; + this.value = value; + } + return JSXAttribute; + }()); + exports.JSXAttribute = JSXAttribute; + var JSXNamespacedName = (function () { + function JSXNamespacedName(namespace, name) { + this.type = jsx_syntax_1.JSXSyntax.JSXNamespacedName; + this.namespace = namespace; + this.name = name; + } + return JSXNamespacedName; + }()); + exports.JSXNamespacedName = JSXNamespacedName; + var JSXOpeningElement = (function () { + function JSXOpeningElement(name, selfClosing, attributes) { + this.type = jsx_syntax_1.JSXSyntax.JSXOpeningElement; + this.name = name; + this.selfClosing = selfClosing; + this.attributes = attributes; + } + return JSXOpeningElement; + }()); + exports.JSXOpeningElement = JSXOpeningElement; + var JSXSpreadAttribute = (function () { + function JSXSpreadAttribute(argument) { + this.type = jsx_syntax_1.JSXSyntax.JSXSpreadAttribute; + this.argument = argument; + } + return JSXSpreadAttribute; + }()); + exports.JSXSpreadAttribute = JSXSpreadAttribute; + var JSXText = (function () { + function JSXText(value, raw) { + this.type = jsx_syntax_1.JSXSyntax.JSXText; + this.value = value; + this.raw = raw; + } + return JSXText; + }()); + exports.JSXText = JSXText; + + +/***/ }, +/* 6 */ +/***/ function(module, exports) { + + "use strict"; + exports.JSXSyntax = { + JSXAttribute: 'JSXAttribute', + JSXClosingElement: 'JSXClosingElement', + JSXElement: 'JSXElement', + JSXEmptyExpression: 'JSXEmptyExpression', + JSXExpressionContainer: 'JSXExpressionContainer', + JSXIdentifier: 'JSXIdentifier', + JSXMemberExpression: 'JSXMemberExpression', + JSXNamespacedName: 'JSXNamespacedName', + JSXOpeningElement: 'JSXOpeningElement', + JSXSpreadAttribute: 'JSXSpreadAttribute', + JSXText: 'JSXText' + }; + + +/***/ }, +/* 7 */ +/***/ function(module, exports, __webpack_require__) { + + "use strict"; + var syntax_1 = __webpack_require__(2); + /* tslint:disable:max-classes-per-file */ + var ArrayExpression = (function () { + function ArrayExpression(elements) { + this.type = syntax_1.Syntax.ArrayExpression; + this.elements = elements; + } + return ArrayExpression; + }()); + exports.ArrayExpression = ArrayExpression; + var ArrayPattern = (function () { + function ArrayPattern(elements) { + this.type = syntax_1.Syntax.ArrayPattern; + this.elements = elements; + } + return ArrayPattern; + }()); + exports.ArrayPattern = ArrayPattern; + var ArrowFunctionExpression = (function () { + function ArrowFunctionExpression(params, body, expression) { + this.type = syntax_1.Syntax.ArrowFunctionExpression; + this.id = null; + this.params = params; + this.body = body; + this.generator = false; + this.expression = expression; + this.async = false; + } + return ArrowFunctionExpression; + }()); + exports.ArrowFunctionExpression = ArrowFunctionExpression; + var AssignmentExpression = (function () { + function AssignmentExpression(operator, left, right) { + this.type = syntax_1.Syntax.AssignmentExpression; + this.operator = operator; + this.left = left; + this.right = right; + } + return AssignmentExpression; + }()); + exports.AssignmentExpression = AssignmentExpression; + var AssignmentPattern = (function () { + function AssignmentPattern(left, right) { + this.type = syntax_1.Syntax.AssignmentPattern; + this.left = left; + this.right = right; + } + return AssignmentPattern; + }()); + exports.AssignmentPattern = AssignmentPattern; + var AsyncArrowFunctionExpression = (function () { + function AsyncArrowFunctionExpression(params, body, expression) { + this.type = syntax_1.Syntax.ArrowFunctionExpression; + this.id = null; + this.params = params; + this.body = body; + this.generator = false; + this.expression = expression; + this.async = true; + } + return AsyncArrowFunctionExpression; + }()); + exports.AsyncArrowFunctionExpression = AsyncArrowFunctionExpression; + var AsyncFunctionDeclaration = (function () { + function AsyncFunctionDeclaration(id, params, body) { + this.type = syntax_1.Syntax.FunctionDeclaration; + this.id = id; + this.params = params; + this.body = body; + this.generator = false; + this.expression = false; + this.async = true; + } + return AsyncFunctionDeclaration; + }()); + exports.AsyncFunctionDeclaration = AsyncFunctionDeclaration; + var AsyncFunctionExpression = (function () { + function AsyncFunctionExpression(id, params, body) { + this.type = syntax_1.Syntax.FunctionExpression; + this.id = id; + this.params = params; + this.body = body; + this.generator = false; + this.expression = false; + this.async = true; + } + return AsyncFunctionExpression; + }()); + exports.AsyncFunctionExpression = AsyncFunctionExpression; + var AwaitExpression = (function () { + function AwaitExpression(argument) { + this.type = syntax_1.Syntax.AwaitExpression; + this.argument = argument; + } + return AwaitExpression; + }()); + exports.AwaitExpression = AwaitExpression; + var BinaryExpression = (function () { + function BinaryExpression(operator, left, right) { + var logical = (operator === '||' || operator === '&&'); + this.type = logical ? syntax_1.Syntax.LogicalExpression : syntax_1.Syntax.BinaryExpression; + this.operator = operator; + this.left = left; + this.right = right; + } + return BinaryExpression; + }()); + exports.BinaryExpression = BinaryExpression; + var BlockStatement = (function () { + function BlockStatement(body) { + this.type = syntax_1.Syntax.BlockStatement; + this.body = body; + } + return BlockStatement; + }()); + exports.BlockStatement = BlockStatement; + var BreakStatement = (function () { + function BreakStatement(label) { + this.type = syntax_1.Syntax.BreakStatement; + this.label = label; + } + return BreakStatement; + }()); + exports.BreakStatement = BreakStatement; + var CallExpression = (function () { + function CallExpression(callee, args) { + this.type = syntax_1.Syntax.CallExpression; + this.callee = callee; + this.arguments = args; + } + return CallExpression; + }()); + exports.CallExpression = CallExpression; + var CatchClause = (function () { + function CatchClause(param, body) { + this.type = syntax_1.Syntax.CatchClause; + this.param = param; + this.body = body; + } + return CatchClause; + }()); + exports.CatchClause = CatchClause; + var ClassBody = (function () { + function ClassBody(body) { + this.type = syntax_1.Syntax.ClassBody; + this.body = body; + } + return ClassBody; + }()); + exports.ClassBody = ClassBody; + var ClassDeclaration = (function () { + function ClassDeclaration(id, superClass, body) { + this.type = syntax_1.Syntax.ClassDeclaration; + this.id = id; + this.superClass = superClass; + this.body = body; + } + return ClassDeclaration; + }()); + exports.ClassDeclaration = ClassDeclaration; + var ClassExpression = (function () { + function ClassExpression(id, superClass, body) { + this.type = syntax_1.Syntax.ClassExpression; + this.id = id; + this.superClass = superClass; + this.body = body; + } + return ClassExpression; + }()); + exports.ClassExpression = ClassExpression; + var ComputedMemberExpression = (function () { + function ComputedMemberExpression(object, property) { + this.type = syntax_1.Syntax.MemberExpression; + this.computed = true; + this.object = object; + this.property = property; + } + return ComputedMemberExpression; + }()); + exports.ComputedMemberExpression = ComputedMemberExpression; + var ConditionalExpression = (function () { + function ConditionalExpression(test, consequent, alternate) { + this.type = syntax_1.Syntax.ConditionalExpression; + this.test = test; + this.consequent = consequent; + this.alternate = alternate; + } + return ConditionalExpression; + }()); + exports.ConditionalExpression = ConditionalExpression; + var ContinueStatement = (function () { + function ContinueStatement(label) { + this.type = syntax_1.Syntax.ContinueStatement; + this.label = label; + } + return ContinueStatement; + }()); + exports.ContinueStatement = ContinueStatement; + var DebuggerStatement = (function () { + function DebuggerStatement() { + this.type = syntax_1.Syntax.DebuggerStatement; + } + return DebuggerStatement; + }()); + exports.DebuggerStatement = DebuggerStatement; + var Directive = (function () { + function Directive(expression, directive) { + this.type = syntax_1.Syntax.ExpressionStatement; + this.expression = expression; + this.directive = directive; + } + return Directive; + }()); + exports.Directive = Directive; + var DoWhileStatement = (function () { + function DoWhileStatement(body, test) { + this.type = syntax_1.Syntax.DoWhileStatement; + this.body = body; + this.test = test; + } + return DoWhileStatement; + }()); + exports.DoWhileStatement = DoWhileStatement; + var EmptyStatement = (function () { + function EmptyStatement() { + this.type = syntax_1.Syntax.EmptyStatement; + } + return EmptyStatement; + }()); + exports.EmptyStatement = EmptyStatement; + var ExportAllDeclaration = (function () { + function ExportAllDeclaration(source) { + this.type = syntax_1.Syntax.ExportAllDeclaration; + this.source = source; + } + return ExportAllDeclaration; + }()); + exports.ExportAllDeclaration = ExportAllDeclaration; + var ExportDefaultDeclaration = (function () { + function ExportDefaultDeclaration(declaration) { + this.type = syntax_1.Syntax.ExportDefaultDeclaration; + this.declaration = declaration; + } + return ExportDefaultDeclaration; + }()); + exports.ExportDefaultDeclaration = ExportDefaultDeclaration; + var ExportNamedDeclaration = (function () { + function ExportNamedDeclaration(declaration, specifiers, source) { + this.type = syntax_1.Syntax.ExportNamedDeclaration; + this.declaration = declaration; + this.specifiers = specifiers; + this.source = source; + } + return ExportNamedDeclaration; + }()); + exports.ExportNamedDeclaration = ExportNamedDeclaration; + var ExportSpecifier = (function () { + function ExportSpecifier(local, exported) { + this.type = syntax_1.Syntax.ExportSpecifier; + this.exported = exported; + this.local = local; + } + return ExportSpecifier; + }()); + exports.ExportSpecifier = ExportSpecifier; + var ExpressionStatement = (function () { + function ExpressionStatement(expression) { + this.type = syntax_1.Syntax.ExpressionStatement; + this.expression = expression; + } + return ExpressionStatement; + }()); + exports.ExpressionStatement = ExpressionStatement; + var ForInStatement = (function () { + function ForInStatement(left, right, body) { + this.type = syntax_1.Syntax.ForInStatement; + this.left = left; + this.right = right; + this.body = body; + this.each = false; + } + return ForInStatement; + }()); + exports.ForInStatement = ForInStatement; + var ForOfStatement = (function () { + function ForOfStatement(left, right, body) { + this.type = syntax_1.Syntax.ForOfStatement; + this.left = left; + this.right = right; + this.body = body; + } + return ForOfStatement; + }()); + exports.ForOfStatement = ForOfStatement; + var ForStatement = (function () { + function ForStatement(init, test, update, body) { + this.type = syntax_1.Syntax.ForStatement; + this.init = init; + this.test = test; + this.update = update; + this.body = body; + } + return ForStatement; + }()); + exports.ForStatement = ForStatement; + var FunctionDeclaration = (function () { + function FunctionDeclaration(id, params, body, generator) { + this.type = syntax_1.Syntax.FunctionDeclaration; + this.id = id; + this.params = params; + this.body = body; + this.generator = generator; + this.expression = false; + this.async = false; + } + return FunctionDeclaration; + }()); + exports.FunctionDeclaration = FunctionDeclaration; + var FunctionExpression = (function () { + function FunctionExpression(id, params, body, generator) { + this.type = syntax_1.Syntax.FunctionExpression; + this.id = id; + this.params = params; + this.body = body; + this.generator = generator; + this.expression = false; + this.async = false; + } + return FunctionExpression; + }()); + exports.FunctionExpression = FunctionExpression; + var Identifier = (function () { + function Identifier(name) { + this.type = syntax_1.Syntax.Identifier; + this.name = name; + } + return Identifier; + }()); + exports.Identifier = Identifier; + var IfStatement = (function () { + function IfStatement(test, consequent, alternate) { + this.type = syntax_1.Syntax.IfStatement; + this.test = test; + this.consequent = consequent; + this.alternate = alternate; + } + return IfStatement; + }()); + exports.IfStatement = IfStatement; + var Import = (function () { + function Import() { + this.type = syntax_1.Syntax.Import; + } + return Import; + }()); + exports.Import = Import; + var ImportDeclaration = (function () { + function ImportDeclaration(specifiers, source) { + this.type = syntax_1.Syntax.ImportDeclaration; + this.specifiers = specifiers; + this.source = source; + } + return ImportDeclaration; + }()); + exports.ImportDeclaration = ImportDeclaration; + var ImportDefaultSpecifier = (function () { + function ImportDefaultSpecifier(local) { + this.type = syntax_1.Syntax.ImportDefaultSpecifier; + this.local = local; + } + return ImportDefaultSpecifier; + }()); + exports.ImportDefaultSpecifier = ImportDefaultSpecifier; + var ImportNamespaceSpecifier = (function () { + function ImportNamespaceSpecifier(local) { + this.type = syntax_1.Syntax.ImportNamespaceSpecifier; + this.local = local; + } + return ImportNamespaceSpecifier; + }()); + exports.ImportNamespaceSpecifier = ImportNamespaceSpecifier; + var ImportSpecifier = (function () { + function ImportSpecifier(local, imported) { + this.type = syntax_1.Syntax.ImportSpecifier; + this.local = local; + this.imported = imported; + } + return ImportSpecifier; + }()); + exports.ImportSpecifier = ImportSpecifier; + var LabeledStatement = (function () { + function LabeledStatement(label, body) { + this.type = syntax_1.Syntax.LabeledStatement; + this.label = label; + this.body = body; + } + return LabeledStatement; + }()); + exports.LabeledStatement = LabeledStatement; + var Literal = (function () { + function Literal(value, raw) { + this.type = syntax_1.Syntax.Literal; + this.value = value; + this.raw = raw; + } + return Literal; + }()); + exports.Literal = Literal; + var MetaProperty = (function () { + function MetaProperty(meta, property) { + this.type = syntax_1.Syntax.MetaProperty; + this.meta = meta; + this.property = property; + } + return MetaProperty; + }()); + exports.MetaProperty = MetaProperty; + var MethodDefinition = (function () { + function MethodDefinition(key, computed, value, kind, isStatic) { + this.type = syntax_1.Syntax.MethodDefinition; + this.key = key; + this.computed = computed; + this.value = value; + this.kind = kind; + this.static = isStatic; + } + return MethodDefinition; + }()); + exports.MethodDefinition = MethodDefinition; + var Module = (function () { + function Module(body) { + this.type = syntax_1.Syntax.Program; + this.body = body; + this.sourceType = 'module'; + } + return Module; + }()); + exports.Module = Module; + var NewExpression = (function () { + function NewExpression(callee, args) { + this.type = syntax_1.Syntax.NewExpression; + this.callee = callee; + this.arguments = args; + } + return NewExpression; + }()); + exports.NewExpression = NewExpression; + var ObjectExpression = (function () { + function ObjectExpression(properties) { + this.type = syntax_1.Syntax.ObjectExpression; + this.properties = properties; + } + return ObjectExpression; + }()); + exports.ObjectExpression = ObjectExpression; + var ObjectPattern = (function () { + function ObjectPattern(properties) { + this.type = syntax_1.Syntax.ObjectPattern; + this.properties = properties; + } + return ObjectPattern; + }()); + exports.ObjectPattern = ObjectPattern; + var Property = (function () { + function Property(kind, key, computed, value, method, shorthand) { + this.type = syntax_1.Syntax.Property; + this.key = key; + this.computed = computed; + this.value = value; + this.kind = kind; + this.method = method; + this.shorthand = shorthand; + } + return Property; + }()); + exports.Property = Property; + var RegexLiteral = (function () { + function RegexLiteral(value, raw, pattern, flags) { + this.type = syntax_1.Syntax.Literal; + this.value = value; + this.raw = raw; + this.regex = { pattern: pattern, flags: flags }; + } + return RegexLiteral; + }()); + exports.RegexLiteral = RegexLiteral; + var RestElement = (function () { + function RestElement(argument) { + this.type = syntax_1.Syntax.RestElement; + this.argument = argument; + } + return RestElement; + }()); + exports.RestElement = RestElement; + var RestProperty = (function () { + function RestProperty(argument) { + this.type = syntax_1.Syntax.RestProperty; + this.argument = argument; + } + return RestProperty; + }()); + exports.RestProperty = RestProperty; + var ReturnStatement = (function () { + function ReturnStatement(argument) { + this.type = syntax_1.Syntax.ReturnStatement; + this.argument = argument; + } + return ReturnStatement; + }()); + exports.ReturnStatement = ReturnStatement; + var Script = (function () { + function Script(body) { + this.type = syntax_1.Syntax.Program; + this.body = body; + this.sourceType = 'script'; + } + return Script; + }()); + exports.Script = Script; + var SequenceExpression = (function () { + function SequenceExpression(expressions) { + this.type = syntax_1.Syntax.SequenceExpression; + this.expressions = expressions; + } + return SequenceExpression; + }()); + exports.SequenceExpression = SequenceExpression; + var SpreadElement = (function () { + function SpreadElement(argument) { + this.type = syntax_1.Syntax.SpreadElement; + this.argument = argument; + } + return SpreadElement; + }()); + exports.SpreadElement = SpreadElement; + var SpreadProperty = (function () { + function SpreadProperty(argument) { + this.type = syntax_1.Syntax.SpreadProperty; + this.argument = argument; + } + return SpreadProperty; + }()); + exports.SpreadProperty = SpreadProperty; + var StaticMemberExpression = (function () { + function StaticMemberExpression(object, property) { + this.type = syntax_1.Syntax.MemberExpression; + this.computed = false; + this.object = object; + this.property = property; + } + return StaticMemberExpression; + }()); + exports.StaticMemberExpression = StaticMemberExpression; + var Super = (function () { + function Super() { + this.type = syntax_1.Syntax.Super; + } + return Super; + }()); + exports.Super = Super; + var SwitchCase = (function () { + function SwitchCase(test, consequent) { + this.type = syntax_1.Syntax.SwitchCase; + this.test = test; + this.consequent = consequent; + } + return SwitchCase; + }()); + exports.SwitchCase = SwitchCase; + var SwitchStatement = (function () { + function SwitchStatement(discriminant, cases) { + this.type = syntax_1.Syntax.SwitchStatement; + this.discriminant = discriminant; + this.cases = cases; + } + return SwitchStatement; + }()); + exports.SwitchStatement = SwitchStatement; + var TaggedTemplateExpression = (function () { + function TaggedTemplateExpression(tag, quasi) { + this.type = syntax_1.Syntax.TaggedTemplateExpression; + this.tag = tag; + this.quasi = quasi; + } + return TaggedTemplateExpression; + }()); + exports.TaggedTemplateExpression = TaggedTemplateExpression; + var TemplateElement = (function () { + function TemplateElement(value, tail) { + this.type = syntax_1.Syntax.TemplateElement; + this.value = value; + this.tail = tail; + } + return TemplateElement; + }()); + exports.TemplateElement = TemplateElement; + var TemplateLiteral = (function () { + function TemplateLiteral(quasis, expressions) { + this.type = syntax_1.Syntax.TemplateLiteral; + this.quasis = quasis; + this.expressions = expressions; + } + return TemplateLiteral; + }()); + exports.TemplateLiteral = TemplateLiteral; + var ThisExpression = (function () { + function ThisExpression() { + this.type = syntax_1.Syntax.ThisExpression; + } + return ThisExpression; + }()); + exports.ThisExpression = ThisExpression; + var ThrowStatement = (function () { + function ThrowStatement(argument) { + this.type = syntax_1.Syntax.ThrowStatement; + this.argument = argument; + } + return ThrowStatement; + }()); + exports.ThrowStatement = ThrowStatement; + var TryStatement = (function () { + function TryStatement(block, handler, finalizer) { + this.type = syntax_1.Syntax.TryStatement; + this.block = block; + this.handler = handler; + this.finalizer = finalizer; + } + return TryStatement; + }()); + exports.TryStatement = TryStatement; + var UnaryExpression = (function () { + function UnaryExpression(operator, argument) { + this.type = syntax_1.Syntax.UnaryExpression; + this.operator = operator; + this.argument = argument; + this.prefix = true; + } + return UnaryExpression; + }()); + exports.UnaryExpression = UnaryExpression; + var UpdateExpression = (function () { + function UpdateExpression(operator, argument, prefix) { + this.type = syntax_1.Syntax.UpdateExpression; + this.operator = operator; + this.argument = argument; + this.prefix = prefix; + } + return UpdateExpression; + }()); + exports.UpdateExpression = UpdateExpression; + var VariableDeclaration = (function () { + function VariableDeclaration(declarations, kind) { + this.type = syntax_1.Syntax.VariableDeclaration; + this.declarations = declarations; + this.kind = kind; + } + return VariableDeclaration; + }()); + exports.VariableDeclaration = VariableDeclaration; + var VariableDeclarator = (function () { + function VariableDeclarator(id, init) { + this.type = syntax_1.Syntax.VariableDeclarator; + this.id = id; + this.init = init; + } + return VariableDeclarator; + }()); + exports.VariableDeclarator = VariableDeclarator; + var WhileStatement = (function () { + function WhileStatement(test, body) { + this.type = syntax_1.Syntax.WhileStatement; + this.test = test; + this.body = body; + } + return WhileStatement; + }()); + exports.WhileStatement = WhileStatement; + var WithStatement = (function () { + function WithStatement(object, body) { + this.type = syntax_1.Syntax.WithStatement; + this.object = object; + this.body = body; + } + return WithStatement; + }()); + exports.WithStatement = WithStatement; + var YieldExpression = (function () { + function YieldExpression(argument, delegate) { + this.type = syntax_1.Syntax.YieldExpression; + this.argument = argument; + this.delegate = delegate; + } + return YieldExpression; + }()); + exports.YieldExpression = YieldExpression; + + +/***/ }, +/* 8 */ +/***/ function(module, exports, __webpack_require__) { + + "use strict"; + var assert_1 = __webpack_require__(9); + var error_handler_1 = __webpack_require__(10); + var messages_1 = __webpack_require__(11); + var Node = __webpack_require__(7); + var scanner_1 = __webpack_require__(12); + var syntax_1 = __webpack_require__(2); + var token_1 = __webpack_require__(13); + var ArrowParameterPlaceHolder = 'ArrowParameterPlaceHolder'; + var Parser = (function () { + function Parser(code, options, delegate) { + if (options === void 0) { options = {}; } + this.config = { + range: (typeof options.range === 'boolean') && options.range, + loc: (typeof options.loc === 'boolean') && options.loc, + source: null, + tokens: (typeof options.tokens === 'boolean') && options.tokens, + comment: (typeof options.comment === 'boolean') && options.comment, + tolerant: (typeof options.tolerant === 'boolean') && options.tolerant + }; + if (this.config.loc && options.source && options.source !== null) { + this.config.source = String(options.source); + } + this.delegate = delegate; + this.errorHandler = new error_handler_1.ErrorHandler(); + this.errorHandler.tolerant = this.config.tolerant; + this.scanner = new scanner_1.Scanner(code, this.errorHandler); + this.scanner.trackComment = this.config.comment; + this.operatorPrecedence = { + ')': 0, + ';': 0, + ',': 0, + '=': 0, + ']': 0, + '||': 1, + '&&': 2, + '|': 3, + '^': 4, + '&': 5, + '==': 6, + '!=': 6, + '===': 6, + '!==': 6, + '<': 7, + '>': 7, + '<=': 7, + '>=': 7, + '<<': 8, + '>>': 8, + '>>>': 8, + '+': 9, + '-': 9, + '*': 11, + '/': 11, + '%': 11 + }; + this.lookahead = { + type: 2 /* EOF */, + value: '', + lineNumber: this.scanner.lineNumber, + lineStart: 0, + start: 0, + end: 0 + }; + this.hasLineTerminator = false; + this.context = { + isModule: false, + await: false, + allowIn: true, + allowStrictDirective: true, + allowYield: true, + firstCoverInitializedNameError: null, + isAssignmentTarget: false, + isBindingElement: false, + inFunctionBody: false, + inIteration: false, + inSwitch: false, + labelSet: {}, + strict: false + }; + this.tokens = []; + this.startMarker = { + index: 0, + line: this.scanner.lineNumber, + column: 0 + }; + this.lastMarker = { + index: 0, + line: this.scanner.lineNumber, + column: 0 + }; + this.nextToken(); + this.lastMarker = { + index: this.scanner.index, + line: this.scanner.lineNumber, + column: this.scanner.index - this.scanner.lineStart + }; + } + Parser.prototype.throwError = function (messageFormat) { + var values = []; + for (var _i = 1; _i < arguments.length; _i++) { + values[_i - 1] = arguments[_i]; + } + var args = Array.prototype.slice.call(arguments, 1); + var msg = messageFormat.replace(/%(\d)/g, function (whole, idx) { + assert_1.assert(idx < args.length, 'Message reference must be in range'); + return args[idx]; + }); + var index = this.lastMarker.index; + var line = this.lastMarker.line; + var column = this.lastMarker.column + 1; + throw this.errorHandler.createError(index, line, column, msg); + }; + Parser.prototype.tolerateError = function (messageFormat) { + var values = []; + for (var _i = 1; _i < arguments.length; _i++) { + values[_i - 1] = arguments[_i]; + } + var args = Array.prototype.slice.call(arguments, 1); + var msg = messageFormat.replace(/%(\d)/g, function (whole, idx) { + assert_1.assert(idx < args.length, 'Message reference must be in range'); + return args[idx]; + }); + var index = this.lastMarker.index; + var line = this.scanner.lineNumber; + var column = this.lastMarker.column + 1; + this.errorHandler.tolerateError(index, line, column, msg); + }; + // Throw an exception because of the token. + Parser.prototype.unexpectedTokenError = function (token, message) { + var msg = message || messages_1.Messages.UnexpectedToken; + var value; + if (token) { + if (!message) { + msg = (token.type === 2 /* EOF */) ? messages_1.Messages.UnexpectedEOS : + (token.type === 3 /* Identifier */) ? messages_1.Messages.UnexpectedIdentifier : + (token.type === 6 /* NumericLiteral */) ? messages_1.Messages.UnexpectedNumber : + (token.type === 8 /* StringLiteral */) ? messages_1.Messages.UnexpectedString : + (token.type === 10 /* Template */) ? messages_1.Messages.UnexpectedTemplate : + messages_1.Messages.UnexpectedToken; + if (token.type === 4 /* Keyword */) { + if (this.scanner.isFutureReservedWord(token.value)) { + msg = messages_1.Messages.UnexpectedReserved; + } + else if (this.context.strict && this.scanner.isStrictModeReservedWord(token.value)) { + msg = messages_1.Messages.StrictReservedWord; + } + } + } + value = token.value; + } + else { + value = 'ILLEGAL'; + } + msg = msg.replace('%0', value); + if (token && typeof token.lineNumber === 'number') { + var index = token.start; + var line = token.lineNumber; + var lastMarkerLineStart = this.lastMarker.index - this.lastMarker.column; + var column = token.start - lastMarkerLineStart + 1; + return this.errorHandler.createError(index, line, column, msg); + } + else { + var index = this.lastMarker.index; + var line = this.lastMarker.line; + var column = this.lastMarker.column + 1; + return this.errorHandler.createError(index, line, column, msg); + } + }; + Parser.prototype.throwUnexpectedToken = function (token, message) { + throw this.unexpectedTokenError(token, message); + }; + Parser.prototype.tolerateUnexpectedToken = function (token, message) { + this.errorHandler.tolerate(this.unexpectedTokenError(token, message)); + }; + Parser.prototype.collectComments = function () { + if (!this.config.comment) { + this.scanner.scanComments(); + } + else { + var comments = this.scanner.scanComments(); + if (comments.length > 0 && this.delegate) { + for (var i = 0; i < comments.length; ++i) { + var e = comments[i]; + var node = void 0; + node = { + type: e.multiLine ? 'BlockComment' : 'LineComment', + value: this.scanner.source.slice(e.slice[0], e.slice[1]) + }; + if (this.config.range) { + node.range = e.range; + } + if (this.config.loc) { + node.loc = e.loc; + } + var metadata = { + start: { + line: e.loc.start.line, + column: e.loc.start.column, + offset: e.range[0] + }, + end: { + line: e.loc.end.line, + column: e.loc.end.column, + offset: e.range[1] + } + }; + this.delegate(node, metadata); + } + } + } + }; + // From internal representation to an external structure + Parser.prototype.getTokenRaw = function (token) { + return this.scanner.source.slice(token.start, token.end); + }; + Parser.prototype.convertToken = function (token) { + var t = { + type: token_1.TokenName[token.type], + value: this.getTokenRaw(token) + }; + if (this.config.range) { + t.range = [token.start, token.end]; + } + if (this.config.loc) { + t.loc = { + start: { + line: this.startMarker.line, + column: this.startMarker.column + }, + end: { + line: this.scanner.lineNumber, + column: this.scanner.index - this.scanner.lineStart + } + }; + } + if (token.type === 9 /* RegularExpression */) { + var pattern = token.pattern; + var flags = token.flags; + t.regex = { pattern: pattern, flags: flags }; + } + return t; + }; + Parser.prototype.nextToken = function () { + var token = this.lookahead; + this.lastMarker.index = this.scanner.index; + this.lastMarker.line = this.scanner.lineNumber; + this.lastMarker.column = this.scanner.index - this.scanner.lineStart; + this.collectComments(); + if (this.scanner.index !== this.startMarker.index) { + this.startMarker.index = this.scanner.index; + this.startMarker.line = this.scanner.lineNumber; + this.startMarker.column = this.scanner.index - this.scanner.lineStart; + } + var next = this.scanner.lex(); + this.hasLineTerminator = (token.lineNumber !== next.lineNumber); + if (next && this.context.strict && next.type === 3 /* Identifier */) { + if (this.scanner.isStrictModeReservedWord(next.value)) { + next.type = 4 /* Keyword */; + } + } + this.lookahead = next; + if (this.config.tokens && next.type !== 2 /* EOF */) { + this.tokens.push(this.convertToken(next)); + } + return token; + }; + Parser.prototype.nextRegexToken = function () { + this.collectComments(); + var token = this.scanner.scanRegExp(); + if (this.config.tokens) { + // Pop the previous token, '/' or '/=' + // This is added from the lookahead token. + this.tokens.pop(); + this.tokens.push(this.convertToken(token)); + } + // Prime the next lookahead. + this.lookahead = token; + this.nextToken(); + return token; + }; + Parser.prototype.createNode = function () { + return { + index: this.startMarker.index, + line: this.startMarker.line, + column: this.startMarker.column + }; + }; + Parser.prototype.startNode = function (token) { + return { + index: token.start, + line: token.lineNumber, + column: token.start - token.lineStart + }; + }; + Parser.prototype.finalize = function (marker, node) { + if (this.config.range) { + node.range = [marker.index, this.lastMarker.index]; + } + if (this.config.loc) { + node.loc = { + start: { + line: marker.line, + column: marker.column, + }, + end: { + line: this.lastMarker.line, + column: this.lastMarker.column + } + }; + if (this.config.source) { + node.loc.source = this.config.source; + } + } + if (this.delegate) { + var metadata = { + start: { + line: marker.line, + column: marker.column, + offset: marker.index + }, + end: { + line: this.lastMarker.line, + column: this.lastMarker.column, + offset: this.lastMarker.index + } + }; + this.delegate(node, metadata); + } + return node; + }; + // Expect the next token to match the specified punctuator. + // If not, an exception will be thrown. + Parser.prototype.expect = function (value) { + var token = this.nextToken(); + if (token.type !== 7 /* Punctuator */ || token.value !== value) { + this.throwUnexpectedToken(token); + } + }; + // Quietly expect a comma when in tolerant mode, otherwise delegates to expect(). + Parser.prototype.expectCommaSeparator = function () { + if (this.config.tolerant) { + var token = this.lookahead; + if (token.type === 7 /* Punctuator */ && token.value === ',') { + this.nextToken(); + } + else if (token.type === 7 /* Punctuator */ && token.value === ';') { + this.nextToken(); + this.tolerateUnexpectedToken(token); + } + else { + this.tolerateUnexpectedToken(token, messages_1.Messages.UnexpectedToken); + } + } + else { + this.expect(','); + } + }; + // Expect the next token to match the specified keyword. + // If not, an exception will be thrown. + Parser.prototype.expectKeyword = function (keyword) { + var token = this.nextToken(); + if (token.type !== 4 /* Keyword */ || token.value !== keyword) { + this.throwUnexpectedToken(token); + } + }; + // Return true if the next token matches the specified punctuator. + Parser.prototype.match = function (value) { + return this.lookahead.type === 7 /* Punctuator */ && this.lookahead.value === value; + }; + // Return true if the next token matches the specified keyword + Parser.prototype.matchKeyword = function (keyword) { + return this.lookahead.type === 4 /* Keyword */ && this.lookahead.value === keyword; + }; + // Return true if the next token matches the specified contextual keyword + // (where an identifier is sometimes a keyword depending on the context) + Parser.prototype.matchContextualKeyword = function (keyword) { + return this.lookahead.type === 3 /* Identifier */ && this.lookahead.value === keyword; + }; + // Return true if the next token is an assignment operator + Parser.prototype.matchAssign = function () { + if (this.lookahead.type !== 7 /* Punctuator */) { + return false; + } + var op = this.lookahead.value; + return op === '=' || + op === '*=' || + op === '**=' || + op === '/=' || + op === '%=' || + op === '+=' || + op === '-=' || + op === '<<=' || + op === '>>=' || + op === '>>>=' || + op === '&=' || + op === '^=' || + op === '|='; + }; + // Cover grammar support. + // + // When an assignment expression position starts with an left parenthesis, the determination of the type + // of the syntax is to be deferred arbitrarily long until the end of the parentheses pair (plus a lookahead) + // or the first comma. This situation also defers the determination of all the expressions nested in the pair. + // + // There are three productions that can be parsed in a parentheses pair that needs to be determined + // after the outermost pair is closed. They are: + // + // 1. AssignmentExpression + // 2. BindingElements + // 3. AssignmentTargets + // + // In order to avoid exponential backtracking, we use two flags to denote if the production can be + // binding element or assignment target. + // + // The three productions have the relationship: + // + // BindingElements ⊆ AssignmentTargets ⊆ AssignmentExpression + // + // with a single exception that CoverInitializedName when used directly in an Expression, generates + // an early error. Therefore, we need the third state, firstCoverInitializedNameError, to track the + // first usage of CoverInitializedName and report it when we reached the end of the parentheses pair. + // + // isolateCoverGrammar function runs the given parser function with a new cover grammar context, and it does not + // effect the current flags. This means the production the parser parses is only used as an expression. Therefore + // the CoverInitializedName check is conducted. + // + // inheritCoverGrammar function runs the given parse function with a new cover grammar context, and it propagates + // the flags outside of the parser. This means the production the parser parses is used as a part of a potential + // pattern. The CoverInitializedName check is deferred. + Parser.prototype.isolateCoverGrammar = function (parseFunction) { + var previousIsBindingElement = this.context.isBindingElement; + var previousIsAssignmentTarget = this.context.isAssignmentTarget; + var previousFirstCoverInitializedNameError = this.context.firstCoverInitializedNameError; + this.context.isBindingElement = true; + this.context.isAssignmentTarget = true; + this.context.firstCoverInitializedNameError = null; + var result = parseFunction.call(this); + if (this.context.firstCoverInitializedNameError !== null) { + this.throwUnexpectedToken(this.context.firstCoverInitializedNameError); + } + this.context.isBindingElement = previousIsBindingElement; + this.context.isAssignmentTarget = previousIsAssignmentTarget; + this.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError; + return result; + }; + Parser.prototype.inheritCoverGrammar = function (parseFunction) { + var previousIsBindingElement = this.context.isBindingElement; + var previousIsAssignmentTarget = this.context.isAssignmentTarget; + var previousFirstCoverInitializedNameError = this.context.firstCoverInitializedNameError; + this.context.isBindingElement = true; + this.context.isAssignmentTarget = true; + this.context.firstCoverInitializedNameError = null; + var result = parseFunction.call(this); + this.context.isBindingElement = this.context.isBindingElement && previousIsBindingElement; + this.context.isAssignmentTarget = this.context.isAssignmentTarget && previousIsAssignmentTarget; + this.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError || this.context.firstCoverInitializedNameError; + return result; + }; + Parser.prototype.consumeSemicolon = function () { + if (this.match(';')) { + this.nextToken(); + } + else if (!this.hasLineTerminator) { + if (this.lookahead.type !== 2 /* EOF */ && !this.match('}')) { + this.throwUnexpectedToken(this.lookahead); + } + this.lastMarker.index = this.startMarker.index; + this.lastMarker.line = this.startMarker.line; + this.lastMarker.column = this.startMarker.column; + } + }; + // https://tc39.github.io/ecma262/#sec-primary-expression + Parser.prototype.parsePrimaryExpression = function () { + var node = this.createNode(); + var expr; + var token, raw; + switch (this.lookahead.type) { + case 3 /* Identifier */: + if ((this.context.isModule || this.context.await) && this.lookahead.value === 'await') { + this.tolerateUnexpectedToken(this.lookahead); + } + expr = this.matchAsyncFunction() ? this.parseFunctionExpression() : this.finalize(node, new Node.Identifier(this.nextToken().value)); + break; + case 6 /* NumericLiteral */: + case 8 /* StringLiteral */: + if (this.context.strict && this.lookahead.octal) { + this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.StrictOctalLiteral); + } + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + token = this.nextToken(); + raw = this.getTokenRaw(token); + expr = this.finalize(node, new Node.Literal(token.value, raw)); + break; + case 1 /* BooleanLiteral */: + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + token = this.nextToken(); + raw = this.getTokenRaw(token); + expr = this.finalize(node, new Node.Literal(token.value === 'true', raw)); + break; + case 5 /* NullLiteral */: + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + token = this.nextToken(); + raw = this.getTokenRaw(token); + expr = this.finalize(node, new Node.Literal(null, raw)); + break; + case 10 /* Template */: + expr = this.parseTemplateLiteral(); + break; + case 7 /* Punctuator */: + switch (this.lookahead.value) { + case '(': + this.context.isBindingElement = false; + expr = this.inheritCoverGrammar(this.parseGroupExpression); + break; + case '[': + expr = this.inheritCoverGrammar(this.parseArrayInitializer); + break; + case '{': + expr = this.inheritCoverGrammar(this.parseObjectInitializer); + break; + case '/': + case '/=': + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + this.scanner.index = this.startMarker.index; + token = this.nextRegexToken(); + raw = this.getTokenRaw(token); + expr = this.finalize(node, new Node.RegexLiteral(token.regex, raw, token.pattern, token.flags)); + break; + default: + expr = this.throwUnexpectedToken(this.nextToken()); + } + break; + case 4 /* Keyword */: + if (!this.context.strict && this.context.allowYield && this.matchKeyword('yield')) { + expr = this.parseIdentifierName(); + } + else if (!this.context.strict && this.matchKeyword('let')) { + expr = this.finalize(node, new Node.Identifier(this.nextToken().value)); + } + else { + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + if (this.matchKeyword('function')) { + expr = this.parseFunctionExpression(); + } + else if (this.matchKeyword('this')) { + this.nextToken(); + expr = this.finalize(node, new Node.ThisExpression()); + } + else if (this.matchKeyword('class')) { + expr = this.parseClassExpression(); + } + else if (this.matchImportCall()) { + expr = this.parseImportCall(); + } + else { + expr = this.throwUnexpectedToken(this.nextToken()); + } + } + break; + default: + expr = this.throwUnexpectedToken(this.nextToken()); + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-array-initializer + Parser.prototype.parseSpreadElement = function () { + var node = this.createNode(); + this.expect('...'); + var arg = this.inheritCoverGrammar(this.parseAssignmentExpression); + return this.finalize(node, new Node.SpreadElement(arg)); + }; + Parser.prototype.parseArrayInitializer = function () { + var node = this.createNode(); + var elements = []; + this.expect('['); + while (!this.match(']')) { + if (this.match(',')) { + this.nextToken(); + elements.push(null); + } + else if (this.match('...')) { + var element = this.parseSpreadElement(); + if (!this.match(']')) { + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + this.expect(','); + } + elements.push(element); + } + else { + elements.push(this.inheritCoverGrammar(this.parseAssignmentExpression)); + if (!this.match(']')) { + this.expect(','); + } + } + } + this.expect(']'); + return this.finalize(node, new Node.ArrayExpression(elements)); + }; + // https://tc39.github.io/ecma262/#sec-object-initializer + Parser.prototype.parsePropertyMethod = function (params) { + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + var previousStrict = this.context.strict; + var previousAllowStrictDirective = this.context.allowStrictDirective; + this.context.allowStrictDirective = params.simple; + var body = this.isolateCoverGrammar(this.parseFunctionSourceElements); + if (this.context.strict && params.firstRestricted) { + this.tolerateUnexpectedToken(params.firstRestricted, params.message); + } + if (this.context.strict && params.stricted) { + this.tolerateUnexpectedToken(params.stricted, params.message); + } + this.context.strict = previousStrict; + this.context.allowStrictDirective = previousAllowStrictDirective; + return body; + }; + Parser.prototype.parsePropertyMethodFunction = function () { + var isGenerator = false; + var node = this.createNode(); + var previousAllowYield = this.context.allowYield; + this.context.allowYield = false; + var params = this.parseFormalParameters(); + var method = this.parsePropertyMethod(params); + this.context.allowYield = previousAllowYield; + return this.finalize(node, new Node.FunctionExpression(null, params.params, method, isGenerator)); + }; + Parser.prototype.parsePropertyMethodAsyncFunction = function () { + var node = this.createNode(); + var previousAllowYield = this.context.allowYield; + var previousAwait = this.context.await; + this.context.allowYield = false; + this.context.await = true; + var params = this.parseFormalParameters(); + var method = this.parsePropertyMethod(params); + this.context.allowYield = previousAllowYield; + this.context.await = previousAwait; + return this.finalize(node, new Node.AsyncFunctionExpression(null, params.params, method)); + }; + Parser.prototype.parseObjectPropertyKey = function () { + var node = this.createNode(); + var token = this.nextToken(); + var key; + switch (token.type) { + case 8 /* StringLiteral */: + case 6 /* NumericLiteral */: + if (this.context.strict && token.octal) { + this.tolerateUnexpectedToken(token, messages_1.Messages.StrictOctalLiteral); + } + var raw = this.getTokenRaw(token); + key = this.finalize(node, new Node.Literal(token.value, raw)); + break; + case 3 /* Identifier */: + case 1 /* BooleanLiteral */: + case 5 /* NullLiteral */: + case 4 /* Keyword */: + key = this.finalize(node, new Node.Identifier(token.value)); + break; + case 7 /* Punctuator */: + if (token.value === '[') { + key = this.isolateCoverGrammar(this.parseAssignmentExpression); + this.expect(']'); + } + else { + key = this.throwUnexpectedToken(token); + } + break; + default: + key = this.throwUnexpectedToken(token); + } + return key; + }; + Parser.prototype.isPropertyKey = function (key, value) { + return (key.type === syntax_1.Syntax.Identifier && key.name === value) || + (key.type === syntax_1.Syntax.Literal && key.value === value); + }; + Parser.prototype.parseObjectProperty = function (hasProto) { + var node = this.createNode(); + var token = this.lookahead; + var kind; + var key = null; + var value = null; + var computed = false; + var method = false; + var shorthand = false; + var isAsync = false; + if (token.type === 3 /* Identifier */) { + var id = token.value; + this.nextToken(); + if (id === 'async' && !this.hasLineTerminator) { + computed = this.match('['); + if (computed) { + isAsync = true; + key = this.parseObjectPropertyKey(); + } + else { + var punctuator = this.lookahead.value; + if (punctuator !== ':' && punctuator !== '(' && punctuator !== '*') { + isAsync = true; + token = this.lookahead; + id = token.value; + this.nextToken(); + } + key = this.finalize(node, new Node.Identifier(id)); + } + } + else { + key = this.finalize(node, new Node.Identifier(id)); + } + } + else if (this.match('*')) { + this.nextToken(); + } + else { + computed = this.match('['); + key = this.parseObjectPropertyKey(); + } + var lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead); + if (token.type === 3 /* Identifier */ && !isAsync && token.value === 'get' && lookaheadPropertyKey) { + kind = 'get'; + computed = this.match('['); + key = this.parseObjectPropertyKey(); + this.context.allowYield = false; + value = this.parseGetterMethod(); + } + else if (token.type === 3 /* Identifier */ && !isAsync && token.value === 'set' && lookaheadPropertyKey) { + kind = 'set'; + computed = this.match('['); + key = this.parseObjectPropertyKey(); + value = this.parseSetterMethod(); + } + else if (token.type === 7 /* Punctuator */ && token.value === '*' && lookaheadPropertyKey) { + kind = 'init'; + computed = this.match('['); + key = this.parseObjectPropertyKey(); + value = this.parseGeneratorMethod(); + method = true; + } + else { + if (!key) { + this.throwUnexpectedToken(this.lookahead); + } + kind = 'init'; + if (this.match(':') && !isAsync) { + if (!computed && this.isPropertyKey(key, '__proto__')) { + if (hasProto.value) { + this.tolerateError(messages_1.Messages.DuplicateProtoProperty); + } + hasProto.value = true; + } + this.nextToken(); + value = this.inheritCoverGrammar(this.parseAssignmentExpression); + } + else if (this.match('(')) { + value = isAsync ? this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction(); + method = true; + } + else if (token.type === 3 /* Identifier */) { + var id = this.finalize(node, new Node.Identifier(token.value)); + if (this.match('=')) { + this.context.firstCoverInitializedNameError = this.lookahead; + this.nextToken(); + shorthand = true; + var init = this.isolateCoverGrammar(this.parseAssignmentExpression); + value = this.finalize(node, new Node.AssignmentPattern(id, init)); + } + else { + shorthand = true; + value = id; + } + } + else { + this.throwUnexpectedToken(this.nextToken()); + } + } + return this.finalize(node, new Node.Property(kind, key, computed, value, method, shorthand)); + }; + Parser.prototype.parseSpreadProperty = function () { + var node = this.createNode(); + this.expect('...'); + var arg = this.inheritCoverGrammar(this.parseAssignmentExpression); + return this.finalize(node, new Node.SpreadProperty(arg)); + }; + Parser.prototype.parseObjectInitializer = function () { + var node = this.createNode(); + this.expect('{'); + var properties = []; + var hasProto = { value: false }; + while (!this.match('}')) { + properties.push(this.match('...') ? this.parseSpreadProperty() : this.parseObjectProperty(hasProto)); + if (!this.match('}')) { + this.expectCommaSeparator(); + } + } + this.expect('}'); + return this.finalize(node, new Node.ObjectExpression(properties)); + }; + // https://tc39.github.io/ecma262/#sec-template-literals + Parser.prototype.parseTemplateHead = function () { + assert_1.assert(this.lookahead.head, 'Template literal must start with a template head'); + var node = this.createNode(); + var token = this.nextToken(); + var raw = token.value; + var cooked = token.cooked; + return this.finalize(node, new Node.TemplateElement({ raw: raw, cooked: cooked }, token.tail)); + }; + Parser.prototype.parseTemplateElement = function () { + if (this.lookahead.type !== 10 /* Template */) { + this.throwUnexpectedToken(); + } + var node = this.createNode(); + var token = this.nextToken(); + var raw = token.value; + var cooked = token.cooked; + return this.finalize(node, new Node.TemplateElement({ raw: raw, cooked: cooked }, token.tail)); + }; + Parser.prototype.parseTemplateLiteral = function () { + var node = this.createNode(); + var expressions = []; + var quasis = []; + var quasi = this.parseTemplateHead(); + quasis.push(quasi); + while (!quasi.tail) { + expressions.push(this.parseExpression()); + quasi = this.parseTemplateElement(); + quasis.push(quasi); + } + return this.finalize(node, new Node.TemplateLiteral(quasis, expressions)); + }; + // https://tc39.github.io/ecma262/#sec-grouping-operator + Parser.prototype.reinterpretExpressionAsPattern = function (expr) { + switch (expr.type) { + case syntax_1.Syntax.Identifier: + case syntax_1.Syntax.MemberExpression: + case syntax_1.Syntax.RestElement: + case syntax_1.Syntax.AssignmentPattern: + break; + case syntax_1.Syntax.SpreadElement: + expr.type = syntax_1.Syntax.RestElement; + this.reinterpretExpressionAsPattern(expr.argument); + break; + case syntax_1.Syntax.SpreadProperty: + expr.type = syntax_1.Syntax.RestProperty; + this.reinterpretExpressionAsPattern(expr.argument); + break; + case syntax_1.Syntax.ArrayExpression: + expr.type = syntax_1.Syntax.ArrayPattern; + for (var i = 0; i < expr.elements.length; i++) { + if (expr.elements[i] !== null) { + this.reinterpretExpressionAsPattern(expr.elements[i]); + } + } + break; + case syntax_1.Syntax.ObjectExpression: + expr.type = syntax_1.Syntax.ObjectPattern; + for (var i = 0; i < expr.properties.length; i++) { + var property = expr.properties[i]; + this.reinterpretExpressionAsPattern(property.type === syntax_1.Syntax.SpreadProperty ? property : property.value); + } + break; + case syntax_1.Syntax.AssignmentExpression: + expr.type = syntax_1.Syntax.AssignmentPattern; + delete expr.operator; + this.reinterpretExpressionAsPattern(expr.left); + break; + default: + // Allow other node type for tolerant parsing. + break; + } + }; + Parser.prototype.parseGroupExpression = function () { + var expr; + this.expect('('); + if (this.match(')')) { + this.nextToken(); + if (!this.match('=>')) { + this.expect('=>'); + } + expr = { + type: ArrowParameterPlaceHolder, + params: [], + async: false + }; + } + else { + var startToken = this.lookahead; + var params = []; + if (this.match('...')) { + expr = this.parseRestElement(params); + this.expect(')'); + if (!this.match('=>')) { + this.expect('=>'); + } + expr = { + type: ArrowParameterPlaceHolder, + params: [expr], + async: false + }; + } + else { + var arrow = false; + this.context.isBindingElement = true; + expr = this.inheritCoverGrammar(this.parseAssignmentExpression); + if (this.match(',')) { + var expressions = []; + this.context.isAssignmentTarget = false; + expressions.push(expr); + while (this.lookahead.type !== 2 /* EOF */) { + if (!this.match(',')) { + break; + } + this.nextToken(); + if (this.match(')')) { + this.nextToken(); + for (var i = 0; i < expressions.length; i++) { + this.reinterpretExpressionAsPattern(expressions[i]); + } + arrow = true; + expr = { + type: ArrowParameterPlaceHolder, + params: expressions, + async: false + }; + } + else if (this.match('...')) { + if (!this.context.isBindingElement) { + this.throwUnexpectedToken(this.lookahead); + } + expressions.push(this.parseRestElement(params)); + this.expect(')'); + if (!this.match('=>')) { + this.expect('=>'); + } + this.context.isBindingElement = false; + for (var i = 0; i < expressions.length; i++) { + this.reinterpretExpressionAsPattern(expressions[i]); + } + arrow = true; + expr = { + type: ArrowParameterPlaceHolder, + params: expressions, + async: false + }; + } + else { + expressions.push(this.inheritCoverGrammar(this.parseAssignmentExpression)); + } + if (arrow) { + break; + } + } + if (!arrow) { + expr = this.finalize(this.startNode(startToken), new Node.SequenceExpression(expressions)); + } + } + if (!arrow) { + this.expect(')'); + if (this.match('=>')) { + if (expr.type === syntax_1.Syntax.Identifier && expr.name === 'yield') { + arrow = true; + expr = { + type: ArrowParameterPlaceHolder, + params: [expr], + async: false + }; + } + if (!arrow) { + if (!this.context.isBindingElement) { + this.throwUnexpectedToken(this.lookahead); + } + if (expr.type === syntax_1.Syntax.SequenceExpression) { + for (var i = 0; i < expr.expressions.length; i++) { + this.reinterpretExpressionAsPattern(expr.expressions[i]); + } + } + else { + this.reinterpretExpressionAsPattern(expr); + } + var params_1 = (expr.type === syntax_1.Syntax.SequenceExpression ? expr.expressions : [expr]); + expr = { + type: ArrowParameterPlaceHolder, + params: params_1, + async: false + }; + } + } + this.context.isBindingElement = false; + } + } + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-left-hand-side-expressions + Parser.prototype.parseArguments = function () { + this.expect('('); + var args = []; + if (!this.match(')')) { + while (true) { + var expr = this.match('...') ? this.parseSpreadElement() : + this.isolateCoverGrammar(this.parseAssignmentExpression); + args.push(expr); + if (this.match(')')) { + break; + } + this.expectCommaSeparator(); + if (this.match(')')) { + break; + } + } + } + this.expect(')'); + return args; + }; + Parser.prototype.isIdentifierName = function (token) { + return token.type === 3 /* Identifier */ || + token.type === 4 /* Keyword */ || + token.type === 1 /* BooleanLiteral */ || + token.type === 5 /* NullLiteral */; + }; + Parser.prototype.parseIdentifierName = function () { + var node = this.createNode(); + var token = this.nextToken(); + if (!this.isIdentifierName(token)) { + this.throwUnexpectedToken(token); + } + return this.finalize(node, new Node.Identifier(token.value)); + }; + Parser.prototype.parseNewExpression = function () { + var node = this.createNode(); + var id = this.parseIdentifierName(); + assert_1.assert(id.name === 'new', 'New expression must start with `new`'); + var expr; + if (this.match('.')) { + this.nextToken(); + if (this.lookahead.type === 3 /* Identifier */ && this.context.inFunctionBody && this.lookahead.value === 'target') { + var property = this.parseIdentifierName(); + expr = new Node.MetaProperty(id, property); + } + else { + this.throwUnexpectedToken(this.lookahead); + } + } + else if (this.matchKeyword('import')) { + this.throwUnexpectedToken(this.lookahead); + } + else { + var callee = this.isolateCoverGrammar(this.parseLeftHandSideExpression); + var args = this.match('(') ? this.parseArguments() : []; + expr = new Node.NewExpression(callee, args); + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + } + return this.finalize(node, expr); + }; + Parser.prototype.parseAsyncArgument = function () { + var arg = this.parseAssignmentExpression(); + this.context.firstCoverInitializedNameError = null; + return arg; + }; + Parser.prototype.parseAsyncArguments = function () { + this.expect('('); + var args = []; + if (!this.match(')')) { + while (true) { + var expr = this.match('...') ? this.parseSpreadElement() : + this.isolateCoverGrammar(this.parseAsyncArgument); + args.push(expr); + if (this.match(')')) { + break; + } + this.expectCommaSeparator(); + if (this.match(')')) { + break; + } + } + } + this.expect(')'); + return args; + }; + Parser.prototype.matchImportCall = function () { + var match = this.matchKeyword('import'); + if (match) { + var state = this.scanner.saveState(); + this.scanner.scanComments(); + var next = this.scanner.lex(); + this.scanner.restoreState(state); + match = (next.type === 7 /* Punctuator */) && (next.value === '('); + } + return match; + }; + Parser.prototype.parseImportCall = function () { + var node = this.createNode(); + this.expectKeyword('import'); + return this.finalize(node, new Node.Import()); + }; + Parser.prototype.parseLeftHandSideExpressionAllowCall = function () { + var startToken = this.lookahead; + var maybeAsync = this.matchContextualKeyword('async'); + var previousAllowIn = this.context.allowIn; + this.context.allowIn = true; + var expr; + if (this.matchKeyword('super') && this.context.inFunctionBody) { + expr = this.createNode(); + this.nextToken(); + expr = this.finalize(expr, new Node.Super()); + if (!this.match('(') && !this.match('.') && !this.match('[')) { + this.throwUnexpectedToken(this.lookahead); + } + } + else { + expr = this.inheritCoverGrammar(this.matchKeyword('new') ? this.parseNewExpression : this.parsePrimaryExpression); + } + while (true) { + if (this.match('.')) { + this.context.isBindingElement = false; + this.context.isAssignmentTarget = true; + this.expect('.'); + var property = this.parseIdentifierName(); + expr = this.finalize(this.startNode(startToken), new Node.StaticMemberExpression(expr, property)); + } + else if (this.match('(')) { + var asyncArrow = maybeAsync && (startToken.lineNumber === this.lookahead.lineNumber); + this.context.isBindingElement = false; + this.context.isAssignmentTarget = false; + var args = asyncArrow ? this.parseAsyncArguments() : this.parseArguments(); + if (expr.type === syntax_1.Syntax.Import && args.length !== 1) { + this.tolerateError(messages_1.Messages.BadImportCallArity); + } + expr = this.finalize(this.startNode(startToken), new Node.CallExpression(expr, args)); + if (asyncArrow && this.match('=>')) { + expr = { + type: ArrowParameterPlaceHolder, + params: args, + async: true + }; + } + } + else if (this.match('[')) { + this.context.isBindingElement = false; + this.context.isAssignmentTarget = true; + this.expect('['); + var property = this.isolateCoverGrammar(this.parseExpression); + this.expect(']'); + expr = this.finalize(this.startNode(startToken), new Node.ComputedMemberExpression(expr, property)); + } + else if (this.lookahead.type === 10 /* Template */ && this.lookahead.head) { + var quasi = this.parseTemplateLiteral(); + expr = this.finalize(this.startNode(startToken), new Node.TaggedTemplateExpression(expr, quasi)); + } + else { + break; + } + } + this.context.allowIn = previousAllowIn; + return expr; + }; + Parser.prototype.parseSuper = function () { + var node = this.createNode(); + this.expectKeyword('super'); + if (!this.match('[') && !this.match('.')) { + this.throwUnexpectedToken(this.lookahead); + } + return this.finalize(node, new Node.Super()); + }; + Parser.prototype.parseLeftHandSideExpression = function () { + assert_1.assert(this.context.allowIn, 'callee of new expression always allow in keyword.'); + var node = this.startNode(this.lookahead); + var expr = (this.matchKeyword('super') && this.context.inFunctionBody) ? this.parseSuper() : + this.inheritCoverGrammar(this.matchKeyword('new') ? this.parseNewExpression : this.parsePrimaryExpression); + while (true) { + if (this.match('[')) { + this.context.isBindingElement = false; + this.context.isAssignmentTarget = true; + this.expect('['); + var property = this.isolateCoverGrammar(this.parseExpression); + this.expect(']'); + expr = this.finalize(node, new Node.ComputedMemberExpression(expr, property)); + } + else if (this.match('.')) { + this.context.isBindingElement = false; + this.context.isAssignmentTarget = true; + this.expect('.'); + var property = this.parseIdentifierName(); + expr = this.finalize(node, new Node.StaticMemberExpression(expr, property)); + } + else if (this.lookahead.type === 10 /* Template */ && this.lookahead.head) { + var quasi = this.parseTemplateLiteral(); + expr = this.finalize(node, new Node.TaggedTemplateExpression(expr, quasi)); + } + else { + break; + } + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-update-expressions + Parser.prototype.parseUpdateExpression = function () { + var expr; + var startToken = this.lookahead; + if (this.match('++') || this.match('--')) { + var node = this.startNode(startToken); + var token = this.nextToken(); + expr = this.inheritCoverGrammar(this.parseUnaryExpression); + if (this.context.strict && expr.type === syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) { + this.tolerateError(messages_1.Messages.StrictLHSPrefix); + } + if (!this.context.isAssignmentTarget) { + this.tolerateError(messages_1.Messages.InvalidLHSInAssignment); + } + var prefix = true; + expr = this.finalize(node, new Node.UpdateExpression(token.value, expr, prefix)); + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + } + else { + expr = this.inheritCoverGrammar(this.parseLeftHandSideExpressionAllowCall); + if (!this.hasLineTerminator && this.lookahead.type === 7 /* Punctuator */) { + if (this.match('++') || this.match('--')) { + if (this.context.strict && expr.type === syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) { + this.tolerateError(messages_1.Messages.StrictLHSPostfix); + } + if (!this.context.isAssignmentTarget) { + this.tolerateError(messages_1.Messages.InvalidLHSInAssignment); + } + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + var operator = this.nextToken().value; + var prefix = false; + expr = this.finalize(this.startNode(startToken), new Node.UpdateExpression(operator, expr, prefix)); + } + } + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-unary-operators + Parser.prototype.parseAwaitExpression = function () { + var node = this.createNode(); + this.nextToken(); + var argument = this.parseUnaryExpression(); + return this.finalize(node, new Node.AwaitExpression(argument)); + }; + Parser.prototype.parseUnaryExpression = function () { + var expr; + if (this.match('+') || this.match('-') || this.match('~') || this.match('!') || + this.matchKeyword('delete') || this.matchKeyword('void') || this.matchKeyword('typeof')) { + var node = this.startNode(this.lookahead); + var token = this.nextToken(); + expr = this.inheritCoverGrammar(this.parseUnaryExpression); + expr = this.finalize(node, new Node.UnaryExpression(token.value, expr)); + if (this.context.strict && expr.operator === 'delete' && expr.argument.type === syntax_1.Syntax.Identifier) { + this.tolerateError(messages_1.Messages.StrictDelete); + } + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + } + else if (this.context.await && this.matchContextualKeyword('await')) { + expr = this.parseAwaitExpression(); + } + else { + expr = this.parseUpdateExpression(); + } + return expr; + }; + Parser.prototype.parseExponentiationExpression = function () { + var startToken = this.lookahead; + var expr = this.inheritCoverGrammar(this.parseUnaryExpression); + if (expr.type !== syntax_1.Syntax.UnaryExpression && this.match('**')) { + this.nextToken(); + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + var left = expr; + var right = this.isolateCoverGrammar(this.parseExponentiationExpression); + expr = this.finalize(this.startNode(startToken), new Node.BinaryExpression('**', left, right)); + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-exp-operator + // https://tc39.github.io/ecma262/#sec-multiplicative-operators + // https://tc39.github.io/ecma262/#sec-additive-operators + // https://tc39.github.io/ecma262/#sec-bitwise-shift-operators + // https://tc39.github.io/ecma262/#sec-relational-operators + // https://tc39.github.io/ecma262/#sec-equality-operators + // https://tc39.github.io/ecma262/#sec-binary-bitwise-operators + // https://tc39.github.io/ecma262/#sec-binary-logical-operators + Parser.prototype.binaryPrecedence = function (token) { + var op = token.value; + var precedence; + if (token.type === 7 /* Punctuator */) { + precedence = this.operatorPrecedence[op] || 0; + } + else if (token.type === 4 /* Keyword */) { + precedence = (op === 'instanceof' || (this.context.allowIn && op === 'in')) ? 7 : 0; + } + else { + precedence = 0; + } + return precedence; + }; + Parser.prototype.parseBinaryExpression = function () { + var startToken = this.lookahead; + var expr = this.inheritCoverGrammar(this.parseExponentiationExpression); + var token = this.lookahead; + var prec = this.binaryPrecedence(token); + if (prec > 0) { + this.nextToken(); + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + var markers = [startToken, this.lookahead]; + var left = expr; + var right = this.isolateCoverGrammar(this.parseExponentiationExpression); + var stack = [left, token.value, right]; + var precedences = [prec]; + while (true) { + prec = this.binaryPrecedence(this.lookahead); + if (prec <= 0) { + break; + } + // Reduce: make a binary expression from the three topmost entries. + while ((stack.length > 2) && (prec <= precedences[precedences.length - 1])) { + right = stack.pop(); + var operator = stack.pop(); + precedences.pop(); + left = stack.pop(); + markers.pop(); + var node = this.startNode(markers[markers.length - 1]); + stack.push(this.finalize(node, new Node.BinaryExpression(operator, left, right))); + } + // Shift. + stack.push(this.nextToken().value); + precedences.push(prec); + markers.push(this.lookahead); + stack.push(this.isolateCoverGrammar(this.parseExponentiationExpression)); + } + // Final reduce to clean-up the stack. + var i = stack.length - 1; + expr = stack[i]; + markers.pop(); + while (i > 1) { + var node = this.startNode(markers.pop()); + var operator = stack[i - 1]; + expr = this.finalize(node, new Node.BinaryExpression(operator, stack[i - 2], expr)); + i -= 2; + } + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-conditional-operator + Parser.prototype.parseConditionalExpression = function () { + var startToken = this.lookahead; + var expr = this.inheritCoverGrammar(this.parseBinaryExpression); + if (this.match('?')) { + this.nextToken(); + var previousAllowIn = this.context.allowIn; + this.context.allowIn = true; + var consequent = this.isolateCoverGrammar(this.parseAssignmentExpression); + this.context.allowIn = previousAllowIn; + this.expect(':'); + var alternate = this.isolateCoverGrammar(this.parseAssignmentExpression); + expr = this.finalize(this.startNode(startToken), new Node.ConditionalExpression(expr, consequent, alternate)); + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-assignment-operators + Parser.prototype.checkPatternParam = function (options, param) { + switch (param.type) { + case syntax_1.Syntax.Identifier: + this.validateParam(options, param, param.name); + break; + case syntax_1.Syntax.RestElement: + case syntax_1.Syntax.RestProperty: + this.checkPatternParam(options, param.argument); + break; + case syntax_1.Syntax.AssignmentPattern: + this.checkPatternParam(options, param.left); + break; + case syntax_1.Syntax.ArrayPattern: + for (var i = 0; i < param.elements.length; i++) { + if (param.elements[i] !== null) { + this.checkPatternParam(options, param.elements[i]); + } + } + break; + case syntax_1.Syntax.ObjectPattern: + for (var i = 0; i < param.properties.length; i++) { + var property = param.properties[i]; + this.checkPatternParam(options, (property.type === syntax_1.Syntax.RestProperty) ? property : property.value); + } + break; + default: + break; + } + options.simple = options.simple && (param instanceof Node.Identifier); + }; + Parser.prototype.reinterpretAsCoverFormalsList = function (expr) { + var params = [expr]; + var options; + var asyncArrow = false; + switch (expr.type) { + case syntax_1.Syntax.Identifier: + break; + case ArrowParameterPlaceHolder: + params = expr.params; + asyncArrow = expr.async; + break; + default: + return null; + } + options = { + simple: true, + paramSet: {} + }; + for (var i = 0; i < params.length; ++i) { + var param = params[i]; + if (param.type === syntax_1.Syntax.AssignmentPattern) { + if (param.right.type === syntax_1.Syntax.YieldExpression) { + if (param.right.argument) { + this.throwUnexpectedToken(this.lookahead); + } + param.right.type = syntax_1.Syntax.Identifier; + param.right.name = 'yield'; + delete param.right.argument; + delete param.right.delegate; + } + } + else if (asyncArrow && param.type === syntax_1.Syntax.Identifier && param.name === 'await') { + this.throwUnexpectedToken(this.lookahead); + } + this.checkPatternParam(options, param); + params[i] = param; + } + if (this.context.strict || !this.context.allowYield) { + for (var i = 0; i < params.length; ++i) { + var param = params[i]; + if (param.type === syntax_1.Syntax.YieldExpression) { + this.throwUnexpectedToken(this.lookahead); + } + } + } + if (options.message === messages_1.Messages.StrictParamDupe) { + var token = this.context.strict ? options.stricted : options.firstRestricted; + this.throwUnexpectedToken(token, options.message); + } + return { + simple: options.simple, + params: params, + stricted: options.stricted, + firstRestricted: options.firstRestricted, + message: options.message + }; + }; + Parser.prototype.parseAssignmentExpression = function () { + var expr; + if (!this.context.allowYield && this.matchKeyword('yield')) { + expr = this.parseYieldExpression(); + } + else { + var startToken = this.lookahead; + var token = startToken; + expr = this.parseConditionalExpression(); + if (token.type === 3 /* Identifier */ && (token.lineNumber === this.lookahead.lineNumber) && token.value === 'async' && (this.lookahead.type === 3 /* Identifier */)) { + var arg = this.parsePrimaryExpression(); + expr = { + type: ArrowParameterPlaceHolder, + params: [arg], + async: true + }; + } + if (expr.type === ArrowParameterPlaceHolder || this.match('=>')) { + // https://tc39.github.io/ecma262/#sec-arrow-function-definitions + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + var isAsync = expr.async; + var list = this.reinterpretAsCoverFormalsList(expr); + if (list) { + if (this.hasLineTerminator) { + this.tolerateUnexpectedToken(this.lookahead); + } + this.context.firstCoverInitializedNameError = null; + var previousStrict = this.context.strict; + var previousAllowStrictDirective = this.context.allowStrictDirective; + this.context.allowStrictDirective = list.simple; + var previousAllowYield = this.context.allowYield; + var previousAwait = this.context.await; + this.context.allowYield = true; + this.context.await = isAsync; + var node = this.startNode(startToken); + this.expect('=>'); + var body = this.match('{') ? this.parseFunctionSourceElements() : + this.isolateCoverGrammar(this.parseAssignmentExpression); + var expression = body.type !== syntax_1.Syntax.BlockStatement; + if (this.context.strict && list.firstRestricted) { + this.throwUnexpectedToken(list.firstRestricted, list.message); + } + if (this.context.strict && list.stricted) { + this.tolerateUnexpectedToken(list.stricted, list.message); + } + expr = isAsync ? this.finalize(node, new Node.AsyncArrowFunctionExpression(list.params, body, expression)) : + this.finalize(node, new Node.ArrowFunctionExpression(list.params, body, expression)); + this.context.strict = previousStrict; + this.context.allowStrictDirective = previousAllowStrictDirective; + this.context.allowYield = previousAllowYield; + this.context.await = previousAwait; + } + } + else { + if (this.matchAssign()) { + if (!this.context.isAssignmentTarget) { + this.tolerateError(messages_1.Messages.InvalidLHSInAssignment); + } + if (this.context.strict && expr.type === syntax_1.Syntax.Identifier) { + var id = expr; + if (this.scanner.isRestrictedWord(id.name)) { + this.tolerateUnexpectedToken(token, messages_1.Messages.StrictLHSAssignment); + } + if (this.scanner.isStrictModeReservedWord(id.name)) { + this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord); + } + } + if (!this.match('=')) { + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + } + else { + this.reinterpretExpressionAsPattern(expr); + } + token = this.nextToken(); + var operator = token.value; + var right = this.isolateCoverGrammar(this.parseAssignmentExpression); + expr = this.finalize(this.startNode(startToken), new Node.AssignmentExpression(operator, expr, right)); + this.context.firstCoverInitializedNameError = null; + } + } + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-comma-operator + Parser.prototype.parseExpression = function () { + var startToken = this.lookahead; + var expr = this.isolateCoverGrammar(this.parseAssignmentExpression); + if (this.match(',')) { + var expressions = []; + expressions.push(expr); + while (this.lookahead.type !== 2 /* EOF */) { + if (!this.match(',')) { + break; + } + this.nextToken(); + expressions.push(this.isolateCoverGrammar(this.parseAssignmentExpression)); + } + expr = this.finalize(this.startNode(startToken), new Node.SequenceExpression(expressions)); + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-block + Parser.prototype.parseStatementListItem = function () { + var statement; + this.context.isAssignmentTarget = true; + this.context.isBindingElement = true; + if (this.lookahead.type === 4 /* Keyword */) { + switch (this.lookahead.value) { + case 'export': + if (!this.context.isModule) { + this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.IllegalExportDeclaration); + } + statement = this.parseExportDeclaration(); + break; + case 'import': + if (this.matchImportCall()) { + statement = this.parseExpressionStatement(); + } + else { + if (!this.context.isModule) { + this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.IllegalImportDeclaration); + } + statement = this.parseImportDeclaration(); + } + break; + case 'const': + statement = this.parseLexicalDeclaration({ inFor: false }); + break; + case 'function': + statement = this.parseFunctionDeclaration(); + break; + case 'class': + statement = this.parseClassDeclaration(); + break; + case 'let': + statement = this.isLexicalDeclaration() ? this.parseLexicalDeclaration({ inFor: false }) : this.parseStatement(); + break; + default: + statement = this.parseStatement(); + break; + } + } + else { + statement = this.parseStatement(); + } + return statement; + }; + Parser.prototype.parseBlock = function () { + var node = this.createNode(); + this.expect('{'); + var block = []; + while (true) { + if (this.match('}')) { + break; + } + block.push(this.parseStatementListItem()); + } + this.expect('}'); + return this.finalize(node, new Node.BlockStatement(block)); + }; + // https://tc39.github.io/ecma262/#sec-let-and-const-declarations + Parser.prototype.parseLexicalBinding = function (kind, options) { + var node = this.createNode(); + var params = []; + var id = this.parsePattern(params, kind); + if (this.context.strict && id.type === syntax_1.Syntax.Identifier) { + if (this.scanner.isRestrictedWord(id.name)) { + this.tolerateError(messages_1.Messages.StrictVarName); + } + } + var init = null; + if (kind === 'const') { + if (!this.matchKeyword('in') && !this.matchContextualKeyword('of')) { + if (this.match('=')) { + this.nextToken(); + init = this.isolateCoverGrammar(this.parseAssignmentExpression); + } + else { + this.throwError(messages_1.Messages.DeclarationMissingInitializer, 'const'); + } + } + } + else if ((!options.inFor && id.type !== syntax_1.Syntax.Identifier) || this.match('=')) { + this.expect('='); + init = this.isolateCoverGrammar(this.parseAssignmentExpression); + } + return this.finalize(node, new Node.VariableDeclarator(id, init)); + }; + Parser.prototype.parseBindingList = function (kind, options) { + var list = [this.parseLexicalBinding(kind, options)]; + while (this.match(',')) { + this.nextToken(); + list.push(this.parseLexicalBinding(kind, options)); + } + return list; + }; + Parser.prototype.isLexicalDeclaration = function () { + var state = this.scanner.saveState(); + this.scanner.scanComments(); + var next = this.scanner.lex(); + this.scanner.restoreState(state); + return (next.type === 3 /* Identifier */) || + (next.type === 7 /* Punctuator */ && next.value === '[') || + (next.type === 7 /* Punctuator */ && next.value === '{') || + (next.type === 4 /* Keyword */ && next.value === 'let') || + (next.type === 4 /* Keyword */ && next.value === 'yield'); + }; + Parser.prototype.parseLexicalDeclaration = function (options) { + var node = this.createNode(); + var kind = this.nextToken().value; + assert_1.assert(kind === 'let' || kind === 'const', 'Lexical declaration must be either let or const'); + var declarations = this.parseBindingList(kind, options); + this.consumeSemicolon(); + return this.finalize(node, new Node.VariableDeclaration(declarations, kind)); + }; + // https://tc39.github.io/ecma262/#sec-destructuring-binding-patterns + Parser.prototype.parseBindingRestElement = function (params, kind) { + var node = this.createNode(); + this.expect('...'); + var arg = this.parsePattern(params, kind); + return this.finalize(node, new Node.RestElement(arg)); + }; + Parser.prototype.parseArrayPattern = function (params, kind) { + var node = this.createNode(); + this.expect('['); + var elements = []; + while (!this.match(']')) { + if (this.match(',')) { + this.nextToken(); + elements.push(null); + } + else { + if (this.match('...')) { + elements.push(this.parseBindingRestElement(params, kind)); + break; + } + else { + elements.push(this.parsePatternWithDefault(params, kind)); + } + if (!this.match(']')) { + this.expect(','); + } + } + } + this.expect(']'); + return this.finalize(node, new Node.ArrayPattern(elements)); + }; + Parser.prototype.parsePropertyPattern = function (params, kind) { + var node = this.createNode(); + var computed = false; + var shorthand = false; + var method = false; + var key; + var value; + if (this.lookahead.type === 3 /* Identifier */) { + var keyToken = this.lookahead; + key = this.parseVariableIdentifier(); + var init = this.finalize(node, new Node.Identifier(keyToken.value)); + if (this.match('=')) { + params.push(keyToken); + shorthand = true; + this.nextToken(); + var expr = this.parseAssignmentExpression(); + value = this.finalize(this.startNode(keyToken), new Node.AssignmentPattern(init, expr)); + } + else if (!this.match(':')) { + params.push(keyToken); + shorthand = true; + value = init; + } + else { + this.expect(':'); + value = this.parsePatternWithDefault(params, kind); + } + } + else { + computed = this.match('['); + key = this.parseObjectPropertyKey(); + this.expect(':'); + value = this.parsePatternWithDefault(params, kind); + } + return this.finalize(node, new Node.Property('init', key, computed, value, method, shorthand)); + }; + Parser.prototype.parseRestProperty = function (params, kind) { + var node = this.createNode(); + this.expect('...'); + var arg = this.parsePattern(params); + if (this.match('=')) { + this.throwError(messages_1.Messages.DefaultRestProperty); + } + if (!this.match('}')) { + this.throwError(messages_1.Messages.PropertyAfterRestProperty); + } + return this.finalize(node, new Node.RestProperty(arg)); + }; + Parser.prototype.parseObjectPattern = function (params, kind) { + var node = this.createNode(); + var properties = []; + this.expect('{'); + while (!this.match('}')) { + properties.push(this.match('...') ? this.parseRestProperty(params, kind) : this.parsePropertyPattern(params, kind)); + if (!this.match('}')) { + this.expect(','); + } + } + this.expect('}'); + return this.finalize(node, new Node.ObjectPattern(properties)); + }; + Parser.prototype.parsePattern = function (params, kind) { + var pattern; + if (this.match('[')) { + pattern = this.parseArrayPattern(params, kind); + } + else if (this.match('{')) { + pattern = this.parseObjectPattern(params, kind); + } + else { + if (this.matchKeyword('let') && (kind === 'const' || kind === 'let')) { + this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.LetInLexicalBinding); + } + params.push(this.lookahead); + pattern = this.parseVariableIdentifier(kind); + } + return pattern; + }; + Parser.prototype.parsePatternWithDefault = function (params, kind) { + var startToken = this.lookahead; + var pattern = this.parsePattern(params, kind); + if (this.match('=')) { + this.nextToken(); + var previousAllowYield = this.context.allowYield; + this.context.allowYield = true; + var right = this.isolateCoverGrammar(this.parseAssignmentExpression); + this.context.allowYield = previousAllowYield; + pattern = this.finalize(this.startNode(startToken), new Node.AssignmentPattern(pattern, right)); + } + return pattern; + }; + // https://tc39.github.io/ecma262/#sec-variable-statement + Parser.prototype.parseVariableIdentifier = function (kind) { + var node = this.createNode(); + var token = this.nextToken(); + if (token.type === 4 /* Keyword */ && token.value === 'yield') { + if (this.context.strict) { + this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord); + } + else if (!this.context.allowYield) { + this.throwUnexpectedToken(token); + } + } + else if (token.type !== 3 /* Identifier */) { + if (this.context.strict && token.type === 4 /* Keyword */ && this.scanner.isStrictModeReservedWord(token.value)) { + this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord); + } + else { + if (this.context.strict || token.value !== 'let' || kind !== 'var') { + this.throwUnexpectedToken(token); + } + } + } + else if ((this.context.isModule || this.context.await) && token.type === 3 /* Identifier */ && token.value === 'await') { + this.tolerateUnexpectedToken(token); + } + return this.finalize(node, new Node.Identifier(token.value)); + }; + Parser.prototype.parseVariableDeclaration = function (options) { + var node = this.createNode(); + var params = []; + var id = this.parsePattern(params, 'var'); + if (this.context.strict && id.type === syntax_1.Syntax.Identifier) { + if (this.scanner.isRestrictedWord(id.name)) { + this.tolerateError(messages_1.Messages.StrictVarName); + } + } + var init = null; + if (this.match('=')) { + this.nextToken(); + init = this.isolateCoverGrammar(this.parseAssignmentExpression); + } + else if (id.type !== syntax_1.Syntax.Identifier && !options.inFor) { + this.expect('='); + } + return this.finalize(node, new Node.VariableDeclarator(id, init)); + }; + Parser.prototype.parseVariableDeclarationList = function (options) { + var opt = { inFor: options.inFor }; + var list = []; + list.push(this.parseVariableDeclaration(opt)); + while (this.match(',')) { + this.nextToken(); + list.push(this.parseVariableDeclaration(opt)); + } + return list; + }; + Parser.prototype.parseVariableStatement = function () { + var node = this.createNode(); + this.expectKeyword('var'); + var declarations = this.parseVariableDeclarationList({ inFor: false }); + this.consumeSemicolon(); + return this.finalize(node, new Node.VariableDeclaration(declarations, 'var')); + }; + // https://tc39.github.io/ecma262/#sec-empty-statement + Parser.prototype.parseEmptyStatement = function () { + var node = this.createNode(); + this.expect(';'); + return this.finalize(node, new Node.EmptyStatement()); + }; + // https://tc39.github.io/ecma262/#sec-expression-statement + Parser.prototype.parseExpressionStatement = function () { + var node = this.createNode(); + var expr = this.parseExpression(); + this.consumeSemicolon(); + return this.finalize(node, new Node.ExpressionStatement(expr)); + }; + // https://tc39.github.io/ecma262/#sec-if-statement + Parser.prototype.parseIfClause = function () { + if (this.context.strict && this.matchKeyword('function')) { + this.tolerateError(messages_1.Messages.StrictFunction); + } + return this.parseStatement(); + }; + Parser.prototype.parseIfStatement = function () { + var node = this.createNode(); + var consequent; + var alternate = null; + this.expectKeyword('if'); + this.expect('('); + var test = this.parseExpression(); + if (!this.match(')') && this.config.tolerant) { + this.tolerateUnexpectedToken(this.nextToken()); + consequent = this.finalize(this.createNode(), new Node.EmptyStatement()); + } + else { + this.expect(')'); + consequent = this.parseIfClause(); + if (this.matchKeyword('else')) { + this.nextToken(); + alternate = this.parseIfClause(); + } + } + return this.finalize(node, new Node.IfStatement(test, consequent, alternate)); + }; + // https://tc39.github.io/ecma262/#sec-do-while-statement + Parser.prototype.parseDoWhileStatement = function () { + var node = this.createNode(); + this.expectKeyword('do'); + var previousInIteration = this.context.inIteration; + this.context.inIteration = true; + var body = this.parseStatement(); + this.context.inIteration = previousInIteration; + this.expectKeyword('while'); + this.expect('('); + var test = this.parseExpression(); + if (!this.match(')') && this.config.tolerant) { + this.tolerateUnexpectedToken(this.nextToken()); + } + else { + this.expect(')'); + if (this.match(';')) { + this.nextToken(); + } + } + return this.finalize(node, new Node.DoWhileStatement(body, test)); + }; + // https://tc39.github.io/ecma262/#sec-while-statement + Parser.prototype.parseWhileStatement = function () { + var node = this.createNode(); + var body; + this.expectKeyword('while'); + this.expect('('); + var test = this.parseExpression(); + if (!this.match(')') && this.config.tolerant) { + this.tolerateUnexpectedToken(this.nextToken()); + body = this.finalize(this.createNode(), new Node.EmptyStatement()); + } + else { + this.expect(')'); + var previousInIteration = this.context.inIteration; + this.context.inIteration = true; + body = this.parseStatement(); + this.context.inIteration = previousInIteration; + } + return this.finalize(node, new Node.WhileStatement(test, body)); + }; + // https://tc39.github.io/ecma262/#sec-for-statement + // https://tc39.github.io/ecma262/#sec-for-in-and-for-of-statements + Parser.prototype.parseForStatement = function () { + var init = null; + var test = null; + var update = null; + var forIn = true; + var left, right; + var node = this.createNode(); + this.expectKeyword('for'); + this.expect('('); + if (this.match(';')) { + this.nextToken(); + } + else { + if (this.matchKeyword('var')) { + init = this.createNode(); + this.nextToken(); + var previousAllowIn = this.context.allowIn; + this.context.allowIn = false; + var declarations = this.parseVariableDeclarationList({ inFor: true }); + this.context.allowIn = previousAllowIn; + if (declarations.length === 1 && this.matchKeyword('in')) { + var decl = declarations[0]; + if (decl.init && (decl.id.type === syntax_1.Syntax.ArrayPattern || decl.id.type === syntax_1.Syntax.ObjectPattern || this.context.strict)) { + this.tolerateError(messages_1.Messages.ForInOfLoopInitializer, 'for-in'); + } + init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var')); + this.nextToken(); + left = init; + right = this.parseExpression(); + init = null; + } + else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword('of')) { + init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var')); + this.nextToken(); + left = init; + right = this.parseAssignmentExpression(); + init = null; + forIn = false; + } + else { + init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var')); + this.expect(';'); + } + } + else if (this.matchKeyword('const') || this.matchKeyword('let')) { + init = this.createNode(); + var kind = this.nextToken().value; + if (!this.context.strict && this.lookahead.value === 'in') { + init = this.finalize(init, new Node.Identifier(kind)); + this.nextToken(); + left = init; + right = this.parseExpression(); + init = null; + } + else { + var previousAllowIn = this.context.allowIn; + this.context.allowIn = false; + var declarations = this.parseBindingList(kind, { inFor: true }); + this.context.allowIn = previousAllowIn; + if (declarations.length === 1 && declarations[0].init === null && this.matchKeyword('in')) { + init = this.finalize(init, new Node.VariableDeclaration(declarations, kind)); + this.nextToken(); + left = init; + right = this.parseExpression(); + init = null; + } + else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword('of')) { + init = this.finalize(init, new Node.VariableDeclaration(declarations, kind)); + this.nextToken(); + left = init; + right = this.parseAssignmentExpression(); + init = null; + forIn = false; + } + else { + this.consumeSemicolon(); + init = this.finalize(init, new Node.VariableDeclaration(declarations, kind)); + } + } + } + else { + var initStartToken = this.lookahead; + var previousAllowIn = this.context.allowIn; + this.context.allowIn = false; + init = this.inheritCoverGrammar(this.parseAssignmentExpression); + this.context.allowIn = previousAllowIn; + if (this.matchKeyword('in')) { + if (!this.context.isAssignmentTarget || init.type === syntax_1.Syntax.AssignmentExpression) { + this.tolerateError(messages_1.Messages.InvalidLHSInForIn); + } + this.nextToken(); + this.reinterpretExpressionAsPattern(init); + left = init; + right = this.parseExpression(); + init = null; + } + else if (this.matchContextualKeyword('of')) { + if (!this.context.isAssignmentTarget || init.type === syntax_1.Syntax.AssignmentExpression) { + this.tolerateError(messages_1.Messages.InvalidLHSInForLoop); + } + this.nextToken(); + this.reinterpretExpressionAsPattern(init); + left = init; + right = this.parseAssignmentExpression(); + init = null; + forIn = false; + } + else { + if (this.match(',')) { + var initSeq = [init]; + while (this.match(',')) { + this.nextToken(); + initSeq.push(this.isolateCoverGrammar(this.parseAssignmentExpression)); + } + init = this.finalize(this.startNode(initStartToken), new Node.SequenceExpression(initSeq)); + } + this.expect(';'); + } + } + } + if (typeof left === 'undefined') { + if (!this.match(';')) { + test = this.parseExpression(); + } + this.expect(';'); + if (!this.match(')')) { + update = this.parseExpression(); + } + } + var body; + if (!this.match(')') && this.config.tolerant) { + this.tolerateUnexpectedToken(this.nextToken()); + body = this.finalize(this.createNode(), new Node.EmptyStatement()); + } + else { + this.expect(')'); + var previousInIteration = this.context.inIteration; + this.context.inIteration = true; + body = this.isolateCoverGrammar(this.parseStatement); + this.context.inIteration = previousInIteration; + } + return (typeof left === 'undefined') ? + this.finalize(node, new Node.ForStatement(init, test, update, body)) : + forIn ? this.finalize(node, new Node.ForInStatement(left, right, body)) : + this.finalize(node, new Node.ForOfStatement(left, right, body)); + }; + // https://tc39.github.io/ecma262/#sec-continue-statement + Parser.prototype.parseContinueStatement = function () { + var node = this.createNode(); + this.expectKeyword('continue'); + var label = null; + if (this.lookahead.type === 3 /* Identifier */ && !this.hasLineTerminator) { + var id = this.parseVariableIdentifier(); + label = id; + var key = '$' + id.name; + if (!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) { + this.throwError(messages_1.Messages.UnknownLabel, id.name); + } + } + this.consumeSemicolon(); + if (label === null && !this.context.inIteration) { + this.throwError(messages_1.Messages.IllegalContinue); + } + return this.finalize(node, new Node.ContinueStatement(label)); + }; + // https://tc39.github.io/ecma262/#sec-break-statement + Parser.prototype.parseBreakStatement = function () { + var node = this.createNode(); + this.expectKeyword('break'); + var label = null; + if (this.lookahead.type === 3 /* Identifier */ && !this.hasLineTerminator) { + var id = this.parseVariableIdentifier(); + var key = '$' + id.name; + if (!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) { + this.throwError(messages_1.Messages.UnknownLabel, id.name); + } + label = id; + } + this.consumeSemicolon(); + if (label === null && !this.context.inIteration && !this.context.inSwitch) { + this.throwError(messages_1.Messages.IllegalBreak); + } + return this.finalize(node, new Node.BreakStatement(label)); + }; + // https://tc39.github.io/ecma262/#sec-return-statement + Parser.prototype.parseReturnStatement = function () { + if (!this.context.inFunctionBody) { + this.tolerateError(messages_1.Messages.IllegalReturn); + } + var node = this.createNode(); + this.expectKeyword('return'); + var hasArgument = !this.match(';') && !this.match('}') && + !this.hasLineTerminator && this.lookahead.type !== 2 /* EOF */; + var argument = hasArgument ? this.parseExpression() : null; + this.consumeSemicolon(); + return this.finalize(node, new Node.ReturnStatement(argument)); + }; + // https://tc39.github.io/ecma262/#sec-with-statement + Parser.prototype.parseWithStatement = function () { + if (this.context.strict) { + this.tolerateError(messages_1.Messages.StrictModeWith); + } + var node = this.createNode(); + var body; + this.expectKeyword('with'); + this.expect('('); + var object = this.parseExpression(); + if (!this.match(')') && this.config.tolerant) { + this.tolerateUnexpectedToken(this.nextToken()); + body = this.finalize(this.createNode(), new Node.EmptyStatement()); + } + else { + this.expect(')'); + body = this.parseStatement(); + } + return this.finalize(node, new Node.WithStatement(object, body)); + }; + // https://tc39.github.io/ecma262/#sec-switch-statement + Parser.prototype.parseSwitchCase = function () { + var node = this.createNode(); + var test; + if (this.matchKeyword('default')) { + this.nextToken(); + test = null; + } + else { + this.expectKeyword('case'); + test = this.parseExpression(); + } + this.expect(':'); + var consequent = []; + while (true) { + if (this.match('}') || this.matchKeyword('default') || this.matchKeyword('case')) { + break; + } + consequent.push(this.parseStatementListItem()); + } + return this.finalize(node, new Node.SwitchCase(test, consequent)); + }; + Parser.prototype.parseSwitchStatement = function () { + var node = this.createNode(); + this.expectKeyword('switch'); + this.expect('('); + var discriminant = this.parseExpression(); + this.expect(')'); + var previousInSwitch = this.context.inSwitch; + this.context.inSwitch = true; + var cases = []; + var defaultFound = false; + this.expect('{'); + while (true) { + if (this.match('}')) { + break; + } + var clause = this.parseSwitchCase(); + if (clause.test === null) { + if (defaultFound) { + this.throwError(messages_1.Messages.MultipleDefaultsInSwitch); + } + defaultFound = true; + } + cases.push(clause); + } + this.expect('}'); + this.context.inSwitch = previousInSwitch; + return this.finalize(node, new Node.SwitchStatement(discriminant, cases)); + }; + // https://tc39.github.io/ecma262/#sec-labelled-statements + Parser.prototype.parseLabelledStatement = function () { + var node = this.createNode(); + var expr = this.parseExpression(); + var statement; + if ((expr.type === syntax_1.Syntax.Identifier) && this.match(':')) { + this.nextToken(); + var id = expr; + var key = '$' + id.name; + if (Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) { + this.throwError(messages_1.Messages.Redeclaration, 'Label', id.name); + } + this.context.labelSet[key] = true; + var body = void 0; + if (this.matchKeyword('class')) { + this.tolerateUnexpectedToken(this.lookahead); + body = this.parseClassDeclaration(); + } + else if (this.matchKeyword('function')) { + var token = this.lookahead; + var declaration = this.parseFunctionDeclaration(); + if (this.context.strict) { + this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunction); + } + else if (declaration.generator) { + this.tolerateUnexpectedToken(token, messages_1.Messages.GeneratorInLegacyContext); + } + body = declaration; + } + else { + body = this.parseStatement(); + } + delete this.context.labelSet[key]; + statement = new Node.LabeledStatement(id, body); + } + else { + this.consumeSemicolon(); + statement = new Node.ExpressionStatement(expr); + } + return this.finalize(node, statement); + }; + // https://tc39.github.io/ecma262/#sec-throw-statement + Parser.prototype.parseThrowStatement = function () { + var node = this.createNode(); + this.expectKeyword('throw'); + if (this.hasLineTerminator) { + this.throwError(messages_1.Messages.NewlineAfterThrow); + } + var argument = this.parseExpression(); + this.consumeSemicolon(); + return this.finalize(node, new Node.ThrowStatement(argument)); + }; + // https://tc39.github.io/ecma262/#sec-try-statement + Parser.prototype.parseCatchClause = function () { + var node = this.createNode(); + this.expectKeyword('catch'); + this.expect('('); + if (this.match(')')) { + this.throwUnexpectedToken(this.lookahead); + } + var params = []; + var param = this.parsePattern(params); + var paramMap = {}; + for (var i = 0; i < params.length; i++) { + var key = '$' + params[i].value; + if (Object.prototype.hasOwnProperty.call(paramMap, key)) { + this.tolerateError(messages_1.Messages.DuplicateBinding, params[i].value); + } + paramMap[key] = true; + } + if (this.context.strict && param.type === syntax_1.Syntax.Identifier) { + if (this.scanner.isRestrictedWord(param.name)) { + this.tolerateError(messages_1.Messages.StrictCatchVariable); + } + } + this.expect(')'); + var body = this.parseBlock(); + return this.finalize(node, new Node.CatchClause(param, body)); + }; + Parser.prototype.parseFinallyClause = function () { + this.expectKeyword('finally'); + return this.parseBlock(); + }; + Parser.prototype.parseTryStatement = function () { + var node = this.createNode(); + this.expectKeyword('try'); + var block = this.parseBlock(); + var handler = this.matchKeyword('catch') ? this.parseCatchClause() : null; + var finalizer = this.matchKeyword('finally') ? this.parseFinallyClause() : null; + if (!handler && !finalizer) { + this.throwError(messages_1.Messages.NoCatchOrFinally); + } + return this.finalize(node, new Node.TryStatement(block, handler, finalizer)); + }; + // https://tc39.github.io/ecma262/#sec-debugger-statement + Parser.prototype.parseDebuggerStatement = function () { + var node = this.createNode(); + this.expectKeyword('debugger'); + this.consumeSemicolon(); + return this.finalize(node, new Node.DebuggerStatement()); + }; + // https://tc39.github.io/ecma262/#sec-ecmascript-language-statements-and-declarations + Parser.prototype.parseStatement = function () { + var statement; + switch (this.lookahead.type) { + case 1 /* BooleanLiteral */: + case 5 /* NullLiteral */: + case 6 /* NumericLiteral */: + case 8 /* StringLiteral */: + case 10 /* Template */: + case 9 /* RegularExpression */: + statement = this.parseExpressionStatement(); + break; + case 7 /* Punctuator */: + var value = this.lookahead.value; + if (value === '{') { + statement = this.parseBlock(); + } + else if (value === '(') { + statement = this.parseExpressionStatement(); + } + else if (value === ';') { + statement = this.parseEmptyStatement(); + } + else { + statement = this.parseExpressionStatement(); + } + break; + case 3 /* Identifier */: + statement = this.matchAsyncFunction() ? this.parseFunctionDeclaration() : this.parseLabelledStatement(); + break; + case 4 /* Keyword */: + switch (this.lookahead.value) { + case 'break': + statement = this.parseBreakStatement(); + break; + case 'continue': + statement = this.parseContinueStatement(); + break; + case 'debugger': + statement = this.parseDebuggerStatement(); + break; + case 'do': + statement = this.parseDoWhileStatement(); + break; + case 'for': + statement = this.parseForStatement(); + break; + case 'function': + statement = this.parseFunctionDeclaration(); + break; + case 'if': + statement = this.parseIfStatement(); + break; + case 'return': + statement = this.parseReturnStatement(); + break; + case 'switch': + statement = this.parseSwitchStatement(); + break; + case 'throw': + statement = this.parseThrowStatement(); + break; + case 'try': + statement = this.parseTryStatement(); + break; + case 'var': + statement = this.parseVariableStatement(); + break; + case 'while': + statement = this.parseWhileStatement(); + break; + case 'with': + statement = this.parseWithStatement(); + break; + default: + statement = this.parseExpressionStatement(); + break; + } + break; + default: + statement = this.throwUnexpectedToken(this.lookahead); + } + return statement; + }; + // https://tc39.github.io/ecma262/#sec-function-definitions + Parser.prototype.parseFunctionSourceElements = function () { + var node = this.createNode(); + this.expect('{'); + var body = this.parseDirectivePrologues(); + var previousLabelSet = this.context.labelSet; + var previousInIteration = this.context.inIteration; + var previousInSwitch = this.context.inSwitch; + var previousInFunctionBody = this.context.inFunctionBody; + this.context.labelSet = {}; + this.context.inIteration = false; + this.context.inSwitch = false; + this.context.inFunctionBody = true; + while (this.lookahead.type !== 2 /* EOF */) { + if (this.match('}')) { + break; + } + body.push(this.parseStatementListItem()); + } + this.expect('}'); + this.context.labelSet = previousLabelSet; + this.context.inIteration = previousInIteration; + this.context.inSwitch = previousInSwitch; + this.context.inFunctionBody = previousInFunctionBody; + return this.finalize(node, new Node.BlockStatement(body)); + }; + Parser.prototype.validateParam = function (options, param, name) { + var key = '$' + name; + if (this.context.strict) { + if (this.scanner.isRestrictedWord(name)) { + options.stricted = param; + options.message = messages_1.Messages.StrictParamName; + } + if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) { + options.stricted = param; + options.message = messages_1.Messages.StrictParamDupe; + } + } + else if (!options.firstRestricted) { + if (this.scanner.isRestrictedWord(name)) { + options.firstRestricted = param; + options.message = messages_1.Messages.StrictParamName; + } + else if (this.scanner.isStrictModeReservedWord(name)) { + options.firstRestricted = param; + options.message = messages_1.Messages.StrictReservedWord; + } + else if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) { + options.stricted = param; + options.message = messages_1.Messages.StrictParamDupe; + } + } + /* istanbul ignore next */ + if (typeof Object.defineProperty === 'function') { + Object.defineProperty(options.paramSet, key, { value: true, enumerable: true, writable: true, configurable: true }); + } + else { + options.paramSet[key] = true; + } + }; + Parser.prototype.parseRestElement = function (params) { + var node = this.createNode(); + this.expect('...'); + var arg = this.parsePattern(params); + if (this.match('=')) { + this.throwError(messages_1.Messages.DefaultRestParameter); + } + if (!this.match(')')) { + this.throwError(messages_1.Messages.ParameterAfterRestParameter); + } + return this.finalize(node, new Node.RestElement(arg)); + }; + Parser.prototype.parseFormalParameter = function (options) { + var params = []; + var param = this.match('...') ? this.parseRestElement(params) : this.parsePatternWithDefault(params); + for (var i = 0; i < params.length; i++) { + this.validateParam(options, params[i], params[i].value); + } + options.simple = options.simple && (param instanceof Node.Identifier); + options.params.push(param); + }; + Parser.prototype.parseFormalParameters = function (firstRestricted) { + var options; + options = { + simple: true, + params: [], + firstRestricted: firstRestricted + }; + this.expect('('); + if (!this.match(')')) { + options.paramSet = {}; + while (this.lookahead.type !== 2 /* EOF */) { + this.parseFormalParameter(options); + if (this.match(')')) { + break; + } + this.expect(','); + if (this.match(')')) { + break; + } + } + } + this.expect(')'); + return { + simple: options.simple, + params: options.params, + stricted: options.stricted, + firstRestricted: options.firstRestricted, + message: options.message + }; + }; + Parser.prototype.matchAsyncFunction = function () { + var match = this.matchContextualKeyword('async'); + if (match) { + var state = this.scanner.saveState(); + this.scanner.scanComments(); + var next = this.scanner.lex(); + this.scanner.restoreState(state); + match = (state.lineNumber === next.lineNumber) && (next.type === 4 /* Keyword */) && (next.value === 'function'); + } + return match; + }; + Parser.prototype.parseFunctionDeclaration = function (identifierIsOptional) { + var node = this.createNode(); + var isAsync = this.matchContextualKeyword('async'); + if (isAsync) { + this.nextToken(); + } + this.expectKeyword('function'); + var isGenerator = isAsync ? false : this.match('*'); + if (isGenerator) { + this.nextToken(); + } + var message; + var id = null; + var firstRestricted = null; + if (!identifierIsOptional || !this.match('(')) { + var token = this.lookahead; + id = this.parseVariableIdentifier(); + if (this.context.strict) { + if (this.scanner.isRestrictedWord(token.value)) { + this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunctionName); + } + } + else { + if (this.scanner.isRestrictedWord(token.value)) { + firstRestricted = token; + message = messages_1.Messages.StrictFunctionName; + } + else if (this.scanner.isStrictModeReservedWord(token.value)) { + firstRestricted = token; + message = messages_1.Messages.StrictReservedWord; + } + } + } + var previousAllowAwait = this.context.await; + var previousAllowYield = this.context.allowYield; + this.context.await = isAsync; + this.context.allowYield = !isGenerator; + var formalParameters = this.parseFormalParameters(firstRestricted); + var params = formalParameters.params; + var stricted = formalParameters.stricted; + firstRestricted = formalParameters.firstRestricted; + if (formalParameters.message) { + message = formalParameters.message; + } + var previousStrict = this.context.strict; + var previousAllowStrictDirective = this.context.allowStrictDirective; + this.context.allowStrictDirective = formalParameters.simple; + var body = this.parseFunctionSourceElements(); + if (this.context.strict && firstRestricted) { + this.throwUnexpectedToken(firstRestricted, message); + } + if (this.context.strict && stricted) { + this.tolerateUnexpectedToken(stricted, message); + } + this.context.strict = previousStrict; + this.context.allowStrictDirective = previousAllowStrictDirective; + this.context.await = previousAllowAwait; + this.context.allowYield = previousAllowYield; + return isAsync ? this.finalize(node, new Node.AsyncFunctionDeclaration(id, params, body)) : + this.finalize(node, new Node.FunctionDeclaration(id, params, body, isGenerator)); + }; + Parser.prototype.parseFunctionExpression = function () { + var node = this.createNode(); + var isAsync = this.matchContextualKeyword('async'); + if (isAsync) { + this.nextToken(); + } + this.expectKeyword('function'); + var isGenerator = isAsync ? false : this.match('*'); + if (isGenerator) { + this.nextToken(); + } + var message; + var id = null; + var firstRestricted; + var previousAllowAwait = this.context.await; + var previousAllowYield = this.context.allowYield; + this.context.await = isAsync; + this.context.allowYield = !isGenerator; + if (!this.match('(')) { + var token = this.lookahead; + id = (!this.context.strict && !isGenerator && this.matchKeyword('yield')) ? this.parseIdentifierName() : this.parseVariableIdentifier(); + if (this.context.strict) { + if (this.scanner.isRestrictedWord(token.value)) { + this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunctionName); + } + } + else { + if (this.scanner.isRestrictedWord(token.value)) { + firstRestricted = token; + message = messages_1.Messages.StrictFunctionName; + } + else if (this.scanner.isStrictModeReservedWord(token.value)) { + firstRestricted = token; + message = messages_1.Messages.StrictReservedWord; + } + } + } + var formalParameters = this.parseFormalParameters(firstRestricted); + var params = formalParameters.params; + var stricted = formalParameters.stricted; + firstRestricted = formalParameters.firstRestricted; + if (formalParameters.message) { + message = formalParameters.message; + } + var previousStrict = this.context.strict; + var previousAllowStrictDirective = this.context.allowStrictDirective; + this.context.allowStrictDirective = formalParameters.simple; + var body = this.parseFunctionSourceElements(); + if (this.context.strict && firstRestricted) { + this.throwUnexpectedToken(firstRestricted, message); + } + if (this.context.strict && stricted) { + this.tolerateUnexpectedToken(stricted, message); + } + this.context.strict = previousStrict; + this.context.allowStrictDirective = previousAllowStrictDirective; + this.context.await = previousAllowAwait; + this.context.allowYield = previousAllowYield; + return isAsync ? this.finalize(node, new Node.AsyncFunctionExpression(id, params, body)) : + this.finalize(node, new Node.FunctionExpression(id, params, body, isGenerator)); + }; + // https://tc39.github.io/ecma262/#sec-directive-prologues-and-the-use-strict-directive + Parser.prototype.parseDirective = function () { + var token = this.lookahead; + var node = this.createNode(); + var expr = this.parseExpression(); + var directive = (expr.type === syntax_1.Syntax.Literal) ? this.getTokenRaw(token).slice(1, -1) : null; + this.consumeSemicolon(); + return this.finalize(node, directive ? new Node.Directive(expr, directive) : new Node.ExpressionStatement(expr)); + }; + Parser.prototype.parseDirectivePrologues = function () { + var firstRestricted = null; + var body = []; + while (true) { + var token = this.lookahead; + if (token.type !== 8 /* StringLiteral */) { + break; + } + var statement = this.parseDirective(); + body.push(statement); + var directive = statement.directive; + if (typeof directive !== 'string') { + break; + } + if (directive === 'use strict') { + this.context.strict = true; + if (firstRestricted) { + this.tolerateUnexpectedToken(firstRestricted, messages_1.Messages.StrictOctalLiteral); + } + if (!this.context.allowStrictDirective) { + this.tolerateUnexpectedToken(token, messages_1.Messages.IllegalLanguageModeDirective); + } + } + else { + if (!firstRestricted && token.octal) { + firstRestricted = token; + } + } + } + return body; + }; + // https://tc39.github.io/ecma262/#sec-method-definitions + Parser.prototype.qualifiedPropertyName = function (token) { + switch (token.type) { + case 3 /* Identifier */: + case 8 /* StringLiteral */: + case 1 /* BooleanLiteral */: + case 5 /* NullLiteral */: + case 6 /* NumericLiteral */: + case 4 /* Keyword */: + return true; + case 7 /* Punctuator */: + return token.value === '['; + default: + break; + } + return false; + }; + Parser.prototype.parseGetterMethod = function () { + var node = this.createNode(); + var isGenerator = false; + var previousAllowYield = this.context.allowYield; + this.context.allowYield = false; + var formalParameters = this.parseFormalParameters(); + if (formalParameters.params.length > 0) { + this.tolerateError(messages_1.Messages.BadGetterArity); + } + var method = this.parsePropertyMethod(formalParameters); + this.context.allowYield = previousAllowYield; + return this.finalize(node, new Node.FunctionExpression(null, formalParameters.params, method, isGenerator)); + }; + Parser.prototype.parseSetterMethod = function () { + var node = this.createNode(); + var isGenerator = false; + var previousAllowYield = this.context.allowYield; + this.context.allowYield = false; + var formalParameters = this.parseFormalParameters(); + if (formalParameters.params.length !== 1) { + this.tolerateError(messages_1.Messages.BadSetterArity); + } + else if (formalParameters.params[0] instanceof Node.RestElement) { + this.tolerateError(messages_1.Messages.BadSetterRestParameter); + } + var method = this.parsePropertyMethod(formalParameters); + this.context.allowYield = previousAllowYield; + return this.finalize(node, new Node.FunctionExpression(null, formalParameters.params, method, isGenerator)); + }; + Parser.prototype.parseGeneratorMethod = function () { + var node = this.createNode(); + var isGenerator = true; + var previousAllowYield = this.context.allowYield; + this.context.allowYield = true; + var params = this.parseFormalParameters(); + this.context.allowYield = false; + var method = this.parsePropertyMethod(params); + this.context.allowYield = previousAllowYield; + return this.finalize(node, new Node.FunctionExpression(null, params.params, method, isGenerator)); + }; + // https://tc39.github.io/ecma262/#sec-generator-function-definitions + Parser.prototype.isStartOfExpression = function () { + var start = true; + var value = this.lookahead.value; + switch (this.lookahead.type) { + case 7 /* Punctuator */: + start = (value === '[') || (value === '(') || (value === '{') || + (value === '+') || (value === '-') || + (value === '!') || (value === '~') || + (value === '++') || (value === '--') || + (value === '/') || (value === '/='); // regular expression literal + break; + case 4 /* Keyword */: + start = (value === 'class') || (value === 'delete') || + (value === 'function') || (value === 'let') || (value === 'new') || + (value === 'super') || (value === 'this') || (value === 'typeof') || + (value === 'void') || (value === 'yield'); + break; + default: + break; + } + return start; + }; + Parser.prototype.parseYieldExpression = function () { + var node = this.createNode(); + this.expectKeyword('yield'); + var argument = null; + var delegate = false; + if (!this.hasLineTerminator) { + var previousAllowYield = this.context.allowYield; + this.context.allowYield = false; + delegate = this.match('*'); + if (delegate) { + this.nextToken(); + argument = this.parseAssignmentExpression(); + } + else if (this.isStartOfExpression()) { + argument = this.parseAssignmentExpression(); + } + this.context.allowYield = previousAllowYield; + } + return this.finalize(node, new Node.YieldExpression(argument, delegate)); + }; + // https://tc39.github.io/ecma262/#sec-class-definitions + Parser.prototype.parseClassElement = function (hasConstructor) { + var token = this.lookahead; + var node = this.createNode(); + var kind = ''; + var key = null; + var value = null; + var computed = false; + var method = false; + var isStatic = false; + var isAsync = false; + if (this.match('*')) { + this.nextToken(); + } + else { + computed = this.match('['); + key = this.parseObjectPropertyKey(); + var id = key; + if (id.name === 'static' && (this.qualifiedPropertyName(this.lookahead) || this.match('*'))) { + token = this.lookahead; + isStatic = true; + computed = this.match('['); + if (this.match('*')) { + this.nextToken(); + } + else { + key = this.parseObjectPropertyKey(); + } + } + if ((token.type === 3 /* Identifier */) && !this.hasLineTerminator && (token.value === 'async')) { + var punctuator = this.lookahead.value; + if (punctuator !== ':' && punctuator !== '(' && punctuator !== '*') { + isAsync = true; + token = this.lookahead; + key = this.parseObjectPropertyKey(); + if (token.type === 3 /* Identifier */) { + if (token.value === 'get' || token.value === 'set') { + this.tolerateUnexpectedToken(token); + } + else if (token.value === 'constructor') { + this.tolerateUnexpectedToken(token, messages_1.Messages.ConstructorIsAsync); + } + } + } + } + } + var lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead); + if (token.type === 3 /* Identifier */) { + if (token.value === 'get' && lookaheadPropertyKey) { + kind = 'get'; + computed = this.match('['); + key = this.parseObjectPropertyKey(); + this.context.allowYield = false; + value = this.parseGetterMethod(); + } + else if (token.value === 'set' && lookaheadPropertyKey) { + kind = 'set'; + computed = this.match('['); + key = this.parseObjectPropertyKey(); + value = this.parseSetterMethod(); + } + } + else if (token.type === 7 /* Punctuator */ && token.value === '*' && lookaheadPropertyKey) { + kind = 'init'; + computed = this.match('['); + key = this.parseObjectPropertyKey(); + value = this.parseGeneratorMethod(); + method = true; + } + if (!kind && key && this.match('(')) { + kind = 'init'; + value = isAsync ? this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction(); + method = true; + } + if (!kind) { + this.throwUnexpectedToken(this.lookahead); + } + if (kind === 'init') { + kind = 'method'; + } + if (!computed) { + if (isStatic && this.isPropertyKey(key, 'prototype')) { + this.throwUnexpectedToken(token, messages_1.Messages.StaticPrototype); + } + if (!isStatic && this.isPropertyKey(key, 'constructor')) { + if (kind !== 'method' || !method || (value && value.generator)) { + this.throwUnexpectedToken(token, messages_1.Messages.ConstructorSpecialMethod); + } + if (hasConstructor.value) { + this.throwUnexpectedToken(token, messages_1.Messages.DuplicateConstructor); + } + else { + hasConstructor.value = true; + } + kind = 'constructor'; + } + } + return this.finalize(node, new Node.MethodDefinition(key, computed, value, kind, isStatic)); + }; + Parser.prototype.parseClassElementList = function () { + var body = []; + var hasConstructor = { value: false }; + this.expect('{'); + while (!this.match('}')) { + if (this.match(';')) { + this.nextToken(); + } + else { + body.push(this.parseClassElement(hasConstructor)); + } + } + this.expect('}'); + return body; + }; + Parser.prototype.parseClassBody = function () { + var node = this.createNode(); + var elementList = this.parseClassElementList(); + return this.finalize(node, new Node.ClassBody(elementList)); + }; + Parser.prototype.parseClassDeclaration = function (identifierIsOptional) { + var node = this.createNode(); + var previousStrict = this.context.strict; + this.context.strict = true; + this.expectKeyword('class'); + var id = (identifierIsOptional && (this.lookahead.type !== 3 /* Identifier */)) ? null : this.parseVariableIdentifier(); + var superClass = null; + if (this.matchKeyword('extends')) { + this.nextToken(); + superClass = this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall); + } + var classBody = this.parseClassBody(); + this.context.strict = previousStrict; + return this.finalize(node, new Node.ClassDeclaration(id, superClass, classBody)); + }; + Parser.prototype.parseClassExpression = function () { + var node = this.createNode(); + var previousStrict = this.context.strict; + this.context.strict = true; + this.expectKeyword('class'); + var id = (this.lookahead.type === 3 /* Identifier */) ? this.parseVariableIdentifier() : null; + var superClass = null; + if (this.matchKeyword('extends')) { + this.nextToken(); + superClass = this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall); + } + var classBody = this.parseClassBody(); + this.context.strict = previousStrict; + return this.finalize(node, new Node.ClassExpression(id, superClass, classBody)); + }; + // https://tc39.github.io/ecma262/#sec-scripts + // https://tc39.github.io/ecma262/#sec-modules + Parser.prototype.parseModule = function () { + this.context.strict = true; + this.context.isModule = true; + var node = this.createNode(); + var body = this.parseDirectivePrologues(); + while (this.lookahead.type !== 2 /* EOF */) { + body.push(this.parseStatementListItem()); + } + return this.finalize(node, new Node.Module(body)); + }; + Parser.prototype.parseScript = function () { + var node = this.createNode(); + var body = this.parseDirectivePrologues(); + while (this.lookahead.type !== 2 /* EOF */) { + body.push(this.parseStatementListItem()); + } + return this.finalize(node, new Node.Script(body)); + }; + // https://tc39.github.io/ecma262/#sec-imports + Parser.prototype.parseModuleSpecifier = function () { + var node = this.createNode(); + if (this.lookahead.type !== 8 /* StringLiteral */) { + this.throwError(messages_1.Messages.InvalidModuleSpecifier); + } + var token = this.nextToken(); + var raw = this.getTokenRaw(token); + return this.finalize(node, new Node.Literal(token.value, raw)); + }; + // import {} ...; + Parser.prototype.parseImportSpecifier = function () { + var node = this.createNode(); + var imported; + var local; + if (this.lookahead.type === 3 /* Identifier */) { + imported = this.parseVariableIdentifier(); + local = imported; + if (this.matchContextualKeyword('as')) { + this.nextToken(); + local = this.parseVariableIdentifier(); + } + } + else { + imported = this.parseIdentifierName(); + local = imported; + if (this.matchContextualKeyword('as')) { + this.nextToken(); + local = this.parseVariableIdentifier(); + } + else { + this.throwUnexpectedToken(this.nextToken()); + } + } + return this.finalize(node, new Node.ImportSpecifier(local, imported)); + }; + // {foo, bar as bas} + Parser.prototype.parseNamedImports = function () { + this.expect('{'); + var specifiers = []; + while (!this.match('}')) { + specifiers.push(this.parseImportSpecifier()); + if (!this.match('}')) { + this.expect(','); + } + } + this.expect('}'); + return specifiers; + }; + // import ...; + Parser.prototype.parseImportDefaultSpecifier = function () { + var node = this.createNode(); + var local = this.parseIdentifierName(); + return this.finalize(node, new Node.ImportDefaultSpecifier(local)); + }; + // import <* as foo> ...; + Parser.prototype.parseImportNamespaceSpecifier = function () { + var node = this.createNode(); + this.expect('*'); + if (!this.matchContextualKeyword('as')) { + this.throwError(messages_1.Messages.NoAsAfterImportNamespace); + } + this.nextToken(); + var local = this.parseIdentifierName(); + return this.finalize(node, new Node.ImportNamespaceSpecifier(local)); + }; + Parser.prototype.parseImportDeclaration = function () { + if (this.context.inFunctionBody) { + this.throwError(messages_1.Messages.IllegalImportDeclaration); + } + var node = this.createNode(); + this.expectKeyword('import'); + var src; + var specifiers = []; + if (this.lookahead.type === 8 /* StringLiteral */) { + // import 'foo'; + src = this.parseModuleSpecifier(); + } + else { + if (this.match('{')) { + // import {bar} + specifiers = specifiers.concat(this.parseNamedImports()); + } + else if (this.match('*')) { + // import * as foo + specifiers.push(this.parseImportNamespaceSpecifier()); + } + else if (this.isIdentifierName(this.lookahead) && !this.matchKeyword('default')) { + // import foo + specifiers.push(this.parseImportDefaultSpecifier()); + if (this.match(',')) { + this.nextToken(); + if (this.match('*')) { + // import foo, * as foo + specifiers.push(this.parseImportNamespaceSpecifier()); + } + else if (this.match('{')) { + // import foo, {bar} + specifiers = specifiers.concat(this.parseNamedImports()); + } + else { + this.throwUnexpectedToken(this.lookahead); + } + } + } + else { + this.throwUnexpectedToken(this.nextToken()); + } + if (!this.matchContextualKeyword('from')) { + var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause; + this.throwError(message, this.lookahead.value); + } + this.nextToken(); + src = this.parseModuleSpecifier(); + } + this.consumeSemicolon(); + return this.finalize(node, new Node.ImportDeclaration(specifiers, src)); + }; + // https://tc39.github.io/ecma262/#sec-exports + Parser.prototype.parseExportSpecifier = function () { + var node = this.createNode(); + var local = this.parseIdentifierName(); + var exported = local; + if (this.matchContextualKeyword('as')) { + this.nextToken(); + exported = this.parseIdentifierName(); + } + return this.finalize(node, new Node.ExportSpecifier(local, exported)); + }; + Parser.prototype.parseExportDeclaration = function () { + if (this.context.inFunctionBody) { + this.throwError(messages_1.Messages.IllegalExportDeclaration); + } + var node = this.createNode(); + this.expectKeyword('export'); + var exportDeclaration; + if (this.matchKeyword('default')) { + // export default ... + this.nextToken(); + if (this.matchKeyword('function')) { + // export default function foo () {} + // export default function () {} + var declaration = this.parseFunctionDeclaration(true); + exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration)); + } + else if (this.matchKeyword('class')) { + // export default class foo {} + var declaration = this.parseClassDeclaration(true); + exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration)); + } + else if (this.matchContextualKeyword('async')) { + // export default async function f () {} + // export default async function () {} + // export default async x => x + var declaration = this.matchAsyncFunction() ? this.parseFunctionDeclaration(true) : this.parseAssignmentExpression(); + exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration)); + } + else { + if (this.matchContextualKeyword('from')) { + this.throwError(messages_1.Messages.UnexpectedToken, this.lookahead.value); + } + // export default {}; + // export default []; + // export default (1 + 2); + var declaration = this.match('{') ? this.parseObjectInitializer() : + this.match('[') ? this.parseArrayInitializer() : this.parseAssignmentExpression(); + this.consumeSemicolon(); + exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration)); + } + } + else if (this.match('*')) { + // export * from 'foo'; + this.nextToken(); + if (!this.matchContextualKeyword('from')) { + var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause; + this.throwError(message, this.lookahead.value); + } + this.nextToken(); + var src = this.parseModuleSpecifier(); + this.consumeSemicolon(); + exportDeclaration = this.finalize(node, new Node.ExportAllDeclaration(src)); + } + else if (this.lookahead.type === 4 /* Keyword */) { + // export var f = 1; + var declaration = void 0; + switch (this.lookahead.value) { + case 'let': + case 'const': + declaration = this.parseLexicalDeclaration({ inFor: false }); + break; + case 'var': + case 'class': + case 'function': + declaration = this.parseStatementListItem(); + break; + default: + this.throwUnexpectedToken(this.lookahead); + } + exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(declaration, [], null)); + } + else if (this.matchAsyncFunction()) { + var declaration = this.parseFunctionDeclaration(); + exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(declaration, [], null)); + } + else { + var specifiers = []; + var source = null; + var isExportFromIdentifier = false; + this.expect('{'); + while (!this.match('}')) { + isExportFromIdentifier = isExportFromIdentifier || this.matchKeyword('default'); + specifiers.push(this.parseExportSpecifier()); + if (!this.match('}')) { + this.expect(','); + } + } + this.expect('}'); + if (this.matchContextualKeyword('from')) { + // export {default} from 'foo'; + // export {foo} from 'foo'; + this.nextToken(); + source = this.parseModuleSpecifier(); + this.consumeSemicolon(); + } + else if (isExportFromIdentifier) { + // export {default}; // missing fromClause + var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause; + this.throwError(message, this.lookahead.value); + } + else { + // export {foo}; + this.consumeSemicolon(); + } + exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(null, specifiers, source)); + } + return exportDeclaration; + }; + return Parser; + }()); + exports.Parser = Parser; + + +/***/ }, +/* 9 */ +/***/ function(module, exports) { + + // Ensure the condition is true, otherwise throw an error. + // This is only to have a better contract semantic, i.e. another safety net + // to catch a logic error. The condition shall be fulfilled in normal case. + // Do NOT use this to enforce a certain condition on any user input. + "use strict"; + function assert(condition, message) { + /* istanbul ignore if */ + if (!condition) { + throw new Error('ASSERT: ' + message); + } + } + exports.assert = assert; + + +/***/ }, +/* 10 */ +/***/ function(module, exports) { + + /* tslint:disable:max-classes-per-file */ + "use strict"; + var ErrorHandler = (function () { + function ErrorHandler() { + this.errors = []; + this.tolerant = false; + } + ErrorHandler.prototype.recordError = function (error) { + this.errors.push(error); + }; + ErrorHandler.prototype.tolerate = function (error) { + if (this.tolerant) { + this.recordError(error); + } + else { + throw error; + } + }; + ErrorHandler.prototype.constructError = function (msg, column) { + var error = new Error(msg); + try { + throw error; + } + catch (base) { + /* istanbul ignore else */ + if (Object.create && Object.defineProperty) { + error = Object.create(base); + Object.defineProperty(error, 'column', { value: column }); + } + } + /* istanbul ignore next */ + return error; + }; + ErrorHandler.prototype.createError = function (index, line, col, description) { + var msg = 'Line ' + line + ': ' + description; + var error = this.constructError(msg, col); + error.index = index; + error.lineNumber = line; + error.description = description; + return error; + }; + ErrorHandler.prototype.throwError = function (index, line, col, description) { + throw this.createError(index, line, col, description); + }; + ErrorHandler.prototype.tolerateError = function (index, line, col, description) { + var error = this.createError(index, line, col, description); + if (this.tolerant) { + this.recordError(error); + } + else { + throw error; + } + }; + return ErrorHandler; + }()); + exports.ErrorHandler = ErrorHandler; + + +/***/ }, +/* 11 */ +/***/ function(module, exports) { + + "use strict"; + // Error messages should be identical to V8. + exports.Messages = { + BadImportCallArity: 'Unexpected token', + BadGetterArity: 'Getter must not have any formal parameters', + BadSetterArity: 'Setter must have exactly one formal parameter', + BadSetterRestParameter: 'Setter function argument must not be a rest parameter', + ConstructorIsAsync: 'Class constructor may not be an async method', + ConstructorSpecialMethod: 'Class constructor may not be an accessor', + DeclarationMissingInitializer: 'Missing initializer in %0 declaration', + DefaultRestParameter: 'Unexpected token =', + DefaultRestProperty: 'Unexpected token =', + DuplicateBinding: 'Duplicate binding %0', + DuplicateConstructor: 'A class may only have one constructor', + DuplicateProtoProperty: 'Duplicate __proto__ fields are not allowed in object literals', + ForInOfLoopInitializer: '%0 loop variable declaration may not have an initializer', + GeneratorInLegacyContext: 'Generator declarations are not allowed in legacy contexts', + IllegalBreak: 'Illegal break statement', + IllegalContinue: 'Illegal continue statement', + IllegalExportDeclaration: 'Unexpected token', + IllegalImportDeclaration: 'Unexpected token', + IllegalLanguageModeDirective: 'Illegal \'use strict\' directive in function with non-simple parameter list', + IllegalReturn: 'Illegal return statement', + InvalidEscapedReservedWord: 'Keyword must not contain escaped characters', + InvalidHexEscapeSequence: 'Invalid hexadecimal escape sequence', + InvalidLHSInAssignment: 'Invalid left-hand side in assignment', + InvalidLHSInForIn: 'Invalid left-hand side in for-in', + InvalidLHSInForLoop: 'Invalid left-hand side in for-loop', + InvalidModuleSpecifier: 'Unexpected token', + InvalidRegExp: 'Invalid regular expression', + LetInLexicalBinding: 'let is disallowed as a lexically bound name', + MissingFromClause: 'Unexpected token', + MultipleDefaultsInSwitch: 'More than one default clause in switch statement', + NewlineAfterThrow: 'Illegal newline after throw', + NoAsAfterImportNamespace: 'Unexpected token', + NoCatchOrFinally: 'Missing catch or finally after try', + ParameterAfterRestParameter: 'Rest parameter must be last formal parameter', + PropertyAfterRestProperty: 'Unexpected token', + Redeclaration: '%0 \'%1\' has already been declared', + StaticPrototype: 'Classes may not have static property named prototype', + StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode', + StrictDelete: 'Delete of an unqualified identifier in strict mode.', + StrictFunction: 'In strict mode code, functions can only be declared at top level or inside a block', + StrictFunctionName: 'Function name may not be eval or arguments in strict mode', + StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode', + StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode', + StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode', + StrictModeWith: 'Strict mode code may not include a with statement', + StrictOctalLiteral: 'Octal literals are not allowed in strict mode.', + StrictParamDupe: 'Strict mode function may not have duplicate parameter names', + StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode', + StrictReservedWord: 'Use of future reserved word in strict mode', + StrictVarName: 'Variable name may not be eval or arguments in strict mode', + TemplateOctalLiteral: 'Octal literals are not allowed in template strings.', + UnexpectedEOS: 'Unexpected end of input', + UnexpectedIdentifier: 'Unexpected identifier', + UnexpectedNumber: 'Unexpected number', + UnexpectedReserved: 'Unexpected reserved word', + UnexpectedString: 'Unexpected string', + UnexpectedTemplate: 'Unexpected quasi %0', + UnexpectedToken: 'Unexpected token %0', + UnexpectedTokenIllegal: 'Unexpected token ILLEGAL', + UnknownLabel: 'Undefined label \'%0\'', + UnterminatedRegExp: 'Invalid regular expression: missing /' + }; + + +/***/ }, +/* 12 */ +/***/ function(module, exports, __webpack_require__) { + + "use strict"; + var assert_1 = __webpack_require__(9); + var character_1 = __webpack_require__(4); + var messages_1 = __webpack_require__(11); + function hexValue(ch) { + return '0123456789abcdef'.indexOf(ch.toLowerCase()); + } + function octalValue(ch) { + return '01234567'.indexOf(ch); + } + var Scanner = (function () { + function Scanner(code, handler) { + this.source = code; + this.errorHandler = handler; + this.trackComment = false; + this.length = code.length; + this.index = 0; + this.lineNumber = (code.length > 0) ? 1 : 0; + this.lineStart = 0; + this.curlyStack = []; + } + Scanner.prototype.saveState = function () { + return { + index: this.index, + lineNumber: this.lineNumber, + lineStart: this.lineStart + }; + }; + Scanner.prototype.restoreState = function (state) { + this.index = state.index; + this.lineNumber = state.lineNumber; + this.lineStart = state.lineStart; + }; + Scanner.prototype.eof = function () { + return this.index >= this.length; + }; + Scanner.prototype.throwUnexpectedToken = function (message) { + if (message === void 0) { message = messages_1.Messages.UnexpectedTokenIllegal; } + return this.errorHandler.throwError(this.index, this.lineNumber, this.index - this.lineStart + 1, message); + }; + Scanner.prototype.tolerateUnexpectedToken = function (message) { + if (message === void 0) { message = messages_1.Messages.UnexpectedTokenIllegal; } + this.errorHandler.tolerateError(this.index, this.lineNumber, this.index - this.lineStart + 1, message); + }; + // https://tc39.github.io/ecma262/#sec-comments + Scanner.prototype.skipSingleLineComment = function (offset) { + var comments = []; + var start, loc; + if (this.trackComment) { + comments = []; + start = this.index - offset; + loc = { + start: { + line: this.lineNumber, + column: this.index - this.lineStart - offset + }, + end: {} + }; + } + while (!this.eof()) { + var ch = this.source.charCodeAt(this.index); + ++this.index; + if (character_1.Character.isLineTerminator(ch)) { + if (this.trackComment) { + loc.end = { + line: this.lineNumber, + column: this.index - this.lineStart - 1 + }; + var entry = { + multiLine: false, + slice: [start + offset, this.index - 1], + range: [start, this.index - 1], + loc: loc + }; + comments.push(entry); + } + if (ch === 13 && this.source.charCodeAt(this.index) === 10) { + ++this.index; + } + ++this.lineNumber; + this.lineStart = this.index; + return comments; + } + } + if (this.trackComment) { + loc.end = { + line: this.lineNumber, + column: this.index - this.lineStart + }; + var entry = { + multiLine: false, + slice: [start + offset, this.index], + range: [start, this.index], + loc: loc + }; + comments.push(entry); + } + return comments; + }; + Scanner.prototype.skipMultiLineComment = function () { + var comments = []; + var start, loc; + if (this.trackComment) { + comments = []; + start = this.index - 2; + loc = { + start: { + line: this.lineNumber, + column: this.index - this.lineStart - 2 + }, + end: {} + }; + } + while (!this.eof()) { + var ch = this.source.charCodeAt(this.index); + if (character_1.Character.isLineTerminator(ch)) { + if (ch === 0x0D && this.source.charCodeAt(this.index + 1) === 0x0A) { + ++this.index; + } + ++this.lineNumber; + ++this.index; + this.lineStart = this.index; + } + else if (ch === 0x2A) { + // Block comment ends with '*/'. + if (this.source.charCodeAt(this.index + 1) === 0x2F) { + this.index += 2; + if (this.trackComment) { + loc.end = { + line: this.lineNumber, + column: this.index - this.lineStart + }; + var entry = { + multiLine: true, + slice: [start + 2, this.index - 2], + range: [start, this.index], + loc: loc + }; + comments.push(entry); + } + return comments; + } + ++this.index; + } + else { + ++this.index; + } + } + // Ran off the end of the file - the whole thing is a comment + if (this.trackComment) { + loc.end = { + line: this.lineNumber, + column: this.index - this.lineStart + }; + var entry = { + multiLine: true, + slice: [start + 2, this.index], + range: [start, this.index], + loc: loc + }; + comments.push(entry); + } + this.tolerateUnexpectedToken(); + return comments; + }; + Scanner.prototype.scanComments = function () { + var comments; + if (this.trackComment) { + comments = []; + } + var start = (this.index === 0); + while (!this.eof()) { + var ch = this.source.charCodeAt(this.index); + if (character_1.Character.isWhiteSpace(ch)) { + ++this.index; + } + else if (character_1.Character.isLineTerminator(ch)) { + ++this.index; + if (ch === 0x0D && this.source.charCodeAt(this.index) === 0x0A) { + ++this.index; + } + ++this.lineNumber; + this.lineStart = this.index; + start = true; + } + else if (ch === 0x2F) { + ch = this.source.charCodeAt(this.index + 1); + if (ch === 0x2F) { + this.index += 2; + var comment = this.skipSingleLineComment(2); + if (this.trackComment) { + comments = comments.concat(comment); + } + start = true; + } + else if (ch === 0x2A) { + this.index += 2; + var comment = this.skipMultiLineComment(); + if (this.trackComment) { + comments = comments.concat(comment); + } + } + else { + break; + } + } + else if (start && ch === 0x2D) { + // U+003E is '>' + if ((this.source.charCodeAt(this.index + 1) === 0x2D) && (this.source.charCodeAt(this.index + 2) === 0x3E)) { + // '-->' is a single-line comment + this.index += 3; + var comment = this.skipSingleLineComment(3); + if (this.trackComment) { + comments = comments.concat(comment); + } + } + else { + break; + } + } + else if (ch === 0x3C) { + if (this.source.slice(this.index + 1, this.index + 4) === '!--') { + this.index += 4; // ` + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/BackArrow.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/BackArrow.svg deleted file mode 100644 index dddaa6dcd..000000000 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/BackArrow.svg +++ /dev/null @@ -1,156 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/BackForwardArrows.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/BackForwardArrows.svg new file mode 100644 index 000000000..396ba1265 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/BackForwardArrows.svg @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/BottomUpTree.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/BottomUpTree.svg deleted file mode 100644 index e7204b6ae..000000000 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/BottomUpTree.svg +++ /dev/null @@ -1,73 +0,0 @@ - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/BreakpointActionAdd.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/BreakpointActionAdd.svg deleted file mode 100644 index e2aecaa92..000000000 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/BreakpointActionAdd.svg +++ /dev/null @@ -1,52 +0,0 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/BreakpointActionRemove.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/BreakpointActionRemove.svg deleted file mode 100644 index c8ced6079..000000000 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/BreakpointActionRemove.svg +++ /dev/null @@ -1,55 +0,0 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/BreakpointButton.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/BreakpointButton.svg index 261f12d73..5088dc3a9 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/BreakpointButton.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/BreakpointButton.svg @@ -1,159 +1,7 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/BreakpointInactiveButton.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/BreakpointInactiveButton.svg index dca083834..e24177c0a 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/BreakpointInactiveButton.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/BreakpointInactiveButton.svg @@ -1,204 +1,7 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Breakpoints.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Breakpoints.svg index 84e9dfe12..bdadae5e7 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/Breakpoints.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Breakpoints.svg @@ -1,52 +1,5 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/COPYING b/Source/WebInspectorUI/UserInterface/Images/gtk/COPYING new file mode 100644 index 000000000..7b9639ed0 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/COPYING @@ -0,0 +1,18 @@ +This work is licensed under the terms of the Creative Commons +Attribution-Share Alike 3.0 United States License with the exception +of the files: + +* GradientStop.png +* GradientStop@2x.png +* GradientStopSelected.png +* GradientStopSelected@2x.png +* SliderThumb.png +* SliderThumb@2x.png +* SliderThumbPressed.png +* SliderThumbPressed@2x.png + +Which are licensed under the terms of the GNU LGPL v2. + +To view a copy of the CC-BY-SA license, visit +http://creativecommons.org/licenses/by-sa/3.0/ or send a letter to Creative +Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA. diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/COPYING_CCBYSA3 b/Source/WebInspectorUI/UserInterface/Images/gtk/COPYING_CCBYSA3 new file mode 100644 index 000000000..baa12f6b5 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/COPYING_CCBYSA3 @@ -0,0 +1,4 @@ +This work is licensed under the Creative Commons Attribution-Share Alike 3.0 +United States License. To view a copy of this license, visit +http://creativecommons.org/licenses/by-sa/3.0/ or send a letter to Creative +Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA. diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/COPYING_LGPL2 b/Source/WebInspectorUI/UserInterface/Images/gtk/COPYING_LGPL2 new file mode 100644 index 000000000..5bc8fb2c8 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/COPYING_LGPL2 @@ -0,0 +1,481 @@ + GNU LIBRARY GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1991 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the library GPL. It is + numbered 2 because it goes with version 2 of the ordinary GPL.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Library General Public License, applies to some +specially designated Free Software Foundation software, and to any +other libraries whose authors decide to use it. You can use it for +your libraries, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if +you distribute copies of the library, or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link a program with the library, you must provide +complete object files to the recipients so that they can relink them +with the library, after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + Our method of protecting your rights has two steps: (1) copyright +the library, and (2) offer you this license which gives you legal +permission to copy, distribute and/or modify the library. + + Also, for each distributor's protection, we want to make certain +that everyone understands that there is no warranty for this free +library. If the library is modified by someone else and passed on, we +want its recipients to know that what they have is not the original +version, so that any problems introduced by others will not reflect on +the original authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that companies distributing free +software will individually obtain patent licenses, thus in effect +transforming the program into proprietary software. To prevent this, +we have made it clear that any patent must be licensed for everyone's +free use or not licensed at all. + + Most GNU software, including some libraries, is covered by the ordinary +GNU General Public License, which was designed for utility programs. This +license, the GNU Library General Public License, applies to certain +designated libraries. This license is quite different from the ordinary +one; be sure to read it in full, and don't assume that anything in it is +the same as in the ordinary license. + + The reason we have a separate public license for some libraries is that +they blur the distinction we usually make between modifying or adding to a +program and simply using it. Linking a program with a library, without +changing the library, is in some sense simply using the library, and is +analogous to running a utility program or application program. However, in +a textual and legal sense, the linked executable is a combined work, a +derivative of the original library, and the ordinary General Public License +treats it as such. + + Because of this blurred distinction, using the ordinary General +Public License for libraries did not effectively promote software +sharing, because most developers did not use the libraries. We +concluded that weaker conditions might promote sharing better. + + However, unrestricted linking of non-free programs would deprive the +users of those programs of all benefit from the free status of the +libraries themselves. This Library General Public License is intended to +permit developers of non-free programs to use free libraries, while +preserving your freedom as a user of such programs to change the free +libraries that are incorporated in them. (We have not seen how to achieve +this as regards changes in header files, but we have achieved it as regards +changes in the actual functions of the Library.) The hope is that this +will lead to faster development of free libraries. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, while the latter only +works together with the library. + + Note that it is possible for a library to be covered by the ordinary +General Public License rather than by this special one. + + GNU LIBRARY GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library which +contains a notice placed by the copyright holder or other authorized +party saying it may be distributed under the terms of this Library +General Public License (also called "this License"). Each licensee is +addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also compile or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + c) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + d) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the source code distributed need not include anything that is normally +distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Library General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Checkers.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Checkers.svg new file mode 100644 index 000000000..a4369d7af --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Checkers.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Circle.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Circle.svg new file mode 100644 index 000000000..3dac0b6db --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Circle.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/ClearBoth.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/ClearBoth.svg new file mode 100644 index 000000000..fcdf12a60 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/ClearBoth.svg @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/ClearLeft.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/ClearLeft.svg new file mode 100644 index 000000000..54c72900b --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/ClearLeft.svg @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/ClearRight.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/ClearRight.svg new file mode 100644 index 000000000..1c21c0dfc --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/ClearRight.svg @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Close.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Close.svg index 94ef884fd..b9c22f5f1 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/Close.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Close.svg @@ -1,53 +1,5 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/CloseLarge.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/CloseLarge.svg new file mode 100644 index 000000000..938535068 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/CloseLarge.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/CloseTimeline.png b/Source/WebInspectorUI/UserInterface/Images/gtk/CloseTimeline.png deleted file mode 100644 index a033c4efa..000000000 Binary files a/Source/WebInspectorUI/UserInterface/Images/gtk/CloseTimeline.png and /dev/null differ diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/CloseTimeline@2x.png b/Source/WebInspectorUI/UserInterface/Images/gtk/CloseTimeline@2x.png deleted file mode 100644 index 1c395e132..000000000 Binary files a/Source/WebInspectorUI/UserInterface/Images/gtk/CloseTimeline@2x.png and /dev/null differ diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/CloseWhite.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/CloseWhite.svg index 9376b2f64..0039c83ae 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/CloseWhite.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/CloseWhite.svg @@ -1,53 +1,5 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Colors.png b/Source/WebInspectorUI/UserInterface/Images/gtk/Colors.png deleted file mode 100644 index 8a7634561..000000000 Binary files a/Source/WebInspectorUI/UserInterface/Images/gtk/Colors.png and /dev/null differ diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Colors@2x.png b/Source/WebInspectorUI/UserInterface/Images/gtk/Colors@2x.png deleted file mode 100644 index 2c12841a0..000000000 Binary files a/Source/WebInspectorUI/UserInterface/Images/gtk/Colors@2x.png and /dev/null differ diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/ColorsLarge.png b/Source/WebInspectorUI/UserInterface/Images/gtk/ColorsLarge.png deleted file mode 100644 index 2c12841a0..000000000 Binary files a/Source/WebInspectorUI/UserInterface/Images/gtk/ColorsLarge.png and /dev/null differ diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/ColorsLarge@2x.png b/Source/WebInspectorUI/UserInterface/Images/gtk/ColorsLarge@2x.png deleted file mode 100644 index 02713789a..000000000 Binary files a/Source/WebInspectorUI/UserInterface/Images/gtk/ColorsLarge@2x.png and /dev/null differ diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Console.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Console.svg new file mode 100644 index 000000000..b17c71696 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Console.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/ContentFlow.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/ContentFlow.svg index 8009d24eb..0f16fc104 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/ContentFlow.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/ContentFlow.svg @@ -1,70 +1,8 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Crosshair.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Crosshair.svg index 7e86d6987..0212dc075 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/Crosshair.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Crosshair.svg @@ -1,66 +1,6 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/CubicBezier.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/CubicBezier.svg new file mode 100644 index 000000000..8e97dd710 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/CubicBezier.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/DOMCharacterData.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/DOMCharacterData.svg index 3cbf16c0a..63d0efda1 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/DOMCharacterData.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/DOMCharacterData.svg @@ -1,345 +1,27 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/DOMComment.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/DOMComment.svg index e42b996bb..bee5ab7b3 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/DOMComment.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/DOMComment.svg @@ -1,348 +1,27 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/DOMDocument.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/DOMDocument.svg index 1de21c2ec..c9d356ae2 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/DOMDocument.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/DOMDocument.svg @@ -1,407 +1,27 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/DOMDocumentType.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/DOMDocumentType.svg index 1de21c2ec..c9d356ae2 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/DOMDocumentType.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/DOMDocumentType.svg @@ -1,407 +1,27 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/DOMElement.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/DOMElement.svg index a29a0e8c8..fba0a631e 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/DOMElement.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/DOMElement.svg @@ -1,381 +1,27 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/DOMNode.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/DOMNode.svg index 641663b23..6dd1a7c5f 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/DOMNode.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/DOMNode.svg @@ -1,389 +1,27 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/DOMTextNode.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/DOMTextNode.svg index 18bb0aff3..d2c5d55a8 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/DOMTextNode.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/DOMTextNode.svg @@ -1,363 +1,27 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/DOMTree.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/DOMTree.svg deleted file mode 100644 index 0c69a95bf..000000000 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/DOMTree.svg +++ /dev/null @@ -1,359 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Debug.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Debug.svg new file mode 100644 index 000000000..8e70c74c8 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Debug.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Debugger.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Debugger.svg new file mode 100644 index 000000000..a9fda3602 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Debugger.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/DisclosureTriangleSmallClosed.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/DisclosureTriangleSmallClosed.svg deleted file mode 100644 index 9f2ebacef..000000000 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/DisclosureTriangleSmallClosed.svg +++ /dev/null @@ -1,53 +0,0 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/DisclosureTriangleSmallOpen.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/DisclosureTriangleSmallOpen.svg deleted file mode 100644 index 4d5984012..000000000 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/DisclosureTriangleSmallOpen.svg +++ /dev/null @@ -1,57 +0,0 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/DisclosureTriangleTinyClosed.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/DisclosureTriangleTinyClosed.svg deleted file mode 100644 index 47f917bb9..000000000 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/DisclosureTriangleTinyClosed.svg +++ /dev/null @@ -1,57 +0,0 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/DisclosureTriangleTinyOpen.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/DisclosureTriangleTinyOpen.svg deleted file mode 100644 index cad2a48b9..000000000 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/DisclosureTriangleTinyOpen.svg +++ /dev/null @@ -1,57 +0,0 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/DisclosureTriangles.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/DisclosureTriangles.svg new file mode 100644 index 000000000..73ad2cb23 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/DisclosureTriangles.svg @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/DockBottom.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/DockBottom.svg index b45d2cd70..5abd0bafd 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/DockBottom.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/DockBottom.svg @@ -1,54 +1,5 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/DockRight.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/DockRight.svg index fe6f1d22a..6ec5e98dc 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/DockRight.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/DockRight.svg @@ -1,37 +1,5 @@ - - - - - - - - - image/svg+xml - - - - - - - - + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/DownloadArrow.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/DownloadArrow.svg index 586a4e603..1a2d57518 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/DownloadArrow.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/DownloadArrow.svg @@ -1,128 +1,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Elements.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Elements.svg new file mode 100644 index 000000000..0ef940fa4 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Elements.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Error.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Error.svg index 3983e2d7b..aacbb622b 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/Error.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Error.svg @@ -1,128 +1,5 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Errors.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Errors.svg index 550a601d8..6f4551e11 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/Errors.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Errors.svg @@ -1,127 +1,5 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/ErrorsEnabled.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/ErrorsEnabled.svg index 6fe0f7d7b..753682a6a 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/ErrorsEnabled.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/ErrorsEnabled.svg @@ -1,75 +1,5 @@ - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/EventListener.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/EventListener.svg index 44e318ab3..eb9557056 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/EventListener.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/EventListener.svg @@ -1,389 +1,27 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Exception.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Exception.svg index c67e7c48b..03ddf692c 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/Exception.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Exception.svg @@ -1,349 +1,27 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Eye.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Eye.svg new file mode 100644 index 000000000..7c17103c8 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Eye.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/FilterFieldGlyph.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/FilterFieldGlyph.svg index dce24257b..d25fd4534 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/FilterFieldGlyph.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/FilterFieldGlyph.svg @@ -1,53 +1,5 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/FloatLeft.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/FloatLeft.svg new file mode 100644 index 000000000..49cb8e5b8 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/FloatLeft.svg @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/FloatRight.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/FloatRight.svg new file mode 100644 index 000000000..132f252b2 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/FloatRight.svg @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/FontStyleItalic.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/FontStyleItalic.svg new file mode 100644 index 000000000..509d52a2b --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/FontStyleItalic.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/FontStyleNormal.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/FontStyleNormal.svg new file mode 100644 index 000000000..72b556142 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/FontStyleNormal.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/ForwardArrow.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/ForwardArrow.svg deleted file mode 100644 index f2774a3e1..000000000 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/ForwardArrow.svg +++ /dev/null @@ -1,156 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Function.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Function.svg index ee93f645a..f15d7379e 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/Function.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Function.svg @@ -1,433 +1,27 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Gear.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Gear.svg new file mode 100644 index 000000000..28ae5e7a6 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Gear.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/GoToArrow.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/GoToArrow.svg index 82d662ef3..63cdc32c3 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/GoToArrow.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/GoToArrow.svg @@ -1,202 +1,42 @@ - - + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/GradientStop.png b/Source/WebInspectorUI/UserInterface/Images/gtk/GradientStop.png new file mode 100644 index 000000000..ceefc506a Binary files /dev/null and b/Source/WebInspectorUI/UserInterface/Images/gtk/GradientStop.png differ diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/GradientStop@2x.png b/Source/WebInspectorUI/UserInterface/Images/gtk/GradientStop@2x.png new file mode 100644 index 000000000..6ecfc10bd Binary files /dev/null and b/Source/WebInspectorUI/UserInterface/Images/gtk/GradientStop@2x.png differ diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/GradientStopSelected.png b/Source/WebInspectorUI/UserInterface/Images/gtk/GradientStopSelected.png new file mode 100644 index 000000000..394ab8f77 Binary files /dev/null and b/Source/WebInspectorUI/UserInterface/Images/gtk/GradientStopSelected.png differ diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/GradientStopSelected@2x.png b/Source/WebInspectorUI/UserInterface/Images/gtk/GradientStopSelected@2x.png new file mode 100644 index 000000000..561a1313b Binary files /dev/null and b/Source/WebInspectorUI/UserInterface/Images/gtk/GradientStopSelected@2x.png differ diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/HeapAllocationsInstrument.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/HeapAllocationsInstrument.svg new file mode 100644 index 000000000..108323f49 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/HeapAllocationsInstrument.svg @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/HeapSnapshotObjectGraph.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/HeapSnapshotObjectGraph.svg new file mode 100644 index 000000000..705812e8f --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/HeapSnapshotObjectGraph.svg @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/HierarchicalNavigationItemChevron.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/HierarchicalNavigationItemChevron.svg index f7098e7d7..62c88e4de 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/HierarchicalNavigationItemChevron.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/HierarchicalNavigationItemChevron.svg @@ -1,156 +1,5 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner1.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner1.svg index 2e0dde01b..61cfd8495 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner1.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner1.svg @@ -1,269 +1,26 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner10.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner10.svg index 403018601..ffe956ce8 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner10.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner10.svg @@ -1,273 +1,26 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner11.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner11.svg index 9a21123e4..30ee22f99 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner11.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner11.svg @@ -1,273 +1,26 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner12.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner12.svg index 6c8f5ab15..d5bd31ced 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner12.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner12.svg @@ -1,273 +1,26 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner2.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner2.svg index f24c95228..9c8f3ea45 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner2.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner2.svg @@ -1,293 +1,26 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner3.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner3.svg index fa16f4ce7..5bbe20241 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner3.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner3.svg @@ -1,273 +1,26 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner4.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner4.svg index 21fd85ecb..8b5de8f2d 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner4.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner4.svg @@ -1,273 +1,26 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner5.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner5.svg index 5d91be102..0f8153a5b 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner5.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner5.svg @@ -1,273 +1,26 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner6.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner6.svg index 6c2b0f768..88169597d 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner6.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner6.svg @@ -1,273 +1,26 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner7.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner7.svg index daa9db871..e37f20300 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner7.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner7.svg @@ -1,273 +1,26 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner8.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner8.svg index 09eff6b92..14a4fc35f 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner8.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner8.svg @@ -1,273 +1,26 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner9.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner9.svg index 5eb6dc312..93c1ca01d 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner9.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/IndeterminateProgressSpinner9.svg @@ -1,273 +1,26 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Info.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Info.svg new file mode 100644 index 000000000..be8464b56 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Info.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Issues.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Issues.svg index 2826092cb..d5b910516 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/Issues.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Issues.svg @@ -1,52 +1,5 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/IssuesEnabled.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/IssuesEnabled.svg index 55ad82494..efbe389a4 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/IssuesEnabled.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/IssuesEnabled.svg @@ -1,52 +1,5 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/LayerBorders.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/LayerBorders.svg index d3bed89bd..9d276a669 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/LayerBorders.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/LayerBorders.svg @@ -1,64 +1,8 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/LayoutInstrument.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/LayoutInstrument.svg new file mode 100644 index 000000000..b682478f2 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/LayoutInstrument.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/LessColumns.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/LessColumns.svg deleted file mode 100644 index ca6e2011c..000000000 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/LessColumns.svg +++ /dev/null @@ -1,53 +0,0 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Locked.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Locked.svg index 13132c39a..37e7fa21b 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/Locked.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Locked.svg @@ -1,53 +1,5 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Log.png b/Source/WebInspectorUI/UserInterface/Images/gtk/Log.png deleted file mode 100644 index 34638e075..000000000 Binary files a/Source/WebInspectorUI/UserInterface/Images/gtk/Log.png and /dev/null differ diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Log.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Log.svg new file mode 100644 index 000000000..1912d524f --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Log.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Log@2x.png b/Source/WebInspectorUI/UserInterface/Images/gtk/Log@2x.png deleted file mode 100644 index 943028d10..000000000 Binary files a/Source/WebInspectorUI/UserInterface/Images/gtk/Log@2x.png and /dev/null differ diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Logs.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Logs.svg index a1ec45187..2da2e9ed9 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/Logs.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Logs.svg @@ -1,52 +1,5 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Memory.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Memory.svg deleted file mode 100644 index 0762be059..000000000 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/Memory.svg +++ /dev/null @@ -1,204 +0,0 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/MemoryInstrument.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/MemoryInstrument.svg new file mode 100644 index 000000000..e7923dde9 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/MemoryInstrument.svg @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Minus.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Minus.svg new file mode 100644 index 000000000..9308ab561 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Minus.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/MoreColumns.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/MoreColumns.svg deleted file mode 100644 index a4cc87c1e..000000000 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/MoreColumns.svg +++ /dev/null @@ -1,53 +0,0 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Native.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Native.svg index 641663b23..6dd1a7c5f 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/Native.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Native.svg @@ -1,389 +1,27 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemAngleBrackets.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemAngleBrackets.svg deleted file mode 100644 index befcfafed..000000000 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemAngleBrackets.svg +++ /dev/null @@ -1,62 +0,0 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemBrushAndRuler.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemBrushAndRuler.svg deleted file mode 100644 index 031cbe54f..000000000 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemBrushAndRuler.svg +++ /dev/null @@ -1,229 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemBug.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemBug.svg deleted file mode 100644 index f3da8db92..000000000 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemBug.svg +++ /dev/null @@ -1,52 +0,0 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemClear.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemClear.svg new file mode 100644 index 000000000..b873ad767 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemClear.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemCodeCoverage.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemCodeCoverage.svg new file mode 100644 index 000000000..513be39af --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemCodeCoverage.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemCurleyBraces.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemCurleyBraces.svg index 6da1aa90c..b02a7b987 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemCurleyBraces.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemCurleyBraces.svg @@ -1,41 +1,6 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemFile.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemFile.svg deleted file mode 100644 index 77d90afc5..000000000 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemFile.svg +++ /dev/null @@ -1,52 +0,0 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemLayers.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemLayers.svg deleted file mode 100644 index b4cc684c9..000000000 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemLayers.svg +++ /dev/null @@ -1,57 +0,0 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemLog.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemLog.svg deleted file mode 100644 index 532ec4e8f..000000000 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemLog.svg +++ /dev/null @@ -1,63 +0,0 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemMagnifyingGlass.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemMagnifyingGlass.svg deleted file mode 100644 index 543dde5a5..000000000 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemMagnifyingGlass.svg +++ /dev/null @@ -1,57 +0,0 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemStopwatch.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemStopwatch.svg deleted file mode 100644 index 129769ba6..000000000 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemStopwatch.svg +++ /dev/null @@ -1,56 +0,0 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemStorage.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemStorage.svg deleted file mode 100644 index 78085bc67..000000000 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemStorage.svg +++ /dev/null @@ -1,52 +0,0 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemTrash.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemTrash.svg index 932c24bc0..b873ad767 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemTrash.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemTrash.svg @@ -1,52 +1,5 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemTypes.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemTypes.svg new file mode 100644 index 000000000..cb040e7b2 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemTypes.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemVariable.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemVariable.svg deleted file mode 100644 index 009a7a786..000000000 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/NavigationItemVariable.svg +++ /dev/null @@ -1,57 +0,0 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Network.png b/Source/WebInspectorUI/UserInterface/Images/gtk/Network.png deleted file mode 100644 index 67f505384..000000000 Binary files a/Source/WebInspectorUI/UserInterface/Images/gtk/Network.png and /dev/null differ diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Network.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Network.svg new file mode 100644 index 000000000..0d65fe36a --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Network.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Network@2x.png b/Source/WebInspectorUI/UserInterface/Images/gtk/Network@2x.png deleted file mode 100644 index 074fa05eb..000000000 Binary files a/Source/WebInspectorUI/UserInterface/Images/gtk/Network@2x.png and /dev/null differ diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/NetworkInstrument.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/NetworkInstrument.svg new file mode 100644 index 000000000..fb240fea3 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/NetworkInstrument.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/NetworkLarge.png b/Source/WebInspectorUI/UserInterface/Images/gtk/NetworkLarge.png deleted file mode 100644 index 074fa05eb..000000000 Binary files a/Source/WebInspectorUI/UserInterface/Images/gtk/NetworkLarge.png and /dev/null differ diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/NetworkLarge@2x.png b/Source/WebInspectorUI/UserInterface/Images/gtk/NetworkLarge@2x.png deleted file mode 100644 index 8d0787e12..000000000 Binary files a/Source/WebInspectorUI/UserInterface/Images/gtk/NetworkLarge@2x.png and /dev/null differ diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/NewTab.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/NewTab.svg new file mode 100644 index 000000000..80a68a79e --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/NewTab.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/NewTabPlus.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/NewTabPlus.svg new file mode 100644 index 000000000..41f57a7a4 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/NewTabPlus.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/PaintFlashing.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/PaintFlashing.svg new file mode 100644 index 000000000..f90a86c03 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/PaintFlashing.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Pause.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Pause.svg index a732811df..401887b9d 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/Pause.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Pause.svg @@ -1,56 +1,6 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/PausedBreakpoint.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/PausedBreakpoint.svg new file mode 100644 index 000000000..be4735c7d --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/PausedBreakpoint.svg @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Pencil.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Pencil.svg new file mode 100644 index 000000000..cc0245bdc --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Pencil.svg @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Percent.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Percent.svg deleted file mode 100644 index 5fce566a5..000000000 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/Percent.svg +++ /dev/null @@ -1,55 +0,0 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Plus.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Plus.svg deleted file mode 100644 index 782534a2a..000000000 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/Plus.svg +++ /dev/null @@ -1,59 +0,0 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - + - - diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Plus13.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Plus13.svg new file mode 100644 index 000000000..198fc8b79 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Plus13.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Plus15.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Plus15.svg new file mode 100644 index 000000000..43b364c5e --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Plus15.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Printer.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Printer.svg new file mode 100644 index 000000000..d31a0f33d --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Printer.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Profile.png b/Source/WebInspectorUI/UserInterface/Images/gtk/Profile.png deleted file mode 100644 index 66f73d810..000000000 Binary files a/Source/WebInspectorUI/UserInterface/Images/gtk/Profile.png and /dev/null differ diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Profile@2x.png b/Source/WebInspectorUI/UserInterface/Images/gtk/Profile@2x.png deleted file mode 100644 index 2dc3fb5f8..000000000 Binary files a/Source/WebInspectorUI/UserInterface/Images/gtk/Profile@2x.png and /dev/null differ diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Program.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Program.svg new file mode 100644 index 000000000..0ab55b4c2 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Program.svg @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/PseudoElement.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/PseudoElement.svg index 868b73bb5..be4735c7d 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/PseudoElement.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/PseudoElement.svg @@ -1,445 +1,27 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Record.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Record.svg new file mode 100644 index 000000000..62feced70 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Record.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Recording.png b/Source/WebInspectorUI/UserInterface/Images/gtk/Recording.png deleted file mode 100644 index 1d2877de8..000000000 Binary files a/Source/WebInspectorUI/UserInterface/Images/gtk/Recording.png and /dev/null differ diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Recording@2x.png b/Source/WebInspectorUI/UserInterface/Images/gtk/Recording@2x.png deleted file mode 100644 index 888248c4d..000000000 Binary files a/Source/WebInspectorUI/UserInterface/Images/gtk/Recording@2x.png and /dev/null differ diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/RecordingHovered.png b/Source/WebInspectorUI/UserInterface/Images/gtk/RecordingHovered.png deleted file mode 100644 index 7d4bfe8c5..000000000 Binary files a/Source/WebInspectorUI/UserInterface/Images/gtk/RecordingHovered.png and /dev/null differ diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/RecordingHovered@2x.png b/Source/WebInspectorUI/UserInterface/Images/gtk/RecordingHovered@2x.png deleted file mode 100644 index c782cba2f..000000000 Binary files a/Source/WebInspectorUI/UserInterface/Images/gtk/RecordingHovered@2x.png and /dev/null differ diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/RecordingStopped.png b/Source/WebInspectorUI/UserInterface/Images/gtk/RecordingStopped.png deleted file mode 100644 index c6a9733f0..000000000 Binary files a/Source/WebInspectorUI/UserInterface/Images/gtk/RecordingStopped.png and /dev/null differ diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/RecordingStopped@2x.png b/Source/WebInspectorUI/UserInterface/Images/gtk/RecordingStopped@2x.png deleted file mode 100644 index d2c060bf5..000000000 Binary files a/Source/WebInspectorUI/UserInterface/Images/gtk/RecordingStopped@2x.png and /dev/null differ diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Reflection.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Reflection.svg index 5caeacb8c..5082d6966 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/Reflection.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Reflection.svg @@ -1,422 +1,27 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Reload.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Reload.svg deleted file mode 100644 index d64f2bc9e..000000000 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/Reload.svg +++ /dev/null @@ -1,52 +0,0 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/ReloadFull.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/ReloadFull.svg new file mode 100644 index 000000000..f8b8ea87e --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/ReloadFull.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/ReloadToolbar.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/ReloadToolbar.svg new file mode 100644 index 000000000..0c234e14e --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/ReloadToolbar.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/RenderingFramesInstrument.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/RenderingFramesInstrument.svg new file mode 100644 index 000000000..f7ab1a20f --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/RenderingFramesInstrument.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/ReplayPauseButton.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/ReplayPauseButton.svg new file mode 100644 index 000000000..f23198d44 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/ReplayPauseButton.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/ReplayPlayButton.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/ReplayPlayButton.svg new file mode 100644 index 000000000..76720c450 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/ReplayPlayButton.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/ReplayRecordingButton.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/ReplayRecordingButton.svg new file mode 100644 index 000000000..de5371b4c --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/ReplayRecordingButton.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Request.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Request.svg index d3bbf3df0..7cc1d5651 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/Request.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Request.svg @@ -1,634 +1,27 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Resources.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Resources.svg index 8705f5b7b..32f69d75a 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/Resources.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Resources.svg @@ -1,52 +1,5 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Response.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Response.svg index 1d238ac1f..060b3b365 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/Response.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Response.svg @@ -1,435 +1,27 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/ResultLine.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/ResultLine.svg index 4899e65f3..81965cf37 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/ResultLine.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/ResultLine.svg @@ -1,587 +1,32 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Resume.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Resume.svg index 0a7eb797d..82361848c 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/Resume.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Resume.svg @@ -1,56 +1,6 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Script.png b/Source/WebInspectorUI/UserInterface/Images/gtk/Script.png deleted file mode 100644 index ed4174c07..000000000 Binary files a/Source/WebInspectorUI/UserInterface/Images/gtk/Script.png and /dev/null differ diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Script@2x.png b/Source/WebInspectorUI/UserInterface/Images/gtk/Script@2x.png deleted file mode 100644 index c3145d351..000000000 Binary files a/Source/WebInspectorUI/UserInterface/Images/gtk/Script@2x.png and /dev/null differ diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/ScriptLarge.png b/Source/WebInspectorUI/UserInterface/Images/gtk/ScriptLarge.png deleted file mode 100644 index c3145d351..000000000 Binary files a/Source/WebInspectorUI/UserInterface/Images/gtk/ScriptLarge.png and /dev/null differ diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/ScriptLarge@2x.png b/Source/WebInspectorUI/UserInterface/Images/gtk/ScriptLarge@2x.png deleted file mode 100644 index 5fd604d9a..000000000 Binary files a/Source/WebInspectorUI/UserInterface/Images/gtk/ScriptLarge@2x.png and /dev/null differ diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/ScriptsInstrument.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/ScriptsInstrument.svg new file mode 100644 index 000000000..5efed36d4 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/ScriptsInstrument.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/SearchResults.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/SearchResults.svg new file mode 100644 index 000000000..c567fdfcc --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/SearchResults.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/ShadowDOM.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/ShadowDOM.svg index d89199939..9a950f3d4 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/ShadowDOM.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/ShadowDOM.svg @@ -1,79 +1,8 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/SortIndicatorArrows.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/SortIndicatorArrows.svg new file mode 100644 index 000000000..a2853d1d6 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/SortIndicatorArrows.svg @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/SortIndicatorDownArrow.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/SortIndicatorDownArrow.svg deleted file mode 100644 index 5c5f97f07..000000000 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/SortIndicatorDownArrow.svg +++ /dev/null @@ -1,216 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/SortIndicatorUpArrow.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/SortIndicatorUpArrow.svg deleted file mode 100644 index 20aa669dc..000000000 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/SortIndicatorUpArrow.svg +++ /dev/null @@ -1,216 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/SourceCode.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/SourceCode.svg deleted file mode 100644 index f4f8a9b7f..000000000 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/SourceCode.svg +++ /dev/null @@ -1,636 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/SplitToggleDown.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/SplitToggleDown.svg deleted file mode 100644 index 382dad1b3..000000000 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/SplitToggleDown.svg +++ /dev/null @@ -1,56 +0,0 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/SplitToggleUp.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/SplitToggleUp.svg index 3cb3366ac..c45f0e872 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/SplitToggleUp.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/SplitToggleUp.svg @@ -1,56 +1,6 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/StepInto.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/StepInto.svg index 461e476ba..f528e16a3 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/StepInto.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/StepInto.svg @@ -1,62 +1,6 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/StepOut.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/StepOut.svg index f19c3f28b..fecfdef5b 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/StepOut.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/StepOut.svg @@ -1,62 +1,6 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/StepOver.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/StepOver.svg index 922752710..c19e030fc 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/StepOver.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/StepOver.svg @@ -1,59 +1,6 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Stop.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Stop.svg new file mode 100644 index 000000000..209800684 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Stop.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Stopwatch.png b/Source/WebInspectorUI/UserInterface/Images/gtk/Stopwatch.png deleted file mode 100644 index a9903e0c2..000000000 Binary files a/Source/WebInspectorUI/UserInterface/Images/gtk/Stopwatch.png and /dev/null differ diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Stopwatch.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Stopwatch.svg new file mode 100644 index 000000000..04ef7833e --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Stopwatch.svg @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Stopwatch@2x.png b/Source/WebInspectorUI/UserInterface/Images/gtk/Stopwatch@2x.png deleted file mode 100644 index d487d0d05..000000000 Binary files a/Source/WebInspectorUI/UserInterface/Images/gtk/Stopwatch@2x.png and /dev/null differ diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Storage.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Storage.svg new file mode 100644 index 000000000..778f0b7ff --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Storage.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/StyleRule.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/StyleRule.svg new file mode 100644 index 000000000..0e8fb90d9 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/StyleRule.svg @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/StyleRuleAuthor.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/StyleRuleAuthor.svg deleted file mode 100644 index aa61c0654..000000000 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/StyleRuleAuthor.svg +++ /dev/null @@ -1,404 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/StyleRuleInherited.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/StyleRuleInherited.svg deleted file mode 100644 index 03b446d12..000000000 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/StyleRuleInherited.svg +++ /dev/null @@ -1,641 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/StyleRuleInheritedElement.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/StyleRuleInheritedElement.svg index da13373ed..11e7c570a 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/StyleRuleInheritedElement.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/StyleRuleInheritedElement.svg @@ -1,632 +1,27 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/StyleRuleInspector.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/StyleRuleInspector.svg deleted file mode 100644 index ff3a5fd4b..000000000 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/StyleRuleInspector.svg +++ /dev/null @@ -1,481 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/StyleRulePseudoElement.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/StyleRulePseudoElement.svg new file mode 100644 index 000000000..b5319a7fd --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/StyleRulePseudoElement.svg @@ -0,0 +1,103 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/StyleRuleUser.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/StyleRuleUser.svg deleted file mode 100644 index 9f742f1ff..000000000 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/StyleRuleUser.svg +++ /dev/null @@ -1,657 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/StyleRuleUserAgent.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/StyleRuleUserAgent.svg deleted file mode 100644 index fad3b345b..000000000 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/StyleRuleUserAgent.svg +++ /dev/null @@ -1,517 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/TailDeletedFunction.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/TailDeletedFunction.svg new file mode 100644 index 000000000..be363b6db --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/TailDeletedFunction.svg @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/TextAlignCenter.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/TextAlignCenter.svg new file mode 100644 index 000000000..b65a33e5e --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/TextAlignCenter.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/TextAlignJustify.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/TextAlignJustify.svg new file mode 100644 index 000000000..9eeb16667 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/TextAlignJustify.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/TextAlignLeft.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/TextAlignLeft.svg new file mode 100644 index 000000000..58a269d64 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/TextAlignLeft.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/TextAlignRight.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/TextAlignRight.svg new file mode 100644 index 000000000..0db480ccd --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/TextAlignRight.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/TextDecorationLineThrough.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/TextDecorationLineThrough.svg new file mode 100644 index 000000000..fbb71d886 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/TextDecorationLineThrough.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/TextDecorationOverline.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/TextDecorationOverline.svg new file mode 100644 index 000000000..015aff71f --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/TextDecorationOverline.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/TextDecorationUnderline.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/TextDecorationUnderline.svg new file mode 100644 index 000000000..b896dd253 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/TextDecorationUnderline.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/TextTransformCapitalize.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/TextTransformCapitalize.svg new file mode 100644 index 000000000..7403b75f1 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/TextTransformCapitalize.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/TextTransformLowercase.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/TextTransformLowercase.svg new file mode 100644 index 000000000..78134de58 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/TextTransformLowercase.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/TextTransformUppercase.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/TextTransformUppercase.svg new file mode 100644 index 000000000..5f1759849 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/TextTransformUppercase.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Thread.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Thread.svg new file mode 100644 index 000000000..f6964146b --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Thread.svg @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Time.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Time.svg index 998069ddd..a436707e3 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/Time.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Time.svg @@ -1,56 +1,6 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Timeline.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Timeline.svg new file mode 100644 index 000000000..5487919e3 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Timeline.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordAPI.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordAPI.svg new file mode 100644 index 000000000..9bd66cbb6 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordAPI.svg @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordAnimation.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordAnimation.svg index ad4a9dc32..62eaa3077 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordAnimation.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordAnimation.svg @@ -1,472 +1,27 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - A - A - A + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordComposite.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordComposite.svg new file mode 100644 index 000000000..bee5ab7b3 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordComposite.svg @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordConsoleProfile.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordConsoleProfile.svg new file mode 100644 index 000000000..7f3f85e7e --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordConsoleProfile.svg @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordEvent.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordEvent.svg index e0f8ff489..fba0a631e 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordEvent.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordEvent.svg @@ -1,400 +1,27 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordLayout.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordLayout.svg index dcaeffb61..8c8329472 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordLayout.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordLayout.svg @@ -1,552 +1,27 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - L - L - L + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordPaint.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordPaint.svg index 868b73bb5..36917c3cd 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordPaint.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordPaint.svg @@ -1,445 +1,27 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordProbeSampled.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordProbeSampled.svg new file mode 100644 index 000000000..7f3f85e7e --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordProbeSampled.svg @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordRenderingFrame.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordRenderingFrame.svg new file mode 100644 index 000000000..8e781cd50 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordRenderingFrame.svg @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordScriptEvaluated.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordScriptEvaluated.svg index d8cc51e8e..0ab55b4c2 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordScriptEvaluated.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordScriptEvaluated.svg @@ -1,430 +1,27 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - S - S - S + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordStyle.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordStyle.svg index dc31c39bd..d392e34d8 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordStyle.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordStyle.svg @@ -1,595 +1,27 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - S - S - S + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordTimer.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordTimer.svg index 123c9fe84..54cdcbfbf 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordTimer.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/TimelineRecordTimer.svg @@ -1,447 +1,27 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - T - T - T + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/ToggleLeftSidebar.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/ToggleLeftSidebar.svg new file mode 100644 index 000000000..82d7371d5 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/ToggleLeftSidebar.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/ToggleRightSidebar.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/ToggleRightSidebar.svg new file mode 100644 index 000000000..005ae77b1 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/ToggleRightSidebar.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/TypeBoolean.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/TypeBoolean.svg new file mode 100644 index 000000000..2a1288dfd --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/TypeBoolean.svg @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/TypeNull.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/TypeNull.svg new file mode 100644 index 000000000..f78976b0f --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/TypeNull.svg @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/TypeNumber.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/TypeNumber.svg new file mode 100644 index 000000000..5ecf98b91 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/TypeNumber.svg @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/TypeObject.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/TypeObject.svg new file mode 100644 index 000000000..073c49711 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/TypeObject.svg @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/TypeRegex.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/TypeRegex.svg new file mode 100644 index 000000000..3d20f67a7 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/TypeRegex.svg @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/TypeString.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/TypeString.svg new file mode 100644 index 000000000..d392e34d8 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/TypeString.svg @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/TypeSymbol.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/TypeSymbol.svg new file mode 100644 index 000000000..e129bc829 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/TypeSymbol.svg @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/TypeUndefined.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/TypeUndefined.svg new file mode 100644 index 000000000..a5f21f3e6 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/TypeUndefined.svg @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Undock.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Undock.svg index 572720376..3803b81ef 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/Undock.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Undock.svg @@ -1,53 +1,5 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/UpDownArrows.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/UpDownArrows.svg index 9b5a099f4..01139140c 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/UpDownArrows.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/UpDownArrows.svg @@ -1,371 +1,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/UserInputPrompt.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/UserInputPrompt.svg index 31205637e..c0130cec4 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/UserInputPrompt.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/UserInputPrompt.svg @@ -1,53 +1,5 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/UserInputPromptPrevious.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/UserInputPromptPrevious.svg index ea47741ee..114302de7 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/UserInputPromptPrevious.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/UserInputPromptPrevious.svg @@ -1,53 +1,5 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/UserInputResult.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/UserInputResult.svg index 36fdd3802..543650618 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/UserInputResult.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/UserInputResult.svg @@ -1,58 +1,6 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/VisualStyleNone.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/VisualStyleNone.svg new file mode 100644 index 000000000..b47fbe802 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/VisualStyleNone.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/VisualStylePropertyLinked.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/VisualStylePropertyLinked.svg new file mode 100644 index 000000000..37129039c --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/VisualStylePropertyLinked.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/VisualStylePropertyUnlinked.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/VisualStylePropertyUnlinked.svg new file mode 100644 index 000000000..6767e5e18 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/VisualStylePropertyUnlinked.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Warning.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Warning.svg index 20a5e14ac..d19d2b721 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/Warning.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Warning.svg @@ -1,54 +1,5 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - + + + + diff --git a/Source/WebInspectorUI/UserInterface/Images/gtk/Weight.svg b/Source/WebInspectorUI/UserInterface/Images/gtk/Weight.svg index 158f7682d..5230ac480 100644 --- a/Source/WebInspectorUI/UserInterface/Images/gtk/Weight.svg +++ b/Source/WebInspectorUI/UserInterface/Images/gtk/Weight.svg @@ -1,60 +1,5 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - + + + + diff --git a/Source/WebInspectorUI/UserInterface/IndeterminateProgressSpinner.css b/Source/WebInspectorUI/UserInterface/IndeterminateProgressSpinner.css deleted file mode 100644 index 8d449cbb2..000000000 --- a/Source/WebInspectorUI/UserInterface/IndeterminateProgressSpinner.css +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -/* These keyframes try to reproduce the 12 discrete steps seen in a standard system progress indicator. */ -@-webkit-keyframes discrete-spinner { - 0% { - background-image: url(Images/IndeterminateProgressSpinner1.svg); - } - - 8.333% { - background-image: url(Images/IndeterminateProgressSpinner2.svg); - } - - 16.666% { - background-image: url(Images/IndeterminateProgressSpinner3.svg); - } - - 25.000% { - background-image: url(Images/IndeterminateProgressSpinner4.svg); - } - - 33.333% { - background-image: url(Images/IndeterminateProgressSpinner5.svg); - } - - 41.666% { - background-image: url(Images/IndeterminateProgressSpinner6.svg); - } - - 50.000% { - background-image: url(Images/IndeterminateProgressSpinner7.svg); - } - - 58.333% { - background-image: url(Images/IndeterminateProgressSpinner8.svg); - } - - 66.666% { - background-image: url(Images/IndeterminateProgressSpinner9.svg); - } - - 75.000% { - background-image: url(Images/IndeterminateProgressSpinner10.svg); - } - - 83.333% { - background-image: url(Images/IndeterminateProgressSpinner11.svg); - } - - 91.666% { - background-image: url(Images/IndeterminateProgressSpinner12.svg); - } - - 100% { - background-image: url(Images/IndeterminateProgressSpinner1.svg); - } -} - -.indeterminate-progress-spinner { - background-image: url(Images/IndeterminateProgressSpinner1.svg); - background-repeat: no-repeat; - background-size: 100% 100%; - - width: 16px; - height: 16px; - - -webkit-animation-name: discrete-spinner; - -webkit-animation-duration: 1s; - -webkit-animation-iteration-count: infinite; - -webkit-animation-timing-function: step-start; -} diff --git a/Source/WebInspectorUI/UserInterface/IndeterminateProgressSpinner.js b/Source/WebInspectorUI/UserInterface/IndeterminateProgressSpinner.js deleted file mode 100644 index 00bcaf887..000000000 --- a/Source/WebInspectorUI/UserInterface/IndeterminateProgressSpinner.js +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.IndeterminateProgressSpinner = function() -{ - WebInspector.Object.call(this); - - this._element = document.createElement("div"); - this._element.className = WebInspector.IndeterminateProgressSpinner.StyleClassName; -} - -WebInspector.IndeterminateProgressSpinner.StyleClassName = "indeterminate-progress-spinner"; - -WebInspector.IndeterminateProgressSpinner.prototype = { - constructor: WebInspector.IndeterminateProgressSpinner, - - // Public - - get element() - { - return this._element; - } -} - -WebInspector.IndeterminateProgressSpinner.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/InspectorBackend.js b/Source/WebInspectorUI/UserInterface/InspectorBackend.js deleted file mode 100644 index fc39d589e..000000000 --- a/Source/WebInspectorUI/UserInterface/InspectorBackend.js +++ /dev/null @@ -1,294 +0,0 @@ -/* - * Copyright (C) 2011 Google Inc. All rights reserved. - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/** - * @constructor - */ -function InspectorBackendClass() -{ - this._lastCallbackId = 1; - this._pendingResponsesCount = 0; - this._callbacks = {}; - this._domainDispatchers = {}; - this._eventArgs = {}; - this._replyArgs = {}; - - this.dumpInspectorTimeStats = false; - this.dumpInspectorProtocolMessages = false; - this._initialized = false; -} - -InspectorBackendClass.prototype = { - _wrap: function(callback, method) - { - var callbackId = this._lastCallbackId++; - if (!callback) - callback = function() {}; - - this._callbacks[callbackId] = callback; - callback.methodName = method; - if (this.dumpInspectorTimeStats) - callback.sendRequestTime = Date.now(); - - return callbackId; - }, - - _getAgent: function(domain) - { - var agentName = domain + "Agent"; - if (!window[agentName]) - window[agentName] = {}; - return window[agentName]; - }, - - registerCommand: function(method, signature, replyArgs) - { - var domainAndMethod = method.split("."); - var agent = this._getAgent(domainAndMethod[0]); - - agent[domainAndMethod[1]] = this._sendMessageToBackend.bind(this, method, signature); - agent[domainAndMethod[1]]["invoke"] = this._invoke.bind(this, method, signature); - agent[domainAndMethod[1]]["supports"] = this._supports.bind(this, method, signature); - this._replyArgs[method] = replyArgs; - - this._initialized = true; - }, - - registerEnum: function(type, values) - { - var domainAndMethod = type.split("."); - var agent = this._getAgent(domainAndMethod[0]); - - agent[domainAndMethod[1]] = values; - - this._initialized = true; - }, - - registerEvent: function(eventName, params) - { - this._eventArgs[eventName] = params; - - this._initialized = true; - }, - - _invoke: function(method, signature, args, callback) - { - this._wrapCallbackAndSendMessageObject(method, args, callback); - }, - - _supports: function(method, signature, paramName) - { - for (var i = 0; i < signature.length; ++i) { - if (signature[i]["name"] === paramName) - return true; - } - - return false; - }, - - _sendMessageToBackend: function(method, signature, vararg) - { - var args = Array.prototype.slice.call(arguments, 2); - var callback = typeof args.lastValue === "function" ? args.pop() : null; - - var params = {}; - var hasParams = false; - for (var i = 0; i < signature.length; ++i) { - var param = signature[i]; - var paramName = param["name"]; - var typeName = param["type"]; - var optionalFlag = param["optional"]; - - if (!args.length && !optionalFlag) { - console.error("Protocol Error: Invalid number of arguments for method '" + method + "' call. It must have the following arguments '" + JSON.stringify(signature) + "'."); - return; - } - - var value = args.shift(); - if (optionalFlag && typeof value === "undefined") { - continue; - } - - if (typeof value !== typeName) { - console.error("Protocol Error: Invalid type of argument '" + paramName + "' for method '" + method + "' call. It must be '" + typeName + "' but it is '" + typeof value + "'."); - return; - } - - params[paramName] = value; - hasParams = true; - } - - if (args.length === 1 && !callback) { - if (typeof args[0] !== "undefined") { - console.error("Protocol Error: Optional callback argument for method '" + method + "' call must be a function but its type is '" + typeof args[0] + "'."); - return; - } - } - - this._wrapCallbackAndSendMessageObject(method, hasParams ? params : null, callback); - }, - - _wrapCallbackAndSendMessageObject: function(method, params, callback) - { - var messageObject = {}; - messageObject.method = method; - if (params) - messageObject.params = params; - messageObject.id = this._wrap(callback, method); - - if (this.dumpInspectorProtocolMessages) - console.log("frontend: " + JSON.stringify(messageObject)); - - ++this._pendingResponsesCount; - this.sendMessageObjectToBackend(messageObject); - }, - - sendMessageObjectToBackend: function(messageObject) - { - var message = JSON.stringify(messageObject); - InspectorFrontendHost.sendMessageToBackend(message); - }, - - registerDomainDispatcher: function(domain, dispatcher) - { - this._domainDispatchers[domain] = dispatcher; - }, - - dispatch: function(message) - { - if (this.dumpInspectorProtocolMessages) - console.log("backend: " + ((typeof message === "string") ? message : JSON.stringify(message))); - - var messageObject = (typeof message === "string") ? JSON.parse(message) : message; - - if ("id" in messageObject) { // just a response for some request - if (messageObject.error) { - if (messageObject.error.code !== -32000) - this.reportProtocolError(messageObject); - } - - var callback = this._callbacks[messageObject.id]; - if (callback) { - var argumentsArray = []; - if (messageObject.result) { - if (callback.expectsResultObject) { - // The callback expects results as an object with properties, this is useful - // for backwards compatibility with renamed or different parameters. - argumentsArray.push(messageObject.result); - } else { - var paramNames = this._replyArgs[callback.methodName]; - if (paramNames) { - for (var i = 0; i < paramNames.length; ++i) - argumentsArray.push(messageObject.result[paramNames[i]]); - } - } - } - - var processingStartTime; - if (this.dumpInspectorTimeStats && callback.methodName) - processingStartTime = Date.now(); - - argumentsArray.unshift(messageObject.error ? messageObject.error.message : null); - callback.apply(null, argumentsArray); - --this._pendingResponsesCount; - delete this._callbacks[messageObject.id]; - - if (this.dumpInspectorTimeStats && callback.methodName) - console.log("time-stats: " + callback.methodName + " = " + (processingStartTime - callback.sendRequestTime) + " + " + (Date.now() - processingStartTime)); - } - - if (this._scripts && !this._pendingResponsesCount) - this.runAfterPendingDispatches(); - - return; - } else { - var method = messageObject.method.split("."); - var domainName = method[0]; - var functionName = method[1]; - if (!(domainName in this._domainDispatchers)) { - console.error("Protocol Error: the message is for non-existing domain '" + domainName + "'"); - return; - } - var dispatcher = this._domainDispatchers[domainName]; - if (!(functionName in dispatcher)) { - console.error("Protocol Error: Attempted to dispatch an unimplemented method '" + messageObject.method + "'"); - return; - } - - if (!this._eventArgs[messageObject.method]) { - console.error("Protocol Error: Attempted to dispatch an unspecified method '" + messageObject.method + "'"); - return; - } - - var params = []; - if (messageObject.params) { - var paramNames = this._eventArgs[messageObject.method]; - for (var i = 0; i < paramNames.length; ++i) - params.push(messageObject.params[paramNames[i]]); - } - - var processingStartTime; - if (this.dumpInspectorTimeStats) - processingStartTime = Date.now(); - - dispatcher[functionName].apply(dispatcher, params); - - if (this.dumpInspectorTimeStats) - console.log("time-stats: " + messageObject.method + " = " + (Date.now() - processingStartTime)); - } - }, - - reportProtocolError: function(messageObject) - { - console.error("Request with id = " + messageObject.id + " failed. " + JSON.stringify(messageObject.error)); - }, - - /** - * @param {string=} script - */ - runAfterPendingDispatches: function(script) - { - if (!this._scripts) - this._scripts = []; - - if (script) - this._scripts.push(script); - - if (!this._pendingResponsesCount) { - var scripts = this._scripts; - this._scripts = []; - for (var id = 0; id < scripts.length; ++id) - scripts[id].call(this); - } - } -} - -InspectorBackend = new InspectorBackendClass(); diff --git a/Source/WebInspectorUI/UserInterface/InspectorFrontendAPI.js b/Source/WebInspectorUI/UserInterface/InspectorFrontendAPI.js deleted file mode 100644 index 7d4c967a6..000000000 --- a/Source/WebInspectorUI/UserInterface/InspectorFrontendAPI.js +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -InspectorFrontendAPI = { - _loaded: false, - - _pendingCommands: [], - - savedURL: function(url) - { - // FIXME: Not implemented. - }, - - appendedToURL: function(url) - { - // FIXME: Not implemented. - }, - - isDebuggingEnabled: function() - { - // FIXME: Not implemented. - return false; - }, - - setDebuggingEnabled: function(enabled) - { - // FIXME: Not implemented. - }, - - isTimelineProfilingEnabled: function() - { - return WebInspector.timelineManager.recordingEnabled; - }, - - setTimelineProfilingEnabled: function(enabled) - { - if (enabled) { - WebInspector.navigationSidebar.selectedSidebarPanel = WebInspector.timelineSidebarPanel; - WebInspector.timelineManager.startRecording(); - } else { - WebInspector.timelineManager.stopRecording(); - } - }, - - isProfilingJavaScript: function() - { - return WebInspector.profileManager.isProfilingJavaScript(); - }, - - startProfilingJavaScript: function() - { - WebInspector.profileManager.startProfilingJavaScript(); - }, - - stopProfilingJavaScript: function() - { - WebInspector.timelineSidebarPanel.show(); - WebInspector.profileManager.stopProfilingJavaScript(); - }, - - setDockSide: function(side) - { - WebInspector.updateDockedState(side); - }, - - showConsole: function() - { - WebInspector.showConsoleView(); - - WebInspector.quickConsole.prompt.focus(); - - // If the page is still loading, focus the quick console again after tabindex autofocus. - if (document.readyState !== "complete") - document.addEventListener("readystatechange", this); - }, - - handleEvent: function(event) - { - console.assert(event.type === "readystatechange"); - - if (document.readyState === "complete") { - WebInspector.quickConsole.prompt.focus(); - document.removeEventListener("readystatechange", this); - } - }, - - showResources: function() - { - WebInspector.ignoreLastContentCookie = true; - WebInspector.navigationSidebar.selectedSidebarPanel = WebInspector.resourceSidebarPanel; - WebInspector.navigationSidebar.collapsed = false; - }, - - showMainResourceForFrame: function(frameIdentifier) - { - WebInspector.ignoreLastContentCookie = true; - WebInspector.navigationSidebar.selectedSidebarPanel = WebInspector.resourceSidebarPanel; - WebInspector.resourceSidebarPanel.showSourceCodeForFrame(frameIdentifier, true); - }, - - setDockingUnavailable: function(unavailable) - { - // Not used. - }, - - contextMenuItemSelected: function(id) - { - WebInspector.contextMenuItemSelected(id); - }, - - contextMenuCleared: function() - { - WebInspector.contextMenuCleared(); - }, - - dispatchMessageAsync: function(messageObject) - { - WebInspector.dispatchMessageFromBackend(messageObject); - }, - - dispatchMessage: function(messageObject) - { - InspectorBackend.dispatch(messageObject); - }, - - dispatch: function(signature) - { - if (!InspectorFrontendAPI._loaded) { - InspectorFrontendAPI._pendingCommands.push(signature); - return null; - } - - var methodName = signature.shift(); - return InspectorFrontendAPI[methodName].apply(InspectorFrontendAPI, signature); - }, - - loadCompleted: function() - { - InspectorFrontendAPI._loaded = true; - - for (var i = 0; i < InspectorFrontendAPI._pendingCommands.length; ++i) - InspectorFrontendAPI.dispatch(InspectorFrontendAPI._pendingCommands[i]); - - InspectorFrontendAPI._pendingCommands = []; - } -}; diff --git a/Source/WebInspectorUI/UserInterface/InspectorFrontendHostStub.js b/Source/WebInspectorUI/UserInterface/InspectorFrontendHostStub.js deleted file mode 100644 index 485de7ee1..000000000 --- a/Source/WebInspectorUI/UserInterface/InspectorFrontendHostStub.js +++ /dev/null @@ -1,174 +0,0 @@ -/* - * Copyright (C) 2009 Google Inc. All rights reserved. - * Copyright (C) 2013 Seokju Kwon (seokju.kwon@gmail.com) - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -if (!window.InspectorFrontendHost) { - WebInspector.InspectorFrontendHostStub = function() - { - } - - WebInspector.InspectorFrontendHostStub.prototype = { - // Public - - initializeWebSocket: function(url) - { - var socket = new WebSocket(url); - socket.addEventListener("open", socketReady.bind(this)); - - function socketReady() - { - this._socket = socket; - - this._socket.addEventListener("message", function(message) { InspectorBackend.dispatch(message.data); }); - this._socket.addEventListener("error", function(error) { console.error(error); }); - - this._sendPendingMessagesToBackendIfNeeded(); - } - }, - - bringToFront: function() - { - this._windowVisible = true; - }, - - closeWindow: function() - { - this._windowVisible = false; - }, - - requestSetDockSide: function(side) - { - InspectorFrontendAPI.setDockSide(side); - }, - - setAttachedWindowHeight: function(height) - { - }, - - setAttachedWindowWidth: function(width) - { - }, - - setToolbarHeight: function(width) - { - }, - - moveWindowBy: function(x, y) - { - }, - - loaded: function() - { - }, - - localizedStringsURL: function() - { - return undefined; - }, - - debuggableType: function() - { - return "web"; - }, - - inspectedURLChanged: function(title) - { - document.title = title; - }, - - copyText: function(text) - { - this._textToCopy = text; - if (!document.execCommand("copy")) - console.error("Clipboard access is denied"); - }, - - openInNewTab: function(url) - { - window.open(url, "_blank"); - }, - - save: function(url, content, base64Encoded, forceSaveAs) - { - }, - - sendMessageToBackend: function(message) - { - if (!this._socket) { - if (!this._pendingMessages) - this._pendingMessages = []; - this._pendingMessages.push(message); - return; - } - - this._sendPendingMessagesToBackendIfNeeded(); - - this._socket.send(message); - }, - - loadResourceSynchronously: function(url) - { - var xhr = new XMLHttpRequest(); - xhr.open("GET", url, false); - xhr.send(null); - - if (xhr.status === 200) - return xhr.responseText; - return null; - }, - - platform: function() - { - return (navigator.platform.match(/mac|win|linux/i) || ["other"])[0].toLowerCase(); - }, - - beep: function() - { - }, - - // Private - - _sendPendingMessagesToBackendIfNeeded: function() - { - if (!this._pendingMessages) - return; - - for (var i = 0; i < this._pendingMessages.length; ++i) - this._socket.send(this._pendingMessages[i]); - - delete this._pendingMessages; - } - } - - InspectorFrontendHost = new WebInspector.InspectorFrontendHostStub(); - - WebInspector.dontLocalizeUserInterface = true; -} diff --git a/Source/WebInspectorUI/UserInterface/InspectorJSBackendCommands.js b/Source/WebInspectorUI/UserInterface/InspectorJSBackendCommands.js deleted file mode 100644 index 51ca8a0f2..000000000 --- a/Source/WebInspectorUI/UserInterface/InspectorJSBackendCommands.js +++ /dev/null @@ -1,64 +0,0 @@ -// File is generated by JavaScriptCore/inspector/scripts/CodeGeneratorInspector.py - -// Copyright (c) 2013 Apple Inc. All Rights Reserved. -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - - -// Debugger. -InspectorBackend.registerDebuggerDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Debugger"); -InspectorBackend.registerEnum("Debugger.BreakpointActionType", {Log: "log", Evaluate: "evaluate", Sound: "sound", Probe: "probe"}); -InspectorBackend.registerEnum("Debugger.ScopeType", {Global: "global", Local: "local", With: "with", Closure: "closure", Catch: "catch"}); -InspectorBackend.registerEvent("Debugger.globalObjectCleared", []); -InspectorBackend.registerEvent("Debugger.scriptParsed", ["scriptId", "url", "startLine", "startColumn", "endLine", "endColumn", "isContentScript", "sourceMapURL", "hasSourceURL"]); -InspectorBackend.registerEvent("Debugger.scriptFailedToParse", ["url", "scriptSource", "startLine", "errorLine", "errorMessage"]); -InspectorBackend.registerEvent("Debugger.breakpointResolved", ["breakpointId", "location"]); -InspectorBackend.registerEvent("Debugger.paused", ["callFrames", "reason", "data"]); -InspectorBackend.registerEvent("Debugger.resumed", []); -InspectorBackend.registerEvent("Debugger.didSampleProbe", ["sample"]); -InspectorBackend.registerCommand("Debugger.enable", [], []); -InspectorBackend.registerCommand("Debugger.disable", [], []); -InspectorBackend.registerCommand("Debugger.setBreakpointsActive", [{"name": "active", "type": "boolean", "optional": 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": "options", "type": "object", "optional": true}], ["breakpointId", "locations"]); -InspectorBackend.registerCommand("Debugger.setBreakpoint", [{"name": "location", "type": "object", "optional": false}, {"name": "options", "type": "object", "optional": true}], ["breakpointId", "actualLocation"]); -InspectorBackend.registerCommand("Debugger.removeBreakpoint", [{"name": "breakpointId", "type": "string", "optional": false}], []); -InspectorBackend.registerCommand("Debugger.continueToLocation", [{"name": "location", "type": "object", "optional": false}], []); -InspectorBackend.registerCommand("Debugger.stepOver", [], []); -InspectorBackend.registerCommand("Debugger.stepInto", [], []); -InspectorBackend.registerCommand("Debugger.stepOut", [], []); -InspectorBackend.registerCommand("Debugger.pause", [], []); -InspectorBackend.registerCommand("Debugger.resume", [], []); -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"]); -InspectorBackend.registerCommand("Debugger.getScriptSource", [{"name": "scriptId", "type": "string", "optional": false}], ["scriptSource"]); -InspectorBackend.registerCommand("Debugger.getFunctionDetails", [{"name": "functionId", "type": "string", "optional": false}], ["details"]); -InspectorBackend.registerCommand("Debugger.setPauseOnExceptions", [{"name": "state", "type": "string", "optional": 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"]); -InspectorBackend.registerCommand("Debugger.setOverlayMessage", [{"name": "message", "type": "string", "optional": true}], []); - -// Inspector. -InspectorBackend.registerInspectorDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Inspector"); -InspectorBackend.registerEvent("Inspector.evaluateForTestInFrontend", ["testCallId", "script"]); -InspectorBackend.registerEvent("Inspector.inspect", ["object", "hints"]); -InspectorBackend.registerEvent("Inspector.detached", ["reason"]); -InspectorBackend.registerEvent("Inspector.targetCrashed", []); -InspectorBackend.registerCommand("Inspector.enable", [], []); -InspectorBackend.registerCommand("Inspector.disable", [], []); - -// Runtime. -InspectorBackend.registerRuntimeDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Runtime"); -InspectorBackend.registerEnum("Runtime.RemoteObjectType", {Object: "object", Function: "function", Undefined: "undefined", String: "string", Number: "number", Boolean: "boolean"}); -InspectorBackend.registerEnum("Runtime.RemoteObjectSubtype", {Array: "array", Null: "null", Node: "node", Regexp: "regexp", Date: "date"}); -InspectorBackend.registerEnum("Runtime.PropertyPreviewType", {Object: "object", Function: "function", Undefined: "undefined", String: "string", Number: "number", Boolean: "boolean"}); -InspectorBackend.registerEnum("Runtime.PropertyPreviewSubtype", {Array: "array", Null: "null", Node: "node", Regexp: "regexp", Date: "date"}); -InspectorBackend.registerEnum("Runtime.SyntaxErrorType", {None: "none", Irrecoverable: "irrecoverable", UnterminatedLiteral: "unterminated-literal", Recoverable: "recoverable"}); -InspectorBackend.registerEvent("Runtime.executionContextCreated", ["context"]); -InspectorBackend.registerCommand("Runtime.parse", [{"name": "source", "type": "string", "optional": false}], ["result", "message", "range"]); -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"]); -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"]); -InspectorBackend.registerCommand("Runtime.getProperties", [{"name": "objectId", "type": "string", "optional": false}, {"name": "ownProperties", "type": "boolean", "optional": true}], ["result", "internalProperties"]); -InspectorBackend.registerCommand("Runtime.releaseObject", [{"name": "objectId", "type": "string", "optional": false}], []); -InspectorBackend.registerCommand("Runtime.releaseObjectGroup", [{"name": "objectGroup", "type": "string", "optional": false}], []); -InspectorBackend.registerCommand("Runtime.run", [], []); -InspectorBackend.registerCommand("Runtime.enable", [], []); -InspectorBackend.registerCommand("Runtime.disable", [], []); diff --git a/Source/WebInspectorUI/UserInterface/InspectorObserver.js b/Source/WebInspectorUI/UserInterface/InspectorObserver.js deleted file mode 100644 index 716464534..000000000 --- a/Source/WebInspectorUI/UserInterface/InspectorObserver.js +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.InspectorObserver = function() -{ - WebInspector.Object.call(this); -}; - -WebInspector.InspectorObserver.prototype = { - constructor: WebInspector.InspectorObserver, - - // Events defined by the "Inspector" domain. - - evaluateForTestInFrontend: function(testCallId, script) - { - // FIXME: Not implemented. - }, - - inspect: function(payload, hints) - { - var remoteObject = WebInspector.RemoteObject.fromPayload(payload); - if (remoteObject.subtype === "node") { - WebInspector.domTreeManager.inspectNodeObject(remoteObject); - WebInspector.navigationSidebar.selectedSidebarPanel = WebInspector.resourceSidebarPanel; - return; - } - - if (hints.databaseId) - WebInspector.storageManager.inspectDatabase(hints.databaseId); - else if (hints.domStorageId) - WebInspector.storageManager.inspectDOMStorage(hints.domStorageId); - - WebInspector.navigationSidebar.selectedSidebarPanel = WebInspector.resourceSidebarPanel; - - remoteObject.release(); - }, - - detached: function(reason) - { - // FIXME: Not implemented. - } -}; - -WebInspector.InspectorObserver.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/InspectorWebBackendCommands.js b/Source/WebInspectorUI/UserInterface/InspectorWebBackendCommands.js deleted file mode 100644 index 1b3a31576..000000000 --- a/Source/WebInspectorUI/UserInterface/InspectorWebBackendCommands.js +++ /dev/null @@ -1,324 +0,0 @@ -// File is generated by JavaScriptCore/inspector/scripts/CodeGeneratorInspector.py - -// Copyright (c) 2013 Apple Inc. All Rights Reserved. -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - - -// ApplicationCache. -InspectorBackend.registerApplicationCacheDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "ApplicationCache"); -InspectorBackend.registerEvent("ApplicationCache.applicationCacheStatusUpdated", ["frameId", "manifestURL", "status"]); -InspectorBackend.registerEvent("ApplicationCache.networkStateUpdated", ["isNowOnline"]); -InspectorBackend.registerCommand("ApplicationCache.getFramesWithManifests", [], ["frameIds"]); -InspectorBackend.registerCommand("ApplicationCache.enable", [], []); -InspectorBackend.registerCommand("ApplicationCache.getManifestForFrame", [{"name": "frameId", "type": "string", "optional": false}], ["manifestURL"]); -InspectorBackend.registerCommand("ApplicationCache.getApplicationCacheForFrame", [{"name": "frameId", "type": "string", "optional": false}], ["applicationCache"]); - -// CSS. -InspectorBackend.registerCSSDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "CSS"); -InspectorBackend.registerEnum("CSS.StyleSheetOrigin", {User: "user", UserAgent: "user-agent", Inspector: "inspector", Regular: "regular"}); -InspectorBackend.registerEnum("CSS.CSSPropertyStatus", {Active: "active", Inactive: "inactive", Disabled: "disabled", Style: "style"}); -InspectorBackend.registerEnum("CSS.CSSMediaSource", {MediaRule: "mediaRule", ImportRule: "importRule", LinkedSheet: "linkedSheet", InlineSheet: "inlineSheet"}); -InspectorBackend.registerEnum("CSS.RegionRegionOverset", {Overset: "overset", Fit: "fit", Empty: "empty"}); -InspectorBackend.registerEvent("CSS.mediaQueryResultChanged", []); -InspectorBackend.registerEvent("CSS.styleSheetChanged", ["styleSheetId"]); -InspectorBackend.registerEvent("CSS.namedFlowCreated", ["namedFlow"]); -InspectorBackend.registerEvent("CSS.namedFlowRemoved", ["documentNodeId", "flowName"]); -InspectorBackend.registerEvent("CSS.regionLayoutUpdated", ["namedFlow"]); -InspectorBackend.registerEvent("CSS.regionOversetChanged", ["namedFlow"]); -InspectorBackend.registerEvent("CSS.registeredNamedFlowContentElement", ["documentNodeId", "flowName", "contentNodeId", "nextContentNodeId"]); -InspectorBackend.registerEvent("CSS.unregisteredNamedFlowContentElement", ["documentNodeId", "flowName", "contentNodeId"]); -InspectorBackend.registerCommand("CSS.enable", [], []); -InspectorBackend.registerCommand("CSS.disable", [], []); -InspectorBackend.registerCommand("CSS.getMatchedStylesForNode", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "includePseudo", "type": "boolean", "optional": true}, {"name": "includeInherited", "type": "boolean", "optional": true}], ["matchedCSSRules", "pseudoElements", "inherited"]); -InspectorBackend.registerCommand("CSS.getInlineStylesForNode", [{"name": "nodeId", "type": "number", "optional": false}], ["inlineStyle", "attributesStyle"]); -InspectorBackend.registerCommand("CSS.getComputedStyleForNode", [{"name": "nodeId", "type": "number", "optional": false}], ["computedStyle"]); -InspectorBackend.registerCommand("CSS.getAllStyleSheets", [], ["headers"]); -InspectorBackend.registerCommand("CSS.getStyleSheet", [{"name": "styleSheetId", "type": "string", "optional": false}], ["styleSheet"]); -InspectorBackend.registerCommand("CSS.getStyleSheetText", [{"name": "styleSheetId", "type": "string", "optional": false}], ["text"]); -InspectorBackend.registerCommand("CSS.setStyleSheetText", [{"name": "styleSheetId", "type": "string", "optional": false}, {"name": "text", "type": "string", "optional": false}], []); -InspectorBackend.registerCommand("CSS.setStyleText", [{"name": "styleId", "type": "object", "optional": false}, {"name": "text", "type": "string", "optional": false}], ["style"]); -InspectorBackend.registerCommand("CSS.setPropertyText", [{"name": "styleId", "type": "object", "optional": false}, {"name": "propertyIndex", "type": "number", "optional": false}, {"name": "text", "type": "string", "optional": false}, {"name": "overwrite", "type": "boolean", "optional": false}], ["style"]); -InspectorBackend.registerCommand("CSS.toggleProperty", [{"name": "styleId", "type": "object", "optional": false}, {"name": "propertyIndex", "type": "number", "optional": false}, {"name": "disable", "type": "boolean", "optional": false}], ["style"]); -InspectorBackend.registerCommand("CSS.setRuleSelector", [{"name": "ruleId", "type": "object", "optional": false}, {"name": "selector", "type": "string", "optional": false}], ["rule"]); -InspectorBackend.registerCommand("CSS.addRule", [{"name": "contextNodeId", "type": "number", "optional": false}, {"name": "selector", "type": "string", "optional": false}], ["rule"]); -InspectorBackend.registerCommand("CSS.getSupportedCSSProperties", [], ["cssProperties"]); -InspectorBackend.registerCommand("CSS.forcePseudoState", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "forcedPseudoClasses", "type": "object", "optional": false}], []); -InspectorBackend.registerCommand("CSS.getNamedFlowCollection", [{"name": "documentNodeId", "type": "number", "optional": false}], ["namedFlows"]); - -// Canvas. -InspectorBackend.registerCanvasDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Canvas"); -InspectorBackend.registerEvent("Canvas.contextCreated", ["frameId"]); -InspectorBackend.registerEvent("Canvas.traceLogsRemoved", ["frameId", "traceLogId"]); -InspectorBackend.registerCommand("Canvas.enable", [], []); -InspectorBackend.registerCommand("Canvas.disable", [], []); -InspectorBackend.registerCommand("Canvas.dropTraceLog", [{"name": "traceLogId", "type": "string", "optional": false}], []); -InspectorBackend.registerCommand("Canvas.hasUninstrumentedCanvases", [], ["result"]); -InspectorBackend.registerCommand("Canvas.captureFrame", [{"name": "frameId", "type": "string", "optional": true}], ["traceLogId"]); -InspectorBackend.registerCommand("Canvas.startCapturing", [{"name": "frameId", "type": "string", "optional": true}], ["traceLogId"]); -InspectorBackend.registerCommand("Canvas.stopCapturing", [{"name": "traceLogId", "type": "string", "optional": false}], []); -InspectorBackend.registerCommand("Canvas.getTraceLog", [{"name": "traceLogId", "type": "string", "optional": false}, {"name": "startOffset", "type": "number", "optional": true}, {"name": "maxLength", "type": "number", "optional": true}], ["traceLog"]); -InspectorBackend.registerCommand("Canvas.replayTraceLog", [{"name": "traceLogId", "type": "string", "optional": false}, {"name": "stepNo", "type": "number", "optional": false}], ["resourceState"]); -InspectorBackend.registerCommand("Canvas.getResourceInfo", [{"name": "resourceId", "type": "string", "optional": false}], ["resourceInfo"]); -InspectorBackend.registerCommand("Canvas.getResourceState", [{"name": "traceLogId", "type": "string", "optional": false}, {"name": "resourceId", "type": "string", "optional": false}], ["resourceState"]); - -// Console. -InspectorBackend.registerConsoleDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Console"); -InspectorBackend.registerEnum("Console.ConsoleMessageSource", {XML: "xml", Javascript: "javascript", Network: "network", ConsoleAPI: "console-api", Storage: "storage", Appcache: "appcache", Rendering: "rendering", CSS: "css", Security: "security", Other: "other"}); -InspectorBackend.registerEnum("Console.ConsoleMessageLevel", {Log: "log", Warning: "warning", Error: "error", Debug: "debug"}); -InspectorBackend.registerEnum("Console.ConsoleMessageType", {Log: "log", Dir: "dir", DirXML: "dirxml", Table: "table", Trace: "trace", Clear: "clear", StartGroup: "startGroup", StartGroupCollapsed: "startGroupCollapsed", EndGroup: "endGroup", Assert: "assert", Timing: "timing", Profile: "profile", ProfileEnd: "profileEnd"}); -InspectorBackend.registerEvent("Console.messageAdded", ["message"]); -InspectorBackend.registerEvent("Console.messageRepeatCountUpdated", ["count"]); -InspectorBackend.registerEvent("Console.messagesCleared", []); -InspectorBackend.registerCommand("Console.enable", [], []); -InspectorBackend.registerCommand("Console.disable", [], []); -InspectorBackend.registerCommand("Console.clearMessages", [], []); -InspectorBackend.registerCommand("Console.setMonitoringXHREnabled", [{"name": "enabled", "type": "boolean", "optional": false}], []); -InspectorBackend.registerCommand("Console.addInspectedNode", [{"name": "nodeId", "type": "number", "optional": false}], []); -InspectorBackend.registerCommand("Console.addInspectedHeapObject", [{"name": "heapObjectId", "type": "number", "optional": false}], []); - -// DOM. -InspectorBackend.registerDOMDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "DOM"); -InspectorBackend.registerEvent("DOM.documentUpdated", []); -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.registerCommand("DOM.getDocument", [], ["root"]); -InspectorBackend.registerCommand("DOM.requestChildNodes", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "depth", "type": "number", "optional": true}], []); -InspectorBackend.registerCommand("DOM.querySelector", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "selector", "type": "string", "optional": false}], ["nodeId"]); -InspectorBackend.registerCommand("DOM.querySelectorAll", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "selector", "type": "string", "optional": false}], ["nodeIds"]); -InspectorBackend.registerCommand("DOM.setNodeName", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "name", "type": "string", "optional": false}], ["nodeId"]); -InspectorBackend.registerCommand("DOM.setNodeValue", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "value", "type": "string", "optional": false}], []); -InspectorBackend.registerCommand("DOM.removeNode", [{"name": "nodeId", "type": "number", "optional": false}], []); -InspectorBackend.registerCommand("DOM.setAttributeValue", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "name", "type": "string", "optional": false}, {"name": "value", "type": "string", "optional": false}], []); -InspectorBackend.registerCommand("DOM.setAttributesAsText", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "text", "type": "string", "optional": false}, {"name": "name", "type": "string", "optional": true}], []); -InspectorBackend.registerCommand("DOM.removeAttribute", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "name", "type": "string", "optional": false}], []); -InspectorBackend.registerCommand("DOM.getEventListenersForNode", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "objectGroup", "type": "string", "optional": true}], ["listeners"]); -InspectorBackend.registerCommand("DOM.getOuterHTML", [{"name": "nodeId", "type": "number", "optional": false}], ["outerHTML"]); -InspectorBackend.registerCommand("DOM.setOuterHTML", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "outerHTML", "type": "string", "optional": false}], []); -InspectorBackend.registerCommand("DOM.performSearch", [{"name": "query", "type": "string", "optional": false}, {"name": "nodeIds", "type": "object", "optional": true}], ["searchId", "resultCount"]); -InspectorBackend.registerCommand("DOM.getSearchResults", [{"name": "searchId", "type": "string", "optional": false}, {"name": "fromIndex", "type": "number", "optional": false}, {"name": "toIndex", "type": "number", "optional": false}], ["nodeIds"]); -InspectorBackend.registerCommand("DOM.discardSearchResults", [{"name": "searchId", "type": "string", "optional": false}], []); -InspectorBackend.registerCommand("DOM.requestNode", [{"name": "objectId", "type": "string", "optional": false}], ["nodeId"]); -InspectorBackend.registerCommand("DOM.setInspectModeEnabled", [{"name": "enabled", "type": "boolean", "optional": false}, {"name": "highlightConfig", "type": "object", "optional": true}], []); -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}, {"name": "usePageCoordinates", "type": "boolean", "optional": true}], []); -InspectorBackend.registerCommand("DOM.highlightQuad", [{"name": "quad", "type": "object", "optional": false}, {"name": "color", "type": "object", "optional": true}, {"name": "outlineColor", "type": "object", "optional": true}, {"name": "usePageCoordinates", "type": "boolean", "optional": true}], []); -InspectorBackend.registerCommand("DOM.highlightNode", [{"name": "highlightConfig", "type": "object", "optional": false}, {"name": "nodeId", "type": "number", "optional": true}, {"name": "objectId", "type": "string", "optional": true}], []); -InspectorBackend.registerCommand("DOM.hideHighlight", [], []); -InspectorBackend.registerCommand("DOM.highlightFrame", [{"name": "frameId", "type": "string", "optional": false}, {"name": "contentColor", "type": "object", "optional": true}, {"name": "contentOutlineColor", "type": "object", "optional": true}], []); -InspectorBackend.registerCommand("DOM.pushNodeByPathToFrontend", [{"name": "path", "type": "string", "optional": false}], ["nodeId"]); -InspectorBackend.registerCommand("DOM.pushNodeByBackendIdToFrontend", [{"name": "backendNodeId", "type": "number", "optional": false}], ["nodeId"]); -InspectorBackend.registerCommand("DOM.releaseBackendNodeIds", [{"name": "nodeGroup", "type": "string", "optional": false}], []); -InspectorBackend.registerCommand("DOM.resolveNode", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "objectGroup", "type": "string", "optional": true}], ["object"]); -InspectorBackend.registerCommand("DOM.getAttributes", [{"name": "nodeId", "type": "number", "optional": false}], ["attributes"]); -InspectorBackend.registerCommand("DOM.moveTo", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "targetNodeId", "type": "number", "optional": false}, {"name": "insertBeforeNodeId", "type": "number", "optional": true}], ["nodeId"]); -InspectorBackend.registerCommand("DOM.undo", [], []); -InspectorBackend.registerCommand("DOM.redo", [], []); -InspectorBackend.registerCommand("DOM.markUndoableState", [], []); -InspectorBackend.registerCommand("DOM.focus", [{"name": "nodeId", "type": "number", "optional": false}], []); - -// DOMDebugger. -InspectorBackend.registerEnum("DOMDebugger.DOMBreakpointType", {SubtreeModified: "subtree-modified", AttributeModified: "attribute-modified", NodeRemoved: "node-removed"}); -InspectorBackend.registerCommand("DOMDebugger.setDOMBreakpoint", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "type", "type": "string", "optional": false}], []); -InspectorBackend.registerCommand("DOMDebugger.removeDOMBreakpoint", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "type", "type": "string", "optional": false}], []); -InspectorBackend.registerCommand("DOMDebugger.setEventListenerBreakpoint", [{"name": "eventName", "type": "string", "optional": false}], []); -InspectorBackend.registerCommand("DOMDebugger.removeEventListenerBreakpoint", [{"name": "eventName", "type": "string", "optional": false}], []); -InspectorBackend.registerCommand("DOMDebugger.setInstrumentationBreakpoint", [{"name": "eventName", "type": "string", "optional": false}], []); -InspectorBackend.registerCommand("DOMDebugger.removeInstrumentationBreakpoint", [{"name": "eventName", "type": "string", "optional": false}], []); -InspectorBackend.registerCommand("DOMDebugger.setXHRBreakpoint", [{"name": "url", "type": "string", "optional": false}], []); -InspectorBackend.registerCommand("DOMDebugger.removeXHRBreakpoint", [{"name": "url", "type": "string", "optional": false}], []); - -// DOMStorage. -InspectorBackend.registerDOMStorageDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "DOMStorage"); -InspectorBackend.registerEvent("DOMStorage.domStorageItemsCleared", ["storageId"]); -InspectorBackend.registerEvent("DOMStorage.domStorageItemRemoved", ["storageId", "key"]); -InspectorBackend.registerEvent("DOMStorage.domStorageItemAdded", ["storageId", "key", "newValue"]); -InspectorBackend.registerEvent("DOMStorage.domStorageItemUpdated", ["storageId", "key", "oldValue", "newValue"]); -InspectorBackend.registerCommand("DOMStorage.enable", [], []); -InspectorBackend.registerCommand("DOMStorage.disable", [], []); -InspectorBackend.registerCommand("DOMStorage.getDOMStorageItems", [{"name": "storageId", "type": "object", "optional": false}], ["entries"]); -InspectorBackend.registerCommand("DOMStorage.setDOMStorageItem", [{"name": "storageId", "type": "object", "optional": false}, {"name": "key", "type": "string", "optional": false}, {"name": "value", "type": "string", "optional": false}], []); -InspectorBackend.registerCommand("DOMStorage.removeDOMStorageItem", [{"name": "storageId", "type": "object", "optional": false}, {"name": "key", "type": "string", "optional": false}], []); - -// Database. -InspectorBackend.registerDatabaseDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Database"); -InspectorBackend.registerEvent("Database.addDatabase", ["database"]); -InspectorBackend.registerCommand("Database.enable", [], []); -InspectorBackend.registerCommand("Database.disable", [], []); -InspectorBackend.registerCommand("Database.getDatabaseTableNames", [{"name": "databaseId", "type": "string", "optional": false}], ["tableNames"]); -InspectorBackend.registerCommand("Database.executeSQL", [{"name": "databaseId", "type": "string", "optional": false}, {"name": "query", "type": "string", "optional": false}], ["columnNames", "values", "sqlError"]); - -// HeapProfiler. -InspectorBackend.registerHeapProfilerDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "HeapProfiler"); -InspectorBackend.registerEvent("HeapProfiler.addProfileHeader", ["header"]); -InspectorBackend.registerEvent("HeapProfiler.addHeapSnapshotChunk", ["uid", "chunk"]); -InspectorBackend.registerEvent("HeapProfiler.finishHeapSnapshot", ["uid"]); -InspectorBackend.registerEvent("HeapProfiler.resetProfiles", []); -InspectorBackend.registerEvent("HeapProfiler.reportHeapSnapshotProgress", ["done", "total"]); -InspectorBackend.registerCommand("HeapProfiler.hasHeapProfiler", [], ["result"]); -InspectorBackend.registerCommand("HeapProfiler.getProfileHeaders", [], ["headers"]); -InspectorBackend.registerCommand("HeapProfiler.getHeapSnapshot", [{"name": "uid", "type": "number", "optional": false}], []); -InspectorBackend.registerCommand("HeapProfiler.removeProfile", [{"name": "uid", "type": "number", "optional": false}], []); -InspectorBackend.registerCommand("HeapProfiler.clearProfiles", [], []); -InspectorBackend.registerCommand("HeapProfiler.takeHeapSnapshot", [{"name": "reportProgress", "type": "boolean", "optional": true}], []); -InspectorBackend.registerCommand("HeapProfiler.collectGarbage", [], []); -InspectorBackend.registerCommand("HeapProfiler.getObjectByHeapObjectId", [{"name": "objectId", "type": "string", "optional": false}, {"name": "objectGroup", "type": "string", "optional": true}], ["result"]); -InspectorBackend.registerCommand("HeapProfiler.getHeapObjectId", [{"name": "objectId", "type": "string", "optional": false}], ["heapSnapshotObjectId"]); - -// IndexedDB. -InspectorBackend.registerIndexedDBDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "IndexedDB"); -InspectorBackend.registerEnum("IndexedDB.KeyType", {Number: "number", String: "string", Date: "date", Array: "array"}); -InspectorBackend.registerEnum("IndexedDB.KeyPathType", {Null: "null", String: "string", Array: "array"}); -InspectorBackend.registerCommand("IndexedDB.enable", [], []); -InspectorBackend.registerCommand("IndexedDB.disable", [], []); -InspectorBackend.registerCommand("IndexedDB.requestDatabaseNames", [{"name": "securityOrigin", "type": "string", "optional": false}], ["databaseNames"]); -InspectorBackend.registerCommand("IndexedDB.requestDatabase", [{"name": "securityOrigin", "type": "string", "optional": false}, {"name": "databaseName", "type": "string", "optional": false}], ["databaseWithObjectStores"]); -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"]); -InspectorBackend.registerCommand("IndexedDB.clearObjectStore", [{"name": "securityOrigin", "type": "string", "optional": false}, {"name": "databaseName", "type": "string", "optional": false}, {"name": "objectStoreName", "type": "string", "optional": false}], []); - -// Input. -InspectorBackend.registerInputDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Input"); -InspectorBackend.registerCommand("Input.dispatchKeyEvent", [{"name": "type", "type": "string", "optional": false}, {"name": "modifiers", "type": "number", "optional": true}, {"name": "timestamp", "type": "number", "optional": true}, {"name": "text", "type": "string", "optional": true}, {"name": "unmodifiedText", "type": "string", "optional": true}, {"name": "keyIdentifier", "type": "string", "optional": true}, {"name": "windowsVirtualKeyCode", "type": "number", "optional": true}, {"name": "nativeVirtualKeyCode", "type": "number", "optional": true}, {"name": "macCharCode", "type": "number", "optional": true}, {"name": "autoRepeat", "type": "boolean", "optional": true}, {"name": "isKeypad", "type": "boolean", "optional": true}, {"name": "isSystemKey", "type": "boolean", "optional": true}], []); -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}], []); - -// LayerTree. -InspectorBackend.registerLayerTreeDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "LayerTree"); -InspectorBackend.registerEvent("LayerTree.layerTreeDidChange", []); -InspectorBackend.registerCommand("LayerTree.enable", [], []); -InspectorBackend.registerCommand("LayerTree.disable", [], []); -InspectorBackend.registerCommand("LayerTree.layersForNode", [{"name": "nodeId", "type": "number", "optional": false}], ["layers"]); -InspectorBackend.registerCommand("LayerTree.reasonsForCompositingLayer", [{"name": "layerId", "type": "string", "optional": false}], ["compositingReasons"]); - -// Memory. -InspectorBackend.registerMemoryDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Memory"); -InspectorBackend.registerCommand("Memory.getDOMCounters", [], ["documents", "nodes", "jsEventListeners"]); - -// Network. -InspectorBackend.registerNetworkDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Network"); -InspectorBackend.registerEnum("Network.InitiatorType", {Parser: "parser", Script: "script", Other: "other"}); -InspectorBackend.registerEvent("Network.requestWillBeSent", ["requestId", "frameId", "loaderId", "documentURL", "request", "timestamp", "initiator", "redirectResponse", "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", "sourceMapURL"]); -InspectorBackend.registerEvent("Network.loadingFailed", ["requestId", "timestamp", "errorText", "canceled"]); -InspectorBackend.registerEvent("Network.requestServedFromMemoryCache", ["requestId", "frameId", "loaderId", "documentURL", "timestamp", "initiator", "resource"]); -InspectorBackend.registerEvent("Network.webSocketWillSendHandshakeRequest", ["requestId", "timestamp", "request"]); -InspectorBackend.registerEvent("Network.webSocketHandshakeResponseReceived", ["requestId", "timestamp", "response"]); -InspectorBackend.registerEvent("Network.webSocketCreated", ["requestId", "url"]); -InspectorBackend.registerEvent("Network.webSocketClosed", ["requestId", "timestamp"]); -InspectorBackend.registerEvent("Network.webSocketFrameReceived", ["requestId", "timestamp", "response"]); -InspectorBackend.registerEvent("Network.webSocketFrameError", ["requestId", "timestamp", "errorMessage"]); -InspectorBackend.registerEvent("Network.webSocketFrameSent", ["requestId", "timestamp", "response"]); -InspectorBackend.registerCommand("Network.enable", [], []); -InspectorBackend.registerCommand("Network.disable", [], []); -InspectorBackend.registerCommand("Network.setExtraHTTPHeaders", [{"name": "headers", "type": "object", "optional": false}], []); -InspectorBackend.registerCommand("Network.getResponseBody", [{"name": "requestId", "type": "string", "optional": false}], ["body", "base64Encoded"]); -InspectorBackend.registerCommand("Network.replayXHR", [{"name": "requestId", "type": "string", "optional": false}], []); -InspectorBackend.registerCommand("Network.canClearBrowserCache", [], ["result"]); -InspectorBackend.registerCommand("Network.clearBrowserCache", [], []); -InspectorBackend.registerCommand("Network.canClearBrowserCookies", [], ["result"]); -InspectorBackend.registerCommand("Network.clearBrowserCookies", [], []); -InspectorBackend.registerCommand("Network.setCacheDisabled", [{"name": "cacheDisabled", "type": "boolean", "optional": false}], []); - -// Page. -InspectorBackend.registerPageDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Page"); -InspectorBackend.registerEnum("Page.ResourceType", {Document: "Document", Stylesheet: "Stylesheet", Image: "Image", Font: "Font", Script: "Script", XHR: "XHR", WebSocket: "WebSocket", Other: "Other"}); -InspectorBackend.registerEnum("Page.CoordinateSystem", {Viewport: "Viewport", Page: "Page"}); -InspectorBackend.registerEvent("Page.domContentEventFired", ["timestamp"]); -InspectorBackend.registerEvent("Page.loadEventFired", ["timestamp"]); -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.javascriptDialogOpening", ["message"]); -InspectorBackend.registerEvent("Page.javascriptDialogClosed", []); -InspectorBackend.registerEvent("Page.scriptsEnabled", ["isEnabled"]); -InspectorBackend.registerCommand("Page.enable", [], []); -InspectorBackend.registerCommand("Page.disable", [], []); -InspectorBackend.registerCommand("Page.addScriptToEvaluateOnLoad", [{"name": "scriptSource", "type": "string", "optional": false}], ["identifier"]); -InspectorBackend.registerCommand("Page.removeScriptToEvaluateOnLoad", [{"name": "identifier", "type": "string", "optional": false}], []); -InspectorBackend.registerCommand("Page.reload", [{"name": "ignoreCache", "type": "boolean", "optional": true}, {"name": "scriptToEvaluateOnLoad", "type": "string", "optional": true}], []); -InspectorBackend.registerCommand("Page.navigate", [{"name": "url", "type": "string", "optional": false}], []); -InspectorBackend.registerCommand("Page.getCookies", [], ["cookies"]); -InspectorBackend.registerCommand("Page.deleteCookie", [{"name": "cookieName", "type": "string", "optional": false}, {"name": "url", "type": "string", "optional": false}], []); -InspectorBackend.registerCommand("Page.getResourceTree", [], ["frameTree"]); -InspectorBackend.registerCommand("Page.getResourceContent", [{"name": "frameId", "type": "string", "optional": false}, {"name": "url", "type": "string", "optional": false}], ["content", "base64Encoded"]); -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"]); -InspectorBackend.registerCommand("Page.searchInResources", [{"name": "text", "type": "string", "optional": false}, {"name": "caseSensitive", "type": "boolean", "optional": true}, {"name": "isRegex", "type": "boolean", "optional": true}], ["result"]); -InspectorBackend.registerCommand("Page.setDocumentContent", [{"name": "frameId", "type": "string", "optional": false}, {"name": "html", "type": "string", "optional": false}], []); -InspectorBackend.registerCommand("Page.setShowPaintRects", [{"name": "result", "type": "boolean", "optional": false}], []); -InspectorBackend.registerCommand("Page.canShowDebugBorders", [], ["show"]); -InspectorBackend.registerCommand("Page.setShowDebugBorders", [{"name": "show", "type": "boolean", "optional": false}], []); -InspectorBackend.registerCommand("Page.canShowFPSCounter", [], ["show"]); -InspectorBackend.registerCommand("Page.setShowFPSCounter", [{"name": "show", "type": "boolean", "optional": false}], []); -InspectorBackend.registerCommand("Page.canContinuouslyPaint", [], ["value"]); -InspectorBackend.registerCommand("Page.setContinuousPaintingEnabled", [{"name": "enabled", "type": "boolean", "optional": false}], []); -InspectorBackend.registerCommand("Page.getScriptExecutionStatus", [], ["result"]); -InspectorBackend.registerCommand("Page.setScriptExecutionDisabled", [{"name": "value", "type": "boolean", "optional": false}], []); -InspectorBackend.registerCommand("Page.setTouchEmulationEnabled", [{"name": "enabled", "type": "boolean", "optional": false}], []); -InspectorBackend.registerCommand("Page.setEmulatedMedia", [{"name": "media", "type": "string", "optional": false}], []); -InspectorBackend.registerCommand("Page.getCompositingBordersVisible", [], ["result"]); -InspectorBackend.registerCommand("Page.setCompositingBordersVisible", [{"name": "visible", "type": "boolean", "optional": false}], []); -InspectorBackend.registerCommand("Page.snapshotNode", [{"name": "nodeId", "type": "number", "optional": false}], ["dataURL"]); -InspectorBackend.registerCommand("Page.snapshotRect", [{"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": "coordinateSystem", "type": "string", "optional": false}], ["dataURL"]); -InspectorBackend.registerCommand("Page.handleJavaScriptDialog", [{"name": "accept", "type": "boolean", "optional": false}, {"name": "promptText", "type": "string", "optional": true}], []); -InspectorBackend.registerCommand("Page.archive", [], ["data"]); - -// Profiler. -InspectorBackend.registerProfilerDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Profiler"); -InspectorBackend.registerEnum("Profiler.ProfileHeaderTypeId", {CPU: "CPU", CSS: "CSS", HEAP: "HEAP"}); -InspectorBackend.registerEvent("Profiler.addProfileHeader", ["header"]); -InspectorBackend.registerEvent("Profiler.addHeapSnapshotChunk", ["uid", "chunk"]); -InspectorBackend.registerEvent("Profiler.finishHeapSnapshot", ["uid"]); -InspectorBackend.registerEvent("Profiler.setRecordingProfile", ["isProfiling"]); -InspectorBackend.registerEvent("Profiler.resetProfiles", []); -InspectorBackend.registerEvent("Profiler.reportHeapSnapshotProgress", ["done", "total"]); -InspectorBackend.registerCommand("Profiler.isSampling", [], ["result"]); -InspectorBackend.registerCommand("Profiler.hasHeapProfiler", [], ["result"]); -InspectorBackend.registerCommand("Profiler.enable", [], []); -InspectorBackend.registerCommand("Profiler.disable", [], []); -InspectorBackend.registerCommand("Profiler.start", [], []); -InspectorBackend.registerCommand("Profiler.stop", [], []); -InspectorBackend.registerCommand("Profiler.getProfileHeaders", [], ["headers"]); -InspectorBackend.registerCommand("Profiler.getCPUProfile", [{"name": "uid", "type": "number", "optional": false}], ["profile"]); -InspectorBackend.registerCommand("Profiler.getHeapSnapshot", [{"name": "uid", "type": "number", "optional": false}], []); -InspectorBackend.registerCommand("Profiler.removeProfile", [{"name": "type", "type": "string", "optional": false}, {"name": "uid", "type": "number", "optional": false}], []); -InspectorBackend.registerCommand("Profiler.clearProfiles", [], []); -InspectorBackend.registerCommand("Profiler.takeHeapSnapshot", [{"name": "reportProgress", "type": "boolean", "optional": true}], []); -InspectorBackend.registerCommand("Profiler.collectGarbage", [], []); -InspectorBackend.registerCommand("Profiler.getObjectByHeapObjectId", [{"name": "objectId", "type": "string", "optional": false}, {"name": "objectGroup", "type": "string", "optional": true}], ["result"]); -InspectorBackend.registerCommand("Profiler.getHeapObjectId", [{"name": "objectId", "type": "string", "optional": false}], ["heapSnapshotObjectId"]); - -// Timeline. -InspectorBackend.registerTimelineDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Timeline"); -InspectorBackend.registerEnum("Timeline.EventType", {EventDispatch: "EventDispatch", BeginFrame: "BeginFrame", ScheduleStyleRecalculation: "ScheduleStyleRecalculation", RecalculateStyles: "RecalculateStyles", InvalidateLayout: "InvalidateLayout", Layout: "Layout", Paint: "Paint", ScrollLayer: "ScrollLayer", ResizeImage: "ResizeImage", CompositeLayers: "CompositeLayers", ParseHTML: "ParseHTML", TimerInstall: "TimerInstall", TimerRemove: "TimerRemove", TimerFire: "TimerFire", EvaluateScript: "EvaluateScript", MarkLoad: "MarkLoad", MarkDOMContent: "MarkDOMContent", TimeStamp: "TimeStamp", Time: "Time", TimeEnd: "TimeEnd", ScheduleResourceRequest: "ScheduleResourceRequest", ResourceSendRequest: "ResourceSendRequest", ResourceReceiveResponse: "ResourceReceiveResponse", ResourceReceivedData: "ResourceReceivedData", ResourceFinish: "ResourceFinish", XHRReadyStateChange: "XHRReadyStateChange", XHRLoad: "XHRLoad", FunctionCall: "FunctionCall", GCEvent: "GCEvent", RequestAnimationFrame: "RequestAnimationFrame", CancelAnimationFrame: "CancelAnimationFrame", FireAnimationFrame: "FireAnimationFrame", WebSocketCreate: "WebSocketCreate", WebSocketSendHandshakeRequest: "WebSocketSendHandshakeRequest", WebSocketReceiveHandshakeResponse: "WebSocketReceiveHandshakeResponse", WebSocketDestroy: "WebSocketDestroy"}); -InspectorBackend.registerEvent("Timeline.eventRecorded", ["record"]); -InspectorBackend.registerCommand("Timeline.start", [{"name": "maxCallStackDepth", "type": "number", "optional": true}, {"name": "includeDomCounters", "type": "boolean", "optional": true}], []); -InspectorBackend.registerCommand("Timeline.stop", [], []); -InspectorBackend.registerCommand("Timeline.supportsFrameInstrumentation", [], ["result"]); -InspectorBackend.registerCommand("Timeline.canMonitorMainThread", [], ["result"]); - -// Worker. -InspectorBackend.registerWorkerDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Worker"); -InspectorBackend.registerEvent("Worker.workerCreated", ["workerId", "url", "inspectorConnected"]); -InspectorBackend.registerEvent("Worker.workerTerminated", ["workerId"]); -InspectorBackend.registerEvent("Worker.dispatchMessageFromWorker", ["workerId", "message"]); -InspectorBackend.registerEvent("Worker.disconnectedFromWorker", []); -InspectorBackend.registerCommand("Worker.enable", [], []); -InspectorBackend.registerCommand("Worker.disable", [], []); -InspectorBackend.registerCommand("Worker.sendMessageToWorker", [{"name": "workerId", "type": "number", "optional": false}, {"name": "message", "type": "object", "optional": false}], []); -InspectorBackend.registerCommand("Worker.canInspectWorkers", [], ["result"]); -InspectorBackend.registerCommand("Worker.connectToWorker", [{"name": "workerId", "type": "number", "optional": false}], []); -InspectorBackend.registerCommand("Worker.disconnectFromWorker", [{"name": "workerId", "type": "number", "optional": false}], []); -InspectorBackend.registerCommand("Worker.setAutoconnectToWorkers", [{"name": "value", "type": "boolean", "optional": false}], []); diff --git a/Source/WebInspectorUI/UserInterface/IssueManager.js b/Source/WebInspectorUI/UserInterface/IssueManager.js deleted file mode 100644 index f70e5aceb..000000000 --- a/Source/WebInspectorUI/UserInterface/IssueManager.js +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.IssueManager = function() -{ - WebInspector.Object.call(this); - - WebInspector.Frame.addEventListener(WebInspector.Frame.Event.MainResourceDidChange, this._mainResourceDidChange, this); - WebInspector.logManager.addEventListener(WebInspector.LogManager.Event.ActiveLogCleared, this._activeLogCleared, this); - - this.initialize(); -} - -WebInspector.IssueManager.Event = { - IssueWasAdded: "issue-manager-issue-was-added", - Cleared: "issue-manager-cleared" -}; - -WebInspector.IssueManager.prototype = { - constructor: WebInspector.IssueManager, - - // Public - - initialize: function() - { - this._issues = []; - - this.dispatchEventToListeners(WebInspector.IssueManager.Event.Cleared); - }, - - issueWasAdded: function(source, level, text, url, lineNumber, parameters) - { - var modifiedLineNumber; - if (lineNumber) { - console.assert(typeof lineNumber === "number"); - modifiedLineNumber = lineNumber - 1; - } - - var issue = new WebInspector.IssueMessage(source, level, text, url, modifiedLineNumber, parameters); - this._issues.push(issue); - - this.dispatchEventToListeners(WebInspector.IssueManager.Event.IssueWasAdded, {issue: issue}); - }, - - issuesForSourceCode: function(sourceCode) - { - var issues = []; - - for (var i = 0; i < this._issues.length; ++i) { - // FIXME: Support issues based on Script identifiers too. - var issue = this._issues[i]; - if (issue.url === sourceCode.url) - issues.push(issue); - } - - return issues; - }, - - // Private - - _activeLogCleared: function(event) - { - this.initialize(); - }, - - _mainResourceDidChange: function(event) - { - console.assert(event.target instanceof WebInspector.Frame); - - if (!event.target.isMainFrame()) - return; - - this.initialize(); - } -}; - -WebInspector.IssueManager.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/IssueMessage.js b/Source/WebInspectorUI/UserInterface/IssueMessage.js deleted file mode 100644 index 6894175f5..000000000 --- a/Source/WebInspectorUI/UserInterface/IssueMessage.js +++ /dev/null @@ -1,242 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.IssueMessage = function(source, level, text, url, lineNumber, parameters) -{ - WebInspector.Object.call(this); - - this._level = level; - this._text = text; - - // FIXME : Remove the string equality checks for undefined - // once we don't get that value anymore from WebCore. - - // FIXME: If the URL is undefined, get the URL from the stacktrace. - if (url && url !== "undefined") - this._url = url; - - if (typeof lineNumber === "number" && lineNumber >= 0) - this._lineNumber = lineNumber; - - if (parameters && parameters !== "undefined") { - this._parameters = []; - for (var i = 0; i < parameters.length; ++i) { - if (parameters[i] instanceof WebInspector.RemoteObject) { - this._parameters.push(parameters[i]); - continue; - } - - if (typeof parameters[i] === "object") - this._parameters.push(WebInspector.RemoteObject.fromPayload(parameters[i])); - else - this._parameters.push(WebInspector.RemoteObject.fromPrimitiveValue(parameters[i])); - } - } - - this._formatTextIfNecessary(); - - switch (source) { - case "javascript": - // FIXME: It would be nice if we had this information (the specific type of JavaScript error) - // as part of the data passed from WebCore, instead of having to determine it ourselves. - var prefixRegex = /^([^:]+): (?:DOM Exception \d+: )?/; - var match = prefixRegex.exec(this._text); - if (match && match[1] in WebInspector.IssueMessage.Type._prefixTypeMap) { - this._type = WebInspector.IssueMessage.Type._prefixTypeMap[match[1]]; - this._text = this._text.substring(match[0].length); - } else - this._type = WebInspector.IssueMessage.Type.OtherIssue; - break; - - case "html": - case "css": - case "wml": - case "xml": - this._type = WebInspector.IssueMessage.Type.PageIssue; - break; - - case "network": - this._type = WebInspector.IssueMessage.Type.NetworkIssue; - break; - - case "console-api": - case "other": - this._type = WebInspector.IssueMessage.Type.OtherIssue; - break; - - default: - console.error("Unknown issue source:", source); - this._type = WebInspector.IssueMessage.Type.OtherIssue; - } -} - -WebInspector.IssueMessage.Level = { - Error: "error", - Warning: "warning" -}; - -WebInspector.IssueMessage.Type = { - SemanticIssue: "issue-message-type-semantic-issue", - RangeIssue: "issue-message-type-range-issue", - ReferenceIssue: "issue-message-type-reference-issue", - TypeIssue: "issue-message-type-type-issue", - PageIssue: "issue-message-type-page-issue", - NetworkIssue: "issue-message-type-network-issue", - SecurityIssue: "issue-message-type-security-issue", - OtherIssue: "issue-message-type-other-issue" -}; - -WebInspector.IssueMessage.Type._prefixTypeMap = { - "SyntaxError": WebInspector.IssueMessage.Type.SemanticIssue, - "URIError": WebInspector.IssueMessage.Type.SemanticIssue, - "EvalError": WebInspector.IssueMessage.Type.SemanticIssue, - "INVALID_CHARACTER_ERR": WebInspector.IssueMessage.Type.SemanticIssue, - "SYNTAX_ERR": WebInspector.IssueMessage.Type.SemanticIssue, - - "RangeError": WebInspector.IssueMessage.Type.RangeIssue, - "INDEX_SIZE_ERR": WebInspector.IssueMessage.Type.RangeIssue, - "DOMSTRING_SIZE_ERR": WebInspector.IssueMessage.Type.RangeIssue, - - "ReferenceError": WebInspector.IssueMessage.Type.ReferenceIssue, - "HIERARCHY_REQUEST_ERR": WebInspector.IssueMessage.Type.ReferenceIssue, - "INVALID_STATE_ERR": WebInspector.IssueMessage.Type.ReferenceIssue, - "NOT_FOUND_ERR": WebInspector.IssueMessage.Type.ReferenceIssue, - "WRONG_DOCUMENT_ERR": WebInspector.IssueMessage.Type.ReferenceIssue, - - "TypeError": WebInspector.IssueMessage.Type.TypeIssue, - "INVALID_NODE_TYPE_ERR": WebInspector.IssueMessage.Type.TypeIssue, - "TYPE_MISMATCH_ERR": WebInspector.IssueMessage.Type.TypeIssue, - - "SECURITY_ERR": WebInspector.IssueMessage.Type.SecurityIssue, - - "NETWORK_ERR": WebInspector.IssueMessage.Type.NetworkIssue, - - "ABORT_ERR": WebInspector.IssueMessage.Type.OtherIssue, - "DATA_CLONE_ERR": WebInspector.IssueMessage.Type.OtherIssue, - "INUSE_ATTRIBUTE_ERR": WebInspector.IssueMessage.Type.OtherIssue, - "INVALID_ACCESS_ERR": WebInspector.IssueMessage.Type.OtherIssue, - "INVALID_MODIFICATION_ERR": WebInspector.IssueMessage.Type.OtherIssue, - "NAMESPACE_ERR": WebInspector.IssueMessage.Type.OtherIssue, - "NOT_SUPPORTED_ERR": WebInspector.IssueMessage.Type.OtherIssue, - "NO_DATA_ALLOWED_ERR": WebInspector.IssueMessage.Type.OtherIssue, - "NO_MODIFICATION_ALLOWED_ERR": WebInspector.IssueMessage.Type.OtherIssue, - "QUOTA_EXCEEDED_ERR": WebInspector.IssueMessage.Type.OtherIssue, - "TIMEOUT_ERR": WebInspector.IssueMessage.Type.OtherIssue, - "URL_MISMATCH_ERR": WebInspector.IssueMessage.Type.OtherIssue, - "VALIDATION_ERR": WebInspector.IssueMessage.Type.OtherIssue -}; - -WebInspector.IssueMessage.Type.displayName = function(type) -{ - switch(type) { - case WebInspector.IssueMessage.Type.SemanticIssue: - return WebInspector.UIString("Semantic Issue"); - case WebInspector.IssueMessage.Type.RangeIssue: - return WebInspector.UIString("Range Issue"); - case WebInspector.IssueMessage.Type.ReferenceIssue: - return WebInspector.UIString("Reference Issue"); - case WebInspector.IssueMessage.Type.TypeIssue: - return WebInspector.UIString("Type Issue"); - case WebInspector.IssueMessage.Type.PageIssue: - return WebInspector.UIString("Page Issue"); - case WebInspector.IssueMessage.Type.NetworkIssue: - return WebInspector.UIString("Network Issue"); - case WebInspector.IssueMessage.Type.SecurityIssue: - return WebInspector.UIString("Security Issue"); - case WebInspector.IssueMessage.Type.OtherIssue: - return WebInspector.UIString("Other Issue"); - default: - console.error("Unknown issue message type:", type); - return WebInspector.UIString("Other Issue"); - } -}; - -WebInspector.IssueMessage.prototype = { - constructor: WebInspector.IssueMessage, - - get type() - { - return this._type; - }, - - get level() - { - return this._level; - }, - - get text() - { - return this._text; - }, - - get url() - { - return this._url; - }, - - get lineNumber() - { - return this._lineNumber; - }, - - // Private - - _formatTextIfNecessary: function() - { - if (!this._parameters) - return; - - if (WebInspector.RemoteObject.type(this._parameters[0]) !== "string") - return; - - function valueFormatter(obj) - { - return obj.description; - } - - var formatters = {}; - formatters.o = valueFormatter; - formatters.s = valueFormatter; - formatters.f = valueFormatter; - formatters.i = valueFormatter; - formatters.d = valueFormatter; - - function append(a, b) - { - a += b; - return a; - } - - var result = String.format(this._parameters[0].description, this._parameters.slice(1), formatters, "", append); - var resultText = result.formattedResult; - - for (var i = 0; i < result.unusedSubstitutions.length; ++i) - resultText += " " + result.unusedSubstitutions[i].description; - - this._text = resultText; - } -}; - -WebInspector.IssueMessage.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/JavaScriptLogViewController.js b/Source/WebInspectorUI/UserInterface/JavaScriptLogViewController.js deleted file mode 100644 index 9dcd6f32b..000000000 --- a/Source/WebInspectorUI/UserInterface/JavaScriptLogViewController.js +++ /dev/null @@ -1,292 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.JavaScriptLogViewController = function(element, scrollElement, textPrompt, delegate, historySettingIdentifier) -{ - WebInspector.Object.call(this); - - console.assert(textPrompt instanceof WebInspector.ConsolePrompt); - console.assert(historySettingIdentifier); - - this._element = element; - this._scrollElement = scrollElement; - - this._promptHistorySetting = new WebInspector.Setting(historySettingIdentifier, null); - - this._prompt = textPrompt; - this._prompt.delegate = this; - this._prompt.history = this._promptHistorySetting.value; - - this.delegate = delegate; - - this._cleared = true; - this._previousMessage = null; - this._repeatCountWasInterrupted = false; - - this._topConsoleGroups = []; - - this.messagesClearKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, "K", this._handleClearShortcut.bind(this)); - this.messagesAlternateClearKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.Control, "L", this._handleClearShortcut.bind(this), this._element); - - this._messagesFindKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, "F", this._handleFindShortcut.bind(this), this._element); - this._messagesFindNextKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, "G", this._handleFindNextShortcut.bind(this), this._element); - this._messagesFindPreviousKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl | WebInspector.KeyboardShortcut.Modifier.Shift, "G", this._handleFindPreviousShortcut.bind(this), this._element); - - this._promptAlternateClearKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.Control, "L", this._handleClearShortcut.bind(this), this._prompt.element); - this._promptFindKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, "F", this._handleFindShortcut.bind(this), this._prompt.element); - this._promptFindNextKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, "G", this._handleFindNextShortcut.bind(this), this._prompt.element); - this._promptFindPreviousKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl | WebInspector.KeyboardShortcut.Modifier.Shift, "G", this._handleFindPreviousShortcut.bind(this), this._prompt.element); - - this.startNewSession(); -}; - -WebInspector.JavaScriptLogViewController.CachedPropertiesDuration = 30000; - -WebInspector.JavaScriptLogViewController.prototype = { - constructor: WebInspector.JavaScriptLogViewController, - - // Public - - get prompt() - { - return this._prompt; - }, - - get topConsoleGroup() - { - return this._topConsoleGroup; - }, - - get currentConsoleGroup() - { - return this._currentConsoleGroup; - }, - - clear: function() - { - this._cleared = true; - - this.startNewSession(true); - - this.prompt.focus(); - - if (this.delegate && typeof this.delegate.didClearMessages === "function") - this.delegate.didClearMessages(); - }, - - startNewSession: function(clearPreviousSessions) - { - if (this._topConsoleGroups.length && clearPreviousSessions) { - for (var i = 0; i < this._topConsoleGroups.length; ++i) - this._element.removeChild(this._topConsoleGroups[i].element); - - this._topConsoleGroups = []; - this._topConsoleGroup = null; - this._currentConsoleGroup = null; - } - - // Reuse the top group if it has no messages. - if (this._topConsoleGroup && !this._topConsoleGroup.hasMessages()) { - // Make sure the session is visible. - this._topConsoleGroup.element.scrollIntoView(); - return; - } - - var hasPreviousSession = !!this._topConsoleGroup; - var consoleGroup = new WebInspector.ConsoleGroup(null, hasPreviousSession); - - this._previousMessage = null; - this._repeatCountWasInterrupted = false; - - this._topConsoleGroups.push(consoleGroup); - this._topConsoleGroup = consoleGroup; - this._currentConsoleGroup = consoleGroup; - - this._element.appendChild(consoleGroup.element); - - // Make sure the new session is visible. - consoleGroup.element.scrollIntoView(); - }, - - appendConsoleMessage: function(consoleMessage) - { - // Clone the message since there might be multiple clients using the message, - // and since the message has a DOM element it can't be two places at once. - var messageClone = consoleMessage.clone(); - - this._appendConsoleMessage(messageClone); - - return messageClone; - }, - - updatePreviousMessageRepeatCount: function(count) - { - console.assert(this._previousMessage); - if (!this._previousMessage) - return; - - if (!this._repeatCountWasInterrupted) { - this._previousMessage.repeatCount = count - (this._previousMessage.ignoredCount || 0); - this._previousMessage.updateRepeatCount(); - } else { - var newMessage = this._previousMessage.clone(); - - // If this message is repeated after being cloned, messageRepeatCountUpdated will be called with a - // count that includes the count of this message before cloning. We should ignore instances of this - // log that occurred before we cloned, so set a property on the message with the number of previous - // instances of this log that we should ignore. - newMessage.ignoredCount = newMessage.repeatCount + (this._previousMessage.ignoredCount || 0); - newMessage.repeatCount = 1; - - this._appendConsoleMessage(newMessage); - } - }, - - isScrolledToBottom: function() - { - // Lie about being scrolled to the bottom if we have a pending request to scroll to the bottom soon. - return this._scrollToBottomTimeout || this._scrollElement.isScrolledToBottom(); - }, - - scrollToBottom: function() - { - if (this._scrollToBottomTimeout) - return; - - function delayedWork() - { - this._scrollToBottomTimeout = null; - this._scrollElement.scrollTop = this._scrollElement.scrollHeight; - } - - // Don't scroll immediately so we are not causing excessive layouts when there - // are many messages being added at once. - this._scrollToBottomTimeout = setTimeout(delayedWork.bind(this), 0); - }, - - // Protected - - consolePromptHistoryDidChange: function(prompt) - { - this._promptHistorySetting.value = this.prompt.history; - }, - - consolePromptShouldCommitText: function(prompt, text, cursorIsAtLastPosition, handler) - { - // Always commit the text if we are not at the last position. - if (!cursorIsAtLastPosition) { - handler(true); - return; - } - - // COMPATIBILITY (iOS 6): RuntimeAgent.parse did not exist in iOS 6. Always commit. - if (!RuntimeAgent.parse) { - handler(true); - return; - } - - function parseFinished(error, result, message, range) - { - handler(result !== RuntimeAgent.SyntaxErrorType.Recoverable); - } - - RuntimeAgent.parse(text, parseFinished.bind(this)); - }, - - consolePromptTextCommitted: function(prompt, text) - { - console.assert(text); - - var commandMessage = new WebInspector.ConsoleCommand(text); - this._appendConsoleMessage(commandMessage, true); - - function printResult(result, wasThrown) - { - if (!result || this._cleared) - return; - - this._appendConsoleMessage(new WebInspector.ConsoleCommandResult(result, wasThrown, commandMessage), true); - } - - text += "\n//# sourceURL=__WebInspectorConsole__\n"; - - WebInspector.runtimeManager.evaluateInInspectedWindow(text, "console", true, false, false, printResult.bind(this)); - }, - - // Private - - _handleClearShortcut: function() - { - this.clear(); - }, - - _handleFindShortcut: function() - { - this.delegate.focusSearchBar(); - }, - - _handleFindNextShortcut: function() - { - this.delegate.highlightNextSearchMatch(); - }, - - _handleFindPreviousShortcut: function() - { - this.delegate.highlightPreviousSearchMatch(); - }, - - _appendConsoleMessage: function(msg, repeatCountWasInterrupted) - { - var wasScrolledToBottom = this.isScrolledToBottom(); - - this._cleared = false; - this._repeatCountWasInterrupted = repeatCountWasInterrupted || false; - - if (!repeatCountWasInterrupted) - this._previousMessage = msg; - - if (msg.type === WebInspector.ConsoleMessage.MessageType.EndGroup) { - var parentGroup = this._currentConsoleGroup.parentGroup; - if (parentGroup) - this._currentConsoleGroup = parentGroup; - } else { - if (msg.type === WebInspector.ConsoleMessage.MessageType.StartGroup || msg.type === WebInspector.ConsoleMessage.MessageType.StartGroupCollapsed) { - var group = new WebInspector.ConsoleGroup(this._currentConsoleGroup); - this._currentConsoleGroup.messagesElement.appendChild(group.element); - this._currentConsoleGroup = group; - } - - this._currentConsoleGroup.addMessage(msg); - } - - if (msg.type === WebInspector.ConsoleMessage.MessageType.Result || wasScrolledToBottom) - this.scrollToBottom(); - - if (this.delegate && typeof this.delegate.didAppendConsoleMessage === "function") - this.delegate.didAppendConsoleMessage(msg); - } -}; - -WebInspector.JavaScriptLogViewController.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/JavaScriptProfileObject.js b/Source/WebInspectorUI/UserInterface/JavaScriptProfileObject.js deleted file mode 100644 index 75755bc60..000000000 --- a/Source/WebInspectorUI/UserInterface/JavaScriptProfileObject.js +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.JavaScriptProfileObject = function(title, id, recording) -{ - WebInspector.ProfileObject.call(this, WebInspector.JavaScriptProfileType.TypeId, title, id, recording); -}; - -WebInspector.JavaScriptProfileObject.prototype = { - constructor: WebInspector.JavaScriptProfileObject -}; - -WebInspector.JavaScriptProfileObject.prototype.__proto__ = WebInspector.ProfileObject.prototype; diff --git a/Source/WebInspectorUI/UserInterface/JavaScriptProfileType.js b/Source/WebInspectorUI/UserInterface/JavaScriptProfileType.js deleted file mode 100644 index 13c68b61b..000000000 --- a/Source/WebInspectorUI/UserInterface/JavaScriptProfileType.js +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (C) 2008, 2013 Apple Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.JavaScriptProfileType = function() -{ - WebInspector.ProfileType.call(this, WebInspector.JavaScriptProfileType.TypeId, WebInspector.UIString("Collect JavaScript Profile")); - this._recording = false; - WebInspector.JavaScriptProfileType.instance = this; -} - -WebInspector.JavaScriptProfileType.TypeId = "CPU"; - -WebInspector.JavaScriptProfileType.prototype = { - get buttonTooltip() - { - return this._recording ? WebInspector.UIString("Stop JavaScript profiling.") : WebInspector.UIString("Start JavaScript profiling."); - }, - - buttonClicked: function() - { - if (this._recording) { - this.stopRecordingProfile(); - WebInspector.networkManager.enableResourceTracking(); - } else { - WebInspector.networkManager.disableResourceTracking(); - this.startRecordingProfile(); - } - }, - - get treeItemTitle() - { - return WebInspector.UIString("JAVASCRIPT PROFILES"); - }, - - get description() - { - return WebInspector.UIString("JavaScript profiles show where the execution time is spent in your page's JavaScript functions."); - }, - - isRecordingProfile: function() - { - return this._recording; - }, - - startRecordingProfile: function() - { - this._recording = true; - ProfilerAgent.start(); - }, - - stopRecordingProfile: function() - { - this._recording = false; - ProfilerAgent.stop(); - }, - - setRecordingProfile: function(isProfiling) - { - this._recording = isProfiling; - }, - - createSidebarTreeElementForProfile: function(profile) - { - return new WebInspector.ProfileSidebarTreeElement(profile, WebInspector.UIString("Profile %d"), "profile-sidebar-tree-item"); - }, - - createView: function(profile) - { - return new WebInspector.JavaScriptProfileView(profile); - } -} - -WebInspector.JavaScriptProfileType.prototype.__proto__ = WebInspector.ProfileType.prototype; diff --git a/Source/WebInspectorUI/UserInterface/JavaScriptProfileView.css b/Source/WebInspectorUI/UserInterface/JavaScriptProfileView.css deleted file mode 100644 index 94889c556..000000000 --- a/Source/WebInspectorUI/UserInterface/JavaScriptProfileView.css +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.content-view.profile-view > .data-grid { - position: absolute; - top: 0; - left: 0; - right: 0; - bottom: 0; - outline: none; - border: none; -} - -.profile-view .data-grid th.average-column { - text-align: center; -} - -.profile-view .data-grid td.average-column { - text-align: right; -} - -.profile-view .data-grid th.self-column { - text-align: center; -} - -.profile-view .data-grid td.self-column { - text-align: right; -} - -.profile-view .data-grid th.total-column { - text-align: center; -} - -.profile-view .data-grid td.total-column { - text-align: right; -} - -.profile-view .data-grid .calls-column { - text-align: center; -} - -.profile-node-file { - float: right; - color: gray; - margin-top: -1px; -} - -.data-grid tr.selected .profile-node-file { - color: rgb(33%, 33%, 33%); -} - -.data-grid:focus tr.selected .profile-node-file { - color: white; -} diff --git a/Source/WebInspectorUI/UserInterface/JavaScriptProfileView.js b/Source/WebInspectorUI/UserInterface/JavaScriptProfileView.js deleted file mode 100644 index 4945b0ba5..000000000 --- a/Source/WebInspectorUI/UserInterface/JavaScriptProfileView.js +++ /dev/null @@ -1,468 +0,0 @@ -/* - * Copyright (C) 2008, 2013 Apple Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.JavaScriptProfileView = function(profile) -{ - console.assert(profile instanceof WebInspector.JavaScriptProfileObject); - - WebInspector.ProfileView.call(this, profile, "javascript-profiler-show-time-as-percent"); - - this._showTreeBottomUpSetting = new WebInspector.Setting("javascript-profiler-show-tree-bottom-up", true); - - this._showTreeBottomUpNavigationItem = new WebInspector.ActivateButtonNavigationItem("show-tree-bottom-up-navigation-item", WebInspector.UIString("Invert call tree"), WebInspector.UIString("Normal call tree"), "Images/BottomUpTree.svg", 16, 16); - this._showTreeBottomUpNavigationItem.addEventListener(WebInspector.ButtonNavigationItem.Event.Clicked, this._toggleBottomUpView, this); - this._showTreeBottomUpNavigationItem.activated = this._showTreeBottomUpSetting.value; - - this._viewType = new WebInspector.Setting("javascript-profiler-view", WebInspector.JavaScriptProfileView._TypeHeavy); -} - -WebInspector.JavaScriptProfileView._TypeTree = "Tree"; -WebInspector.JavaScriptProfileView._TypeHeavy = "Heavy"; - -WebInspector.JavaScriptProfileView.prototype = { - constructor: WebInspector.JavaScriptProfileView, - - updateLayout: function() - { - if (this.dataGrid) - this.dataGrid.updateLayout(); - }, - - get recordingTitle() - { - return WebInspector.UIString("Recording JavaScript Profile\u2026"); - }, - - displayProfile: function() - { - var columns = { "self": { title: WebInspector.UIString("Self"), width: "72px", sort: "descending", sortable: true }, - "total": { title: WebInspector.UIString("Total"), width: "72px", sortable: true }, - "average": { title: WebInspector.UIString("Average"), width: "72px", sortable: true }, - "calls": { title: WebInspector.UIString("Calls"), width: "54px", sortable: true }, - "function": { title: WebInspector.UIString("Function"), disclosure: true, sortable: true } }; - - this.dataGrid = new WebInspector.DataGrid(columns); - this.dataGrid.addEventListener(WebInspector.DataGrid.Event.SortChanged, this._sortData, this); - - this.element.appendChild(this.dataGrid.element); - this.dataGrid.updateLayout(); - - function profileCallback(error, profile) - { - if (error) - return; - - if (!profile.head) { - // Profiling was tentatively terminated with the "Clear all profiles." button. - return; - } - this.profile.head = profile.head; - this._assignParentsInProfile(); - this._changeView(); - } - - // COMPATIBILITY (iOS 6): getCPUProfile use to be called getProfile. - if (ProfilerAgent.getProfile) - ProfilerAgent.getProfile(this.profile.type, this.profile.id, profileCallback.bind(this)); - else - ProfilerAgent.getCPUProfile(this.profile.id, profileCallback.bind(this)); - }, - - get navigationItems() - { - return [this._showTreeBottomUpNavigationItem, this.showTimeAsPercentNavigationItem]; - }, - - get bottomUpProfileDataGridTree() - { - if (!this._bottomUpProfileDataGridTree) - this._bottomUpProfileDataGridTree = new WebInspector.BottomUpProfileDataGridTree(this, this.profile.head); - return this._bottomUpProfileDataGridTree; - }, - - get topDownProfileDataGridTree() - { - if (!this._topDownProfileDataGridTree) - this._topDownProfileDataGridTree = new WebInspector.TopDownProfileDataGridTree(this, this.profile.head); - return this._topDownProfileDataGridTree; - }, - - willHide: function() - { - this._currentSearchResultIndex = -1; - }, - - refresh: function() - { - var selectedProfileNode = this.dataGrid.selectedNode ? this.dataGrid.selectedNode.profileNode : null; - - this.dataGrid.removeChildren(); - - var children = this.profileDataGridTree.children; - var count = children.length; - - for (var index = 0; index < count; ++index) - this.dataGrid.appendChild(children[index]); - - if (selectedProfileNode) - selectedProfileNode.selected = true; - }, - - refreshVisibleData: function() - { - var child = this.dataGrid.children[0]; - while (child) { - child.refresh(); - child = child.traverseNextNode(false, null, true); - } - }, - - searchCanceled: function() - { - if (this._searchResults) { - for (var i = 0; i < this._searchResults.length; ++i) { - var profileNode = this._searchResults[i].profileNode; - - delete profileNode._searchMatchedSelfColumn; - delete profileNode._searchMatchedTotalColumn; - delete profileNode._searchMatchedCallsColumn; - delete profileNode._searchMatchedFunctionColumn; - - profileNode.refresh(); - } - } - - delete this._searchFinishedCallback; - this._currentSearchResultIndex = -1; - this._searchResults = []; - }, - - performSearch: function(query, finishedCallback) - { - // Call searchCanceled since it will reset everything we need before doing a new search. - this.searchCanceled(); - - query = query.trim(); - - if (!query.length) - return; - - this._searchFinishedCallback = finishedCallback; - - var greaterThan = query.charAt(0) === ">"; - var lessThan = query.charAt(0) === "<"; - var equalTo = (query.charAt(0) === "=" || ((greaterThan || lessThan) && query.charAt(1) === "=")); - var percentUnits = (query.lastIndexOf("%") === (query.length - 1)); - var millisecondsUnits = (query.length > 2 && query.lastIndexOf("ms") === (query.length - 2)); - var secondsUnits = (!millisecondsUnits && query.lastIndexOf("s") === (query.length - 1)); - - var queryNumber = parseFloat(query); - if (greaterThan || lessThan || equalTo) { - if (equalTo && (greaterThan || lessThan)) - queryNumber = parseFloat(query.substring(2)); - else - queryNumber = parseFloat(query.substring(1)); - } - - var queryNumberMilliseconds = (secondsUnits ? (queryNumber * 1000) : queryNumber); - - // Make equalTo implicitly true if it wasn't specified there is no other operator. - if (!isNaN(queryNumber) && !(greaterThan || lessThan)) - equalTo = true; - - function matchesQuery(/*ProfileDataGridNode*/ profileDataGridNode) - { - delete profileDataGridNode._searchMatchedSelfColumn; - delete profileDataGridNode._searchMatchedTotalColumn; - delete profileDataGridNode._searchMatchedAverageColumn; - delete profileDataGridNode._searchMatchedCallsColumn; - delete profileDataGridNode._searchMatchedFunctionColumn; - - if (percentUnits) { - if (lessThan) { - if (profileDataGridNode.selfPercent < queryNumber) - profileDataGridNode._searchMatchedSelfColumn = true; - if (profileDataGridNode.totalPercent < queryNumber) - profileDataGridNode._searchMatchedTotalColumn = true; - if (profileDataGridNode.averagePercent < queryNumberMilliseconds) - profileDataGridNode._searchMatchedAverageColumn = true; - } else if (greaterThan) { - if (profileDataGridNode.selfPercent > queryNumber) - profileDataGridNode._searchMatchedSelfColumn = true; - if (profileDataGridNode.totalPercent > queryNumber) - profileDataGridNode._searchMatchedTotalColumn = true; - if (profileDataGridNode.averagePercent < queryNumberMilliseconds) - profileDataGridNode._searchMatchedAverageColumn = true; - } - - if (equalTo) { - if (profileDataGridNode.selfPercent == queryNumber) - profileDataGridNode._searchMatchedSelfColumn = true; - if (profileDataGridNode.totalPercent == queryNumber) - profileDataGridNode._searchMatchedTotalColumn = true; - if (profileDataGridNode.averagePercent < queryNumberMilliseconds) - profileDataGridNode._searchMatchedAverageColumn = true; - } - } else if (millisecondsUnits || secondsUnits) { - if (lessThan) { - if (profileDataGridNode.selfTime < queryNumberMilliseconds) - profileDataGridNode._searchMatchedSelfColumn = true; - if (profileDataGridNode.totalTime < queryNumberMilliseconds) - profileDataGridNode._searchMatchedTotalColumn = true; - if (profileDataGridNode.averageTime < queryNumberMilliseconds) - profileDataGridNode._searchMatchedAverageColumn = true; - } else if (greaterThan) { - if (profileDataGridNode.selfTime > queryNumberMilliseconds) - profileDataGridNode._searchMatchedSelfColumn = true; - if (profileDataGridNode.totalTime > queryNumberMilliseconds) - profileDataGridNode._searchMatchedTotalColumn = true; - if (profileDataGridNode.averageTime > queryNumberMilliseconds) - profileDataGridNode._searchMatchedAverageColumn = true; - } - - if (equalTo) { - if (profileDataGridNode.selfTime == queryNumberMilliseconds) - profileDataGridNode._searchMatchedSelfColumn = true; - if (profileDataGridNode.totalTime == queryNumberMilliseconds) - profileDataGridNode._searchMatchedTotalColumn = true; - if (profileDataGridNode.averageTime == queryNumberMilliseconds) - profileDataGridNode._searchMatchedAverageColumn = true; - } - } else { - if (equalTo && profileDataGridNode.numberOfCalls == queryNumber) - profileDataGridNode._searchMatchedCallsColumn = true; - if (greaterThan && profileDataGridNode.numberOfCalls > queryNumber) - profileDataGridNode._searchMatchedCallsColumn = true; - if (lessThan && profileDataGridNode.numberOfCalls < queryNumber) - profileDataGridNode._searchMatchedCallsColumn = true; - } - - if (profileDataGridNode.functionName.hasSubstring(query, true) || profileDataGridNode.url.hasSubstring(query, true)) - profileDataGridNode._searchMatchedFunctionColumn = true; - - if (profileDataGridNode._searchMatchedSelfColumn || - profileDataGridNode._searchMatchedTotalColumn || - profileDataGridNode._searchMatchedAverageColumn || - profileDataGridNode._searchMatchedCallsColumn || - profileDataGridNode._searchMatchedFunctionColumn) - { - profileDataGridNode.refresh(); - return true; - } - - return false; - } - - var current = this.profileDataGridTree.children[0]; - - while (current) { - if (matchesQuery(current)) { - this._searchResults.push({ profileNode: current }); - } - - current = current.traverseNextNode(false, null, false); - } - - finishedCallback(this, this._searchResults.length); - }, - - jumpToFirstSearchResult: function() - { - if (!this._searchResults || !this._searchResults.length) - return; - this._currentSearchResultIndex = 0; - this._jumpToSearchResult(this._currentSearchResultIndex); - }, - - jumpToLastSearchResult: function() - { - if (!this._searchResults || !this._searchResults.length) - return; - this._currentSearchResultIndex = (this._searchResults.length - 1); - this._jumpToSearchResult(this._currentSearchResultIndex); - }, - - jumpToNextSearchResult: function() - { - if (!this._searchResults || !this._searchResults.length) - return; - if (++this._currentSearchResultIndex >= this._searchResults.length) - this._currentSearchResultIndex = 0; - this._jumpToSearchResult(this._currentSearchResultIndex); - }, - - jumpToPreviousSearchResult: function() - { - if (!this._searchResults || !this._searchResults.length) - return; - if (--this._currentSearchResultIndex < 0) - this._currentSearchResultIndex = (this._searchResults.length - 1); - this._jumpToSearchResult(this._currentSearchResultIndex); - }, - - showingFirstSearchResult: function() - { - return (this._currentSearchResultIndex === 0); - }, - - showingLastSearchResult: function() - { - return (this._searchResults && this._currentSearchResultIndex === (this._searchResults.length - 1)); - }, - - _jumpToSearchResult: function(index) - { - var searchResult = this._searchResults[index]; - if (!searchResult) - return; - - var profileNode = searchResult.profileNode; - profileNode.revealAndSelect(); - }, - - _toggleBottomUpView: function(event) - { - this._showTreeBottomUpSetting.value = !this._showTreeBottomUpSetting.value; - this._showTreeBottomUpNavigationItem.activated = this._showTreeBottomUpSetting.value; - this._changeView(); - }, - - _changeView: function() - { - if (!this.profile) - return; - - if (!this._showTreeBottomUpSetting.value) { - this.profileDataGridTree = this.topDownProfileDataGridTree; - this._sortProfile(); - this._viewType.value = WebInspector.JavaScriptProfileView._TypeTree; - } else { - this.profileDataGridTree = this.bottomUpProfileDataGridTree; - this._sortProfile(); - this._viewType.value = WebInspector.JavaScriptProfileView._TypeHeavy; - } - - if (!this.currentQuery || !this._searchFinishedCallback || !this._searchResults) - return; - - // The current search needs to be performed again. First negate out previous match - // count by calling the search finished callback with a negative number of matches. - // Then perform the search again the with same query and callback. - this._searchFinishedCallback(this, -this._searchResults.length); - this.performSearch(this.currentQuery, this._searchFinishedCallback); - }, - - toggleTimeDisplay: function(event) - { - WebInspector.ProfileView.prototype.toggleTimeDisplay.call(this, event); - this.showTimeAsPercent.value = !this.showTimeAsPercent.value; - this.refreshVisibleData(); - }, - - _focusClicked: function(event) - { - if (!this.dataGrid.selectedNode) - return; - - this.profileDataGridTree.focus(this.dataGrid.selectedNode); - this.refresh(); - this.refreshVisibleData(); - }, - - _excludeClicked: function(event) - { - var selectedNode = this.dataGrid.selectedNode; - - if (!selectedNode) - return; - - selectedNode.deselect(); - - this.profileDataGridTree.exclude(selectedNode); - this.refresh(); - this.refreshVisibleData(); - }, - - _resetClicked: function(event) - { - this.profileDataGridTree.restore(); - this.refresh(); - this.refreshVisibleData(); - }, - - _dataGridNodeSelected: function(node) - { - // FIXME: Update UI we have to focus on a data grid node or exclude it from the profile. - }, - - _dataGridNodeDeselected: function(node) - { - // FIXME: Update UI we have to focus on a data grid node or exclude it from the profile. - }, - - _sortData: function(event) - { - this._sortProfile(this.profile); - }, - - _sortProfile: function() - { - var sortAscending = this.dataGrid.sortOrder === "ascending"; - var sortColumnIdentifier = this.dataGrid.sortColumnIdentifier; - var sortProperty = { - "average": "averageTime", - "self": "selfTime", - "total": "totalTime", - "calls": "numberOfCalls", - "function": "functionName" - }[sortColumnIdentifier]; - - this.profileDataGridTree.sort(WebInspector.ProfileDataGridTree.propertyComparator(sortProperty, sortAscending)); - - this.refresh(); - }, - - _assignParentsInProfile: function() - { - var head = this.profile.head; - head.parent = null; - head.head = null; - var nodesToTraverse = [ { parent: head, children: head.children } ]; - while (nodesToTraverse.length > 0) { - var pair = nodesToTraverse.shift(); - var parent = pair.parent; - var children = pair.children; - var length = children.length; - for (var i = 0; i < length; ++i) { - children[i].head = head; - children[i].parent = parent; - if (children[i].children.length > 0) - nodesToTraverse.push({ parent: children[i], children: children[i].children }); - } - } - } -} - -WebInspector.JavaScriptProfileView.prototype.__proto__ = WebInspector.ProfileView.prototype; diff --git a/Source/WebInspectorUI/UserInterface/JavaScriptRuntimeCompletionProvider.js b/Source/WebInspectorUI/UserInterface/JavaScriptRuntimeCompletionProvider.js deleted file mode 100644 index 0c2d98fb2..000000000 --- a/Source/WebInspectorUI/UserInterface/JavaScriptRuntimeCompletionProvider.js +++ /dev/null @@ -1,244 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.JavaScriptRuntimeCompletionProvider = function() -{ - WebInspector.Object.call(this); - - console.assert(!WebInspector.JavaScriptRuntimeCompletionProvider._instance); - - WebInspector.debuggerManager.addEventListener(WebInspector.DebuggerManager.Event.ActiveCallFrameDidChange, this._clearLastProperties, this); -}; - -Object.defineProperty(WebInspector, "javaScriptRuntimeCompletionProvider", -{ - get: function() - { - if (!WebInspector.JavaScriptRuntimeCompletionProvider._instance) - WebInspector.JavaScriptRuntimeCompletionProvider._instance = new WebInspector.JavaScriptRuntimeCompletionProvider; - return WebInspector.JavaScriptRuntimeCompletionProvider._instance; - } -}); - -WebInspector.JavaScriptRuntimeCompletionProvider.prototype = { - constructor: WebInspector.JavaScriptRuntimeCompletionProvider, - - // Protected - - completionControllerCompletionsNeeded: function(completionController, defaultCompletions, base, prefix, suffix, forced) - { - // Don't allow non-forced empty prefix completions unless the base is that start of property access. - if (!forced && !prefix && !/[.[]$/.test(base)) { - completionController.updateCompletions(null); - return; - } - - // If the base ends with an open parentheses or open curly bracket then treat it like there is - // no base so we get global object completions. - if (/[({]$/.test(base)) - base = ""; - - var lastBaseIndex = base.length - 1; - var dotNotation = base[lastBaseIndex] === "."; - var bracketNotation = base[lastBaseIndex] === "["; - - if (dotNotation || bracketNotation) { - base = base.substring(0, lastBaseIndex); - - // Don't suggest anything for an empty base that is using dot notation. - // Bracket notation with an empty base will be treated as an array. - if (!base && dotNotation) { - completionController.updateCompletions(defaultCompletions); - return; - } - - // Don't allow non-forced empty prefix completions if the user is entering a number, since it might be a float. - // But allow number completions if the base already has a decimal, so "10.0." will suggest Number properties. - if (!forced && !prefix && dotNotation && base.indexOf(".") === -1 && parseInt(base, 10) == base) { - completionController.updateCompletions(null); - return; - } - - // An empty base with bracket notation is not property access, it is an array. - // Clear the bracketNotation flag so completions are not quoted. - if (!base && bracketNotation) - bracketNotation = false; - } - - // If the base is the same as the last time, we can reuse the property names we have already gathered. - // Doing this eliminates delay caused by the async nature of the code below and it only calls getters - // and functions once instead of repetitively. Sure, there can be difference each time the base is evaluated, - // but this optimization gives us more of a win. We clear the cache after 30 seconds or when stepping in the - // debugger to make sure we don't use stale properties in most cases. - if (this._lastBase === base && this._lastPropertyNames) { - receivedPropertyNames.call(this, this._lastPropertyNames); - return; - } - - this._lastBase = base; - this._lastPropertyNames = null; - - var activeCallFrame = WebInspector.debuggerManager.activeCallFrame; - if (!base && activeCallFrame && !this._alwaysEvaluateInWindowContext) - activeCallFrame.collectScopeChainVariableNames(receivedPropertyNames.bind(this)); - else - WebInspector.runtimeManager.evaluateInInspectedWindow(base, "completion", true, true, false, evaluated.bind(this)); - - function updateLastPropertyNames(propertyNames) - { - if (this._clearLastPropertiesTimeout) - clearTimeout(this._clearLastPropertiesTimeout); - this._clearLastPropertiesTimeout = setTimeout(this._clearLastProperties.bind(this), WebInspector.JavaScriptLogViewController.CachedPropertiesDuration); - - this._lastPropertyNames = propertyNames || {}; - } - - function evaluated(result, wasThrown) - { - if (wasThrown || !result || result.type === "undefined" || (result.type === "object" && result.subtype === "null")) { - RuntimeAgent.releaseObjectGroup("completion"); - - updateLastPropertyNames.call(this, {}); - completionController.updateCompletions(defaultCompletions); - - return; - } - - function getCompletions(primitiveType) - { - var object; - if (primitiveType === "string") - object = new String(""); - else if (primitiveType === "number") - object = new Number(0); - else if (primitiveType === "boolean") - object = new Boolean(false); - else - object = this; - - var resultSet = {}; - for (var o = object; o; o = o.__proto__) { - try { - var names = Object.getOwnPropertyNames(o); - for (var i = 0; i < names.length; ++i) - resultSet[names[i]] = true; - } catch (e) { - // Ignore - } - } - - return resultSet; - } - - if (result.type === "object" || result.type === "function") - result.callFunctionJSON(getCompletions, undefined, receivedPropertyNames.bind(this)); - else if (result.type === "string" || result.type === "number" || result.type === "boolean") - WebInspector.runtimeManager.evaluateInInspectedWindow("(" + getCompletions + ")(\"" + result.type + "\")", "completion", false, true, true, receivedPropertyNamesFromEvaluate.bind(this)); - else - console.error("Unknown result type: " + result.type); - } - - function receivedPropertyNamesFromEvaluate(object, wasThrown, result) - { - receivedPropertyNames.call(this, result && !wasThrown ? result.value : null); - } - - function receivedPropertyNames(propertyNames) - { - propertyNames = propertyNames || {}; - - updateLastPropertyNames.call(this, propertyNames); - - RuntimeAgent.releaseObjectGroup("completion"); - - if (!base) { - const commandLineAPI = ["$", "$$", "$x", "dir", "dirxml", "keys", "values", "profile", "profileEnd", "monitorEvents", "unmonitorEvents", "inspect", "copy", "clear", "getEventListeners", "$0", "$1", "$2", "$3", "$4", "$_"]; - for (var i = 0; i < commandLineAPI.length; ++i) - propertyNames[commandLineAPI[i]] = true; - } - - propertyNames = Object.keys(propertyNames); - - var implicitSuffix = ""; - if (bracketNotation) { - var quoteUsed = prefix[0] === "'" ? "'" : "\""; - if (suffix !== "]" && suffix !== quoteUsed) - implicitSuffix = "]"; - } - - var completions = defaultCompletions; - var knownCompletions = completions.keySet(); - - for (var i = 0; i < propertyNames.length; ++i) { - var property = propertyNames[i]; - - if (dotNotation && !/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(property)) - continue; - - if (bracketNotation) { - if (parseInt(property) != property) - property = quoteUsed + property.escapeCharacters(quoteUsed + "\\") + (suffix !== quoteUsed ? quoteUsed : ""); - } - - if (!property.startsWith(prefix) || property in knownCompletions) - continue; - - completions.push(property); - knownCompletions[property] = true; - } - - function compare(a, b) - { - // Try to sort in numerical order first. - var numericCompareResult = a - b; - if (!isNaN(numericCompareResult)) - return numericCompareResult; - - // Not numbers, sort as strings. - return a.localeCompare(b); - } - - completions.sort(compare); - - completionController.updateCompletions(completions, implicitSuffix); - } - }, - - // Private - - _clearLastProperties: function() - { - if (this._clearLastPropertiesTimeout) { - clearTimeout(this._clearLastPropertiesTimeout); - delete this._clearLastPropertiesTimeout; - } - - // Clear the cache of property names so any changes while stepping or sitting idle get picked up if the same - // expression is evaluated again. - this._lastPropertyNames = null; - } -}; - -WebInspector.JavaScriptRuntimeCompletionProvider.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/KeyboardShortcut.js b/Source/WebInspectorUI/UserInterface/KeyboardShortcut.js deleted file mode 100644 index ef68c24df..000000000 --- a/Source/WebInspectorUI/UserInterface/KeyboardShortcut.js +++ /dev/null @@ -1,254 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.KeyboardShortcut = function(modifiers, key, callback, targetElement) -{ - WebInspector.Object.call(this); - - console.assert(key); - console.assert(!callback || typeof callback === "function"); - console.assert(!targetElement || targetElement instanceof Element); - - if (typeof key === "string") { - key = key[0].toUpperCase(); - key = new WebInspector.Key(key.charCodeAt(0), key); - } - - if (callback && !targetElement) - targetElement = document; - - this._modifiers = modifiers || WebInspector.KeyboardShortcut.Modifier.None; - this._key = key; - this._targetElement = targetElement; - this._callback = callback; - this._disabled = false; - this._implicitlyPreventsDefault = true; - - if (targetElement) { - var targetKeyboardShortcuts = targetElement._keyboardShortcuts; - if (!targetKeyboardShortcuts) - targetKeyboardShortcuts = targetElement._keyboardShortcuts = []; - - targetKeyboardShortcuts.push(this); - - if (!WebInspector.KeyboardShortcut._registeredKeyDownListener) { - WebInspector.KeyboardShortcut._registeredKeyDownListener = true; - window.addEventListener("keydown", WebInspector.KeyboardShortcut._handleKeyDown); - } - } -}; - -WebInspector.KeyboardShortcut._handleKeyDown = function(event) -{ - if (event.defaultPrevented) - return; - - for (var targetElement = event.target; targetElement; targetElement = targetElement.parentNode) { - if (!targetElement._keyboardShortcuts) - continue; - - for (var i = 0; i < targetElement._keyboardShortcuts.length; ++i) { - var keyboardShortcut = targetElement._keyboardShortcuts[i]; - if (!keyboardShortcut.matchesEvent(event)) - continue; - - keyboardShortcut.callback(event, keyboardShortcut); - - if (keyboardShortcut.implicitlyPreventsDefault) - event.preventDefault(); - - return; - } - } -}; - -WebInspector.KeyboardShortcut.Modifier = { - None: 0, - Shift: 1, - Control: 2, - Option: 4, - Command: 8, - - get CommandOrControl() - { - return InspectorFrontendHost.platform() === "mac" ? this.Command : this.Control; - } -}; - -WebInspector.Key = function(keyCode, displayName) -{ - this._keyCode = keyCode; - this._displayName = displayName; -}; - -WebInspector.Key.prototype = { - get keyCode() - { - return this._keyCode; - }, - - get displayName() - { - return this._displayName; - }, - - toString: function() - { - return this._displayName; - } -}; - -WebInspector.KeyboardShortcut.Key = { - Backspace: new WebInspector.Key(8, "\u232b"), - Tab: new WebInspector.Key(9, "\u21e5"), - Enter: new WebInspector.Key(13, "\u21a9"), - Escape: new WebInspector.Key(27, "\u238b"), - Space: new WebInspector.Key(32, "Space"), - PageUp: new WebInspector.Key(33, "\u21de"), - PageDown: new WebInspector.Key(34, "\u21df"), - End: new WebInspector.Key(35, "\u2198"), - Home: new WebInspector.Key(36, "\u2196"), - Left: new WebInspector.Key(37, "\u2190"), - Up: new WebInspector.Key(38, "\u2191"), - Right: new WebInspector.Key(39, "\u2192"), - Down: new WebInspector.Key(40, "\u2193"), - Delete: new WebInspector.Key(46, "\u2326"), - Zero: new WebInspector.Key(48, "0"), - F1: new WebInspector.Key(112, "F1"), - F2: new WebInspector.Key(113, "F2"), - F3: new WebInspector.Key(114, "F3"), - F4: new WebInspector.Key(115, "F4"), - F5: new WebInspector.Key(116, "F5"), - F6: new WebInspector.Key(117, "F6"), - F7: new WebInspector.Key(118, "F7"), - F8: new WebInspector.Key(119, "F8"), - F9: new WebInspector.Key(120, "F9"), - F10: new WebInspector.Key(121, "F10"), - F11: new WebInspector.Key(122, "F11"), - F12: new WebInspector.Key(123, "F12"), - Semicolon: new WebInspector.Key(186, ";"), - Plus: new WebInspector.Key(187, "+"), - Comma: new WebInspector.Key(188, ","), - Minus: new WebInspector.Key(189, "-"), - Period: new WebInspector.Key(190, "."), - Slash: new WebInspector.Key(191, "/"), - Apostrophe: new WebInspector.Key(192, "`"), - SingleQuote: new WebInspector.Key(222, "\'") -}; - -WebInspector.KeyboardShortcut.prototype = { - constructor: WebInspector.KeyboardShortcut, - - // Public - - get modifiers() - { - return this._modifiers; - }, - - get key() - { - return this._key; - }, - - get displayName() - { - var result = ""; - - if (this._modifiers & WebInspector.KeyboardShortcut.Modifier.Control) - result += "\u2303"; - if (this._modifiers & WebInspector.KeyboardShortcut.Modifier.Option) - result += InspectorFrontendHost.platform() === "mac" ? "\u2325" : "\u2387"; - if (this._modifiers & WebInspector.KeyboardShortcut.Modifier.Shift) - result += "\u21e7"; - if (this._modifiers & WebInspector.KeyboardShortcut.Modifier.Command) - result += "\u2318"; - - result += this._key.toString(); - - return result; - }, - - get callback() - { - return this._callback; - }, - - get disabled() - { - return this._disabled; - }, - - set disabled(disabled) - { - this._disabled = disabled || false; - }, - - get implicitlyPreventsDefault() - { - return this._implicitlyPreventsDefault; - }, - - set implicitlyPreventsDefault(implicitly) - { - this._implicitlyPreventsDefault = implicitly; - }, - - unbind: function() - { - this._disabled = true; - - if (!this._targetElement) - return; - - var targetKeyboardShortcuts = this._targetElement._keyboardShortcuts; - if (!targetKeyboardShortcuts) - return; - - targetKeyboardShortcuts.remove(this); - }, - - matchesEvent: function(event) - { - if (this._disabled) - return false; - - if (this._key.keyCode !== event.keyCode) - return false; - - var eventModifiers = WebInspector.KeyboardShortcut.Modifier.None; - if (event.shiftKey) - eventModifiers |= WebInspector.KeyboardShortcut.Modifier.Shift; - if (event.ctrlKey) - eventModifiers |= WebInspector.KeyboardShortcut.Modifier.Control; - if (event.altKey) - eventModifiers |= WebInspector.KeyboardShortcut.Modifier.Option; - if (event.metaKey) - eventModifiers |= WebInspector.KeyboardShortcut.Modifier.Command; - return this._modifiers === eventModifiers; - } -}; - -WebInspector.KeyboardShortcut.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/LayerTreeDataGrid.js b/Source/WebInspectorUI/UserInterface/LayerTreeDataGrid.js deleted file mode 100644 index 8bd9c7147..000000000 --- a/Source/WebInspectorUI/UserInterface/LayerTreeDataGrid.js +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.LayerTreeDataGrid = function() { - WebInspector.DataGrid.call(this, { - name: { title: WebInspector.UIString("Node"), sortable: false }, - paintCount: { title: WebInspector.UIString("Paints"), sortable: true, aligned: "right", width: "50px" }, - memory: { title: WebInspector.UIString("Memory"), sortable: true, sort: "descending", aligned: "right", width: "70px" } - }); -}; - -WebInspector.LayerTreeDataGrid.prototype = { - constructor: WebInspector.LayerTreeDataGrid, - - insertChild: function(child) - { - WebInspector.DataGrid.prototype.insertChild.call(this, child); - - this._updateChildren(); - }, - - removeChild: function(child) - { - WebInspector.DataGrid.prototype.removeChild.call(this, child); - - this._updateChildren(); - }, - - setChildren: function(children) - { - this._suspendLayout = true; - - var removedChildren = this.children.filter(function(child) { - return !children.contains(child); - }); - - while (removedChildren.length) - this.removeChild(removedChildren.pop()); - - children.forEach(function(child) { - if (child.parent !== this) - this.appendChild(child); - }.bind(this)); - - this._suspendLayout = false; - - this.children = children; - this._updateChildren(); - }, - - _updateChildren: function() - { - if (this._suspendLayout) - return; - - // Iterate through nodes by DOM order first so we can establish - // the DOM index. - var elements = this.dataTableBody.rows; - for (var i = 0, count = elements.length - 1; i < count; ++i) - elements[i]._dataGridNode._domIndex = i; - - // Now iterate through children to set up their sibling relationship - // and update the element style to offset the position of the node - // to match its position in the children list vs. DOM order. - var children = this.children; - for (var i = 0, count = children.length; i < count; ++i) { - var child = children[i]; - child.previousSibling = i > 0 ? children[i - 1] : null; - child.nextSibling = i + 1 < count ? children[i + 1] : null; - - var ty = (i - child._domIndex) * 100; - child.element.style.webkitTransform = "translateY(" + ty + "%)"; - - // Since the DOM order won't necessarily match the visual order of the - // children in the data grid we manually set "even" and "odd" and CSS - // class names on the data grid nodes so that they may be styled with - // a different mechanism than the built-in CSS pseudo-classes. - var classList = child.element.classList; - if (i % 2) { - classList.remove("odd"); - classList.add("even"); - } else { - classList.remove("even"); - classList.add("odd"); - } - } - - this.hasChildren = this.children.length > 0; - }, - - _recalculateSiblings: function(myIndex) - { - // Overriding default implementation to do nothing at all - // since we're setting sibling relationship in _updateChildren. - } -}; - -WebInspector.LayerTreeDataGrid.prototype.__proto__ = WebInspector.DataGrid.prototype; diff --git a/Source/WebInspectorUI/UserInterface/LayerTreeDataGridNode.js b/Source/WebInspectorUI/UserInterface/LayerTreeDataGridNode.js deleted file mode 100644 index 82538ecf7..000000000 --- a/Source/WebInspectorUI/UserInterface/LayerTreeDataGridNode.js +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.LayerTreeDataGridNode = function(layer) -{ - WebInspector.DataGridNode.call(this); - - this._outlets = {}; - - this.layer = layer; -}; - -WebInspector.LayerTreeDataGridNode.prototype = { - constructor: WebInspector.DataGridNode, - - // DataGridNode Overrides. - - createCells: function() - { - WebInspector.DataGridNode.prototype.createCells.call(this); - - this._cellsWereCreated = true; - }, - - createCellContent: function(columnIdentifier, cell) - { - var cell = columnIdentifier === "name" ? this._makeNameCell() : this._makeOutlet(columnIdentifier, document.createTextNode()); - this._updateCell(columnIdentifier); - return cell; - }, - - // Public - - get layer() - { - return this._layer; - }, - - set layer(layer) - { - this._layer = layer; - - var domNode = WebInspector.domTreeManager.nodeForId(layer.nodeId); - - this.data = { - name: domNode ? WebInspector.displayNameForNode(domNode) : WebInspector.UIString("Unknown node"), - paintCount: layer.paintCount || "\u2014", - memory: Number.bytesToString(layer.memory || 0) - }; - }, - - get data() - { - return this._data; - }, - - set data(data) - { - Object.keys(data).forEach(function(columnIdentifier) { - if (this._data[columnIdentifier] === data[columnIdentifier]) - return; - - this._data[columnIdentifier] = data[columnIdentifier]; - if (this._cellsWereCreated) - this._updateCell(columnIdentifier); - }, this); - }, - - // Private - - _makeOutlet: function(name, element) - { - return this._outlets[name] = element; - }, - - _makeNameCell: function() - { - var fragment = document.createDocumentFragment(); - - fragment.appendChild(document.createElement("img")).className = "icon"; - - var label = this._makeOutlet("label", fragment.appendChild(document.createElement("div"))); - label.className = "label"; - - var nameLabel = this._makeOutlet("nameLabel", label.appendChild(document.createElement("span"))); - nameLabel.className = "name"; - - var pseudoLabel = this._makeOutlet("pseudoLabel", document.createElement("span")); - pseudoLabel.className = "pseudo-element"; - - var reflectionLabel = this._makeOutlet("reflectionLabel", document.createElement("span")); - reflectionLabel.className = "reflection"; - reflectionLabel.textContent = " \u2014 " + WebInspector.UIString("Reflection"); - - var goToButton = this._makeOutlet("goToButton", fragment.appendChild(WebInspector.createGoToArrowButton())); - goToButton.addEventListener("click", this._goToArrowWasClicked.bind(this), false); - - return fragment; - }, - - _updateCell: function(columnIdentifier) - { - var data = this._data[columnIdentifier]; - if (columnIdentifier === "name") - this._updateNameCellData(data); - else - this._outlets[columnIdentifier].textContent = data; - }, - - _updateNameCellData: function(data) - { - var layer = this._layer; - var label = this._outlets.label; - - this._outlets.nameLabel.textContent = data; - - if (layer.pseudoElement) - label.appendChild(this._outlets.pseudoLabel).textContent = "::" + layer.pseudoElement; - else if (this._outlets.pseudoLabel.parentNode) - label.removeChild(this._outlets.pseudoLabel); - - if (layer.isReflection) - label.appendChild(this._outlets.reflectionLabel); - else if (this._outlets.reflectionLabel.parentNode) - label.removeChild(this._outlets.reflectionLabel); - - if (WebInspector.domTreeManager.nodeForId(layer.nodeId)) - label.parentNode.appendChild(this._outlets.goToButton); - else if (this._outlets.goToButton.parentNode) - label.parentNode.removeChild(this._outlets.goToButton); - - var element = this.element; - if (layer.isReflection) - element.classList.add("reflection"); - else if (layer.pseudoElement) - element.classList.add("pseudo-element"); - }, - - _goToArrowWasClicked: function() - { - var domNode = WebInspector.domTreeManager.nodeForId(this._layer.nodeId); - WebInspector.resourceSidebarPanel.showMainFrameDOMTree(domNode, true); - } -}; - -WebInspector.LayerTreeDataGridNode.prototype.__proto__ = WebInspector.DataGridNode.prototype; diff --git a/Source/WebInspectorUI/UserInterface/LayerTreeManager.js b/Source/WebInspectorUI/UserInterface/LayerTreeManager.js deleted file mode 100644 index ac22f4e7f..000000000 --- a/Source/WebInspectorUI/UserInterface/LayerTreeManager.js +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.LayerTreeManager = function() { - WebInspector.Object.call(this); - - this._supported = !!window.LayerTreeAgent; - - if (this._supported) - LayerTreeAgent.enable(); -}; - -WebInspector.LayerTreeManager.Event = { - LayerTreeDidChange: "layer-tree-did-change" -}; - -WebInspector.LayerTreeManager.prototype = { - constructor: WebInspector.LayerTreeManager, - - // Public - - get supported() - { - return this._supported; - }, - - layerTreeMutations: function(previousLayers, newLayers) - { - console.assert(this.supported); - - if (isEmptyObject(previousLayers)) { - return { - preserved: [], - additions: newLayers, - removals: [] - }; - } - - function nodeIdForLayer(layer) - { - return layer.isGeneratedContent ? layer.pseudoElementId : layer.nodeId; - } - - var layerIdsInPreviousLayers = []; - var nodeIdsInPreviousLayers = []; - var nodeIdsForReflectionsInPreviousLayers = []; - - previousLayers.forEach(function(layer) { - layerIdsInPreviousLayers.push(layer.layerId); - - var nodeId = nodeIdForLayer(layer); - if (!nodeId) - return; - - if (layer.isReflection) - nodeIdsForReflectionsInPreviousLayers.push(nodeId); - else - nodeIdsInPreviousLayers.push(nodeId); - }); - - var preserved = []; - var additions = []; - - var layerIdsInNewLayers = []; - var nodeIdsInNewLayers = []; - var nodeIdsForReflectionsInNewLayers = []; - - newLayers.forEach(function(layer) { - layerIdsInNewLayers.push(layer.layerId); - - var existed = layerIdsInPreviousLayers.contains(layer.layerId); - - var nodeId = nodeIdForLayer(layer); - if (!nodeId) - return; - - if (layer.isReflection) { - nodeIdsForReflectionsInNewLayers.push(nodeId); - existed = existed || nodeIdsForReflectionsInPreviousLayers.contains(nodeId); - } else { - nodeIdsInNewLayers.push(nodeId); - existed = existed || nodeIdsInPreviousLayers.contains(nodeId); - } - - if (existed) - preserved.push(layer); - else - additions.push(layer); - }); - - var removals = previousLayers.filter(function(layer) { - var nodeId = nodeIdForLayer(layer); - - if (layer.isReflection) - return !nodeIdsForReflectionsInNewLayers.contains(nodeId); - else - return !nodeIdsInNewLayers.contains(nodeId) && !layerIdsInNewLayers.contains(layer.layerId); - }); - - return { - preserved: preserved, - additions: additions, - removals: removals - }; - }, - - layersForNode: function(node, callback) - { - console.assert(this.supported); - - LayerTreeAgent.layersForNode(node.id, function(error, layers) { - if (error || isEmptyObject(layers)) { - callback(null, []); - return; - } - - var firstLayer = layers[0]; - var layerForNode = firstLayer.nodeId === node.id && !firstLayer.isGeneratedContent ? layers.shift() : null; - callback(layerForNode, layers); - }.bind(this)); - }, - - reasonsForCompositingLayer: function(layer, callback) - { - console.assert(this.supported); - - LayerTreeAgent.reasonsForCompositingLayer(layer.layerId, function(error, reasons) { - callback(error ? 0 : reasons); - }); - }, - - layerTreeDidChange: function() - { - this.dispatchEventToListeners(WebInspector.LayerTreeManager.Event.LayerTreeDidChange); - } -}; - -WebInspector.LayerTreeManager.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/LayerTreeObserver.js b/Source/WebInspectorUI/UserInterface/LayerTreeObserver.js deleted file mode 100644 index ddbb9d359..000000000 --- a/Source/WebInspectorUI/UserInterface/LayerTreeObserver.js +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.LayerTreeObserver = function() -{ - WebInspector.Object.call(this); -}; - -WebInspector.LayerTreeObserver.prototype = { - constructor: WebInspector.LayerTreeObserver, - - // Events defined by the "LayerTree" domain. - - layerTreeDidChange: function() - { - if (WebInspector.layerTreeManager.supported) - WebInspector.layerTreeManager.layerTreeDidChange(); - } -}; - -WebInspector.LayerTreeObserver.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/LayerTreeSidebarPanel.css b/Source/WebInspectorUI/UserInterface/LayerTreeSidebarPanel.css deleted file mode 100644 index 40fd4ca43..000000000 --- a/Source/WebInspectorUI/UserInterface/LayerTreeSidebarPanel.css +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - - -/* We use an internal container to act as a vertical stack. */ - -.layer-tree.panel .box-container { - height: 100%; - /* Let it stack its content as vertical boxes. */ - display: -webkit-flex; - -webkit-flex-direction: column; -} - -/* Hide the collapsed arrow from sections. */ - -.layer-tree.panel .details-section > .header::before { - /* Don't show the collpased arrow. */ - display: none; -} - -.layer-tree.panel .details-section > .header { - /* Add a little padding since there's no arrow to show. */ - padding-left: 4px; - /* Turn off mouse events so we can't click to toggle section. */ - pointer-events: none; -} - -.layer-tree.panel .details-section > .header > label { - /* Always show the options box. */ - display: block !important; - /* Turn on events just for the element that we'll use to load the image resource + // so that we can query its intrinsic size. + var image = new Image; + image.addEventListener("load", imageDidLoad.bind(this), false); + + // Set the image source using an object URL once we've obtained its data. + this.requestContent().then(function(content) { + objectURL = image.src = content.sourceCode.createObjectURL(); + }); + } + + requestContent() + { + if (this._finished) + return super.requestContent(); + + if (this._failed) + return Promise.resolve({error: WebInspector.UIString("An error occurred trying to load the resource.")}); + + if (!this._finishThenRequestContentPromise) { + this._finishThenRequestContentPromise = new Promise((resolve, reject) => { + this.addEventListener(WebInspector.Resource.Event.LoadingDidFinish, resolve); + this.addEventListener(WebInspector.Resource.Event.LoadingDidFail, reject); + }).then(WebInspector.SourceCode.prototype.requestContent.bind(this)); + } + + return this._finishThenRequestContentPromise; + } + + associateWithScript(script) + { + if (!this._scripts) + this._scripts = []; + + this._scripts.push(script); + + if (this._type === WebInspector.Resource.Type.Other || this._type === WebInspector.Resource.Type.XHR) { + let oldType = this._type; + this._type = WebInspector.Resource.Type.Script; + this.dispatchEventToListeners(WebInspector.Resource.Event.TypeDidChange, {oldType}); + } + } + + saveIdentityToCookie(cookie) + { + cookie[WebInspector.Resource.URLCookieKey] = this.url.hash; + cookie[WebInspector.Resource.MainResourceCookieKey] = this.isMainResource(); + } + + generateCURLCommand() + { + function escapeStringPosix(str) { + function escapeCharacter(x) { + let code = x.charCodeAt(0); + let hex = code.toString(16); + if (code < 256) + return "\\x" + hex.padStart(2, "0"); + return "\\u" + hex.padStart(4, "0"); + } + + if (/[^\x20-\x7E]|'/.test(str)) { + // Use ANSI-C quoting syntax. + return "$'" + str.replace(/\\/g, "\\\\") + .replace(/'/g, "\\'") + .replace(/\n/g, "\\n") + .replace(/\r/g, "\\r") + .replace(/[^\x20-\x7E]/g, escapeCharacter) + "'"; + } else { + // Use single quote syntax. + return `'${str}'`; + } + } + + let command = ["curl " + escapeStringPosix(this.url).replace(/[[{}\]]/g, "\\$&")]; + command.push(`-X${this.requestMethod}`); + + for (let key in this.requestHeaders) + command.push("-H " + escapeStringPosix(`${key}: ${this.requestHeaders[key]}`)); + + if (this.requestDataContentType && this.requestMethod !== "GET" && this.requestData) { + if (this.requestDataContentType.match(/^application\/x-www-form-urlencoded\s*(;.*)?$/i)) + command.push("--data " + escapeStringPosix(this.requestData)); + else + command.push("--data-binary " + escapeStringPosix(this.requestData)); + } + + let curlCommand = command.join(" \\\n"); + InspectorFrontendHost.copyText(curlCommand); + return curlCommand; + } +}; + +WebInspector.Resource.TypeIdentifier = "resource"; +WebInspector.Resource.URLCookieKey = "resource-url"; +WebInspector.Resource.MainResourceCookieKey = "resource-is-main-resource"; + +WebInspector.Resource.Event = { + URLDidChange: "resource-url-did-change", + MIMETypeDidChange: "resource-mime-type-did-change", + TypeDidChange: "resource-type-did-change", + RequestHeadersDidChange: "resource-request-headers-did-change", + ResponseReceived: "resource-response-received", + LoadingDidFinish: "resource-loading-did-finish", + LoadingDidFail: "resource-loading-did-fail", + TimestampsDidChange: "resource-timestamps-did-change", + SizeDidChange: "resource-size-did-change", + TransferSizeDidChange: "resource-transfer-size-did-change", + CacheStatusDidChange: "resource-cached-did-change", + InitiatedResourcesDidChange: "resource-initiated-resources-did-change", +}; + +// Keep these in sync with the "ResourceType" enum defined by the "Page" domain. +WebInspector.Resource.Type = { + Document: "resource-type-document", + Stylesheet: "resource-type-stylesheet", + Image: "resource-type-image", + Font: "resource-type-font", + Script: "resource-type-script", + XHR: "resource-type-xhr", + Fetch: "resource-type-fetch", + WebSocket: "resource-type-websocket", + Other: "resource-type-other" +}; + +// This MIME Type map is private, use WebInspector.Resource.typeFromMIMEType(). +WebInspector.Resource._mimeTypeMap = { + "text/html": WebInspector.Resource.Type.Document, + "text/xml": WebInspector.Resource.Type.Document, + "text/plain": WebInspector.Resource.Type.Document, + "application/xhtml+xml": WebInspector.Resource.Type.Document, + "image/svg+xml": WebInspector.Resource.Type.Document, + + "text/css": WebInspector.Resource.Type.Stylesheet, + "text/xsl": WebInspector.Resource.Type.Stylesheet, + "text/x-less": WebInspector.Resource.Type.Stylesheet, + "text/x-sass": WebInspector.Resource.Type.Stylesheet, + "text/x-scss": WebInspector.Resource.Type.Stylesheet, + + "application/pdf": WebInspector.Resource.Type.Image, + + "application/x-font-type1": WebInspector.Resource.Type.Font, + "application/x-font-ttf": WebInspector.Resource.Type.Font, + "application/x-font-woff": WebInspector.Resource.Type.Font, + "application/x-truetype-font": WebInspector.Resource.Type.Font, + + "text/javascript": WebInspector.Resource.Type.Script, + "text/ecmascript": WebInspector.Resource.Type.Script, + "application/javascript": WebInspector.Resource.Type.Script, + "application/ecmascript": WebInspector.Resource.Type.Script, + "application/x-javascript": WebInspector.Resource.Type.Script, + "application/json": WebInspector.Resource.Type.Script, + "application/x-json": WebInspector.Resource.Type.Script, + "text/x-javascript": WebInspector.Resource.Type.Script, + "text/x-json": WebInspector.Resource.Type.Script, + "text/javascript1.1": WebInspector.Resource.Type.Script, + "text/javascript1.2": WebInspector.Resource.Type.Script, + "text/javascript1.3": WebInspector.Resource.Type.Script, + "text/jscript": WebInspector.Resource.Type.Script, + "text/livescript": WebInspector.Resource.Type.Script, + "text/x-livescript": WebInspector.Resource.Type.Script, + "text/typescript": WebInspector.Resource.Type.Script, + "text/x-clojure": WebInspector.Resource.Type.Script, + "text/x-coffeescript": WebInspector.Resource.Type.Script +}; diff --git a/Source/WebInspectorUI/UserInterface/Models/ResourceCollection.js b/Source/WebInspectorUI/UserInterface/Models/ResourceCollection.js new file mode 100644 index 000000000..bd38ad2f5 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Models/ResourceCollection.js @@ -0,0 +1,199 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * Copyright (C) 2016 Devin Rousso . All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.ResourceCollection = class ResourceCollection extends WebInspector.Collection +{ + constructor(resourceType) + { + super(WebInspector.ResourceCollection.verifierForType(resourceType)); + + this._resourceType = resourceType || null; + this._resourceURLMap = new Map; + this._resourcesTypeMap = new Map; + } + + // Static + + static verifierForType(type) { + switch (type) { + case WebInspector.Resource.Type.Document: + return WebInspector.ResourceCollection.TypeVerifier.Document; + case WebInspector.Resource.Type.Stylesheet: + return WebInspector.ResourceCollection.TypeVerifier.Stylesheet; + case WebInspector.Resource.Type.Image: + return WebInspector.ResourceCollection.TypeVerifier.Image; + case WebInspector.Resource.Type.Font: + return WebInspector.ResourceCollection.TypeVerifier.Font; + case WebInspector.Resource.Type.Script: + return WebInspector.ResourceCollection.TypeVerifier.Script; + case WebInspector.Resource.Type.XHR: + return WebInspector.ResourceCollection.TypeVerifier.XHR; + case WebInspector.Resource.Type.Fetch: + return WebInspector.ResourceCollection.TypeVerifier.Fetch; + case WebInspector.Resource.Type.WebSocket: + return WebInspector.ResourceCollection.TypeVerifier.WebSocket; + case WebInspector.Resource.Type.Other: + return WebInspector.ResourceCollection.TypeVerifier.Other; + default: + return WebInspector.Collection.TypeVerifier.Resource; + } + } + + // Public + + resourceForURL(url) + { + return this._resourceURLMap.get(url) || null; + } + + resourceCollectionForType(type) + { + if (this._resourceType) { + console.assert(type === this._resourceType); + return this; + } + + let resourcesCollectionForType = this._resourcesTypeMap.get(type); + if (!resourcesCollectionForType) { + resourcesCollectionForType = new WebInspector.ResourceCollection(type); + this._resourcesTypeMap.set(type, resourcesCollectionForType); + } + + return resourcesCollectionForType; + } + + clear() + { + super.clear(); + + this._resourceURLMap.clear(); + + if (!this._resourceType) + this._resourcesTypeMap.clear(); + } + + // Protected + + itemAdded(item) + { + this._associateWithResource(item); + } + + itemRemoved(item) + { + this._disassociateWithResource(item); + } + + itemsCleared(items) + { + const skipRemoval = true; + + for (let item of items) + this._disassociateWithResource(item, skipRemoval); + } + + // Private + + _associateWithResource(resource) + { + this._resourceURLMap.set(resource.url, resource); + + if (!this._resourceType) { + let resourcesCollectionForType = this.resourceCollectionForType(resource.type); + resourcesCollectionForType.add(resource); + } + + resource.addEventListener(WebInspector.Resource.Event.URLDidChange, this._resourceURLDidChange, this); + resource.addEventListener(WebInspector.Resource.Event.TypeDidChange, this._resourceTypeDidChange, this); + } + + _disassociateWithResource(resource, skipRemoval) + { + resource.removeEventListener(WebInspector.Resource.Event.URLDidChange, this._resourceURLDidChange, this); + resource.removeEventListener(WebInspector.Resource.Event.TypeDidChange, this._resourceTypeDidChange, this); + + if (skipRemoval) + return; + + if (!this._resourceType) { + let resourcesCollectionForType = this.resourceCollectionForType(resource.type); + resourcesCollectionForType.remove(resource); + } + + this._resourceURLMap.delete(resource.url); + } + + _resourceURLDidChange(event) + { + let resource = event.target; + console.assert(resource instanceof WebInspector.Resource); + if (!(resource instanceof WebInspector.Resource)) + return; + + let oldURL = event.data.oldURL; + console.assert(oldURL); + if (!oldURL) + return; + + this._resourceURLMap.set(resource.url, resource); + this._resourceURLMap.delete(oldURL); + } + + _resourceTypeDidChange(event) + { + let resource = event.target; + console.assert(resource instanceof WebInspector.Resource); + if (!(resource instanceof WebInspector.Resource)) + return; + + if (this._resourceType) { + console.assert(resource.type !== this._resourceType); + this.remove(resource); + return; + } + + console.assert(event.data.oldType); + + let resourcesWithNewType = this.resourceCollectionForType(resource.type); + resourcesWithNewType.add(resource); + + // It is not necessary to remove the resource from the sub-collection for the old type since + // this is handled by that sub-collection's own _resourceTypeDidChange handler (via the + // above if statement). + } +}; + +WebInspector.ResourceCollection.TypeVerifier = { + Document: (object) => WebInspector.Collection.TypeVerifier.Resource(object) && object.type === WebInspector.Resource.Type.Document, + Stylesheet: (object) => WebInspector.Collection.TypeVerifier.Resource(object) && object.type === WebInspector.Resource.Type.Stylesheet, + Image: (object) => WebInspector.Collection.TypeVerifier.Resource(object) && object.type === WebInspector.Resource.Type.Image, + Font: (object) => WebInspector.Collection.TypeVerifier.Resource(object) && object.type === WebInspector.Resource.Type.Font, + Script: (object) => WebInspector.Collection.TypeVerifier.Resource(object) && object.type === WebInspector.Resource.Type.Script, + XHR: (object) => WebInspector.Collection.TypeVerifier.Resource(object) && object.type === WebInspector.Resource.Type.XHR, + Fetch: (object) => WebInspector.Collection.TypeVerifier.Resource(object) && object.type === WebInspector.Resource.Type.Fetch, + WebSocket: (object) => WebInspector.Collection.TypeVerifier.Resource(object) && object.type === WebInspector.Resource.Type.WebSocket, + Other: (object) => WebInspector.Collection.TypeVerifier.Resource(object) && object.type === WebInspector.Resource.Type.Other, +}; diff --git a/Source/WebInspectorUI/UserInterface/Models/ResourceQueryMatch.js b/Source/WebInspectorUI/UserInterface/Models/ResourceQueryMatch.js new file mode 100644 index 000000000..0668525bc --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Models/ResourceQueryMatch.js @@ -0,0 +1,48 @@ +/* + * Copyright (C) 2016 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.ResourceQueryMatch = class QueryMatch extends WebInspector.Object +{ + constructor(type, index, queryIndex) + { + super(); + + this._type = type; + this._index = index; + this._queryIndex = queryIndex; + this._rank = undefined; + } + + // Public + + get type() { return this._type; } + get index() { return this._index; } + get queryIndex() { return this._queryIndex; } +}; + +WebInspector.ResourceQueryMatch.Type = { + Normal: Symbol("normal"), + Special: Symbol("special") +}; diff --git a/Source/WebInspectorUI/UserInterface/Models/ResourceQueryResult.js b/Source/WebInspectorUI/UserInterface/Models/ResourceQueryResult.js new file mode 100644 index 000000000..c2bf09d37 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Models/ResourceQueryResult.js @@ -0,0 +1,149 @@ +/* + * Copyright (C) 2016 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.ResourceQueryResult = class QueryResult extends WebInspector.Object +{ + constructor(resource, matches, cookie) + { + console.assert(matches.length, "Query matches list can't be empty."); + + super(); + + this._resource = resource; + this._matches = matches; + this._cookie = cookie || null; + } + + // Public + + get resource() { return this._resource; } + get cookie() { return this._cookie; } + + get rank() + { + if (this._rank === undefined) + this._calculateRank(); + + return this._rank; + } + + get matchingTextRanges() + { + if (!this._matchingTextRanges) + this._matchingTextRanges = this._createMatchingTextRanges(); + + return this._matchingTextRanges; + } + + // Private + + _calculateRank() + { + const normalWeight = 10; + const consecutiveWeight = 5; + const specialMultiplier = 5; + + function getMultiplier(match) { + if (match.type === WebInspector.ResourceQueryMatch.Type.Special) + return specialMultiplier; + + return 1; + } + + this._rank = 0; + + let previousMatch = null; + let consecutiveMatchStart = null; + for (let match of this._matches) { + this._rank += normalWeight * getMultiplier(match); + + let consecutive = previousMatch && previousMatch.index === match.index - 1; + if (consecutive) { + if (!consecutiveMatchStart) + consecutiveMatchStart = previousMatch; + + // If the first match in this consecutive series was a special character, give a + // bonus (more likely to match a specific word in the text). Otherwise, multiply + // by the current length of the consecutive sequence (gives priority to fewer + // longer sequences instead of more short sequences). + this._rank += consecutiveWeight * getMultiplier(consecutiveMatchStart) * (match.index - consecutiveMatchStart.index); + } else if (consecutiveMatchStart) + consecutiveMatchStart = null; + + previousMatch = match; + + // The match index is deducted from the total rank, so matches that occur closer to + // the beginning of the string are ranked higher. Increase the amount subtracted if + // the match is special, so as to favor matches towards the beginning of the string. + if (!consecutive) + this._rank -= match.index * getMultiplier(match); + } + } + + _createMatchingTextRanges() + { + if (!this._matches.length) + return []; + + let ranges = []; + let startIndex = this._matches[0].index; + let endIndex = startIndex; + for (let i = 1; i < this._matches.length; ++i) { + let match = this._matches[i]; + + // Increment endIndex for consecutive match. + if (match.index === endIndex + 1) { + endIndex++; + continue; + } + + // Begin a new range when a gap between this match and the previous match is found. + ranges.push(new WebInspector.TextRange(0, startIndex, 0, endIndex + 1)); + startIndex = match.index; + endIndex = startIndex; + } + + ranges.push(new WebInspector.TextRange(0, startIndex, 0, endIndex + 1)); + return ranges; + } + + // Testing + + __test_createMatchesMask() + { + let filename = this._resource.displayName; + let lastIndex = -1; + let result = ""; + + for (let match of this._matches) { + let gap = " ".repeat(match.index - lastIndex - 1); + result += gap; + result += filename[match.index]; + lastIndex = match.index; + } + + return result; + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Models/ResourceTimelineRecord.js b/Source/WebInspectorUI/UserInterface/Models/ResourceTimelineRecord.js new file mode 100644 index 000000000..03a090971 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Models/ResourceTimelineRecord.js @@ -0,0 +1,74 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.ResourceTimelineRecord = class ResourceTimelineRecord extends WebInspector.TimelineRecord +{ + constructor(resource) + { + super(WebInspector.TimelineRecord.Type.Network); + + this._resource = resource; + this._resource.addEventListener(WebInspector.Resource.Event.TimestampsDidChange, this._dispatchUpdatedEvent, this); + } + + // Public + + get resource() + { + return this._resource; + } + + get updatesDynamically() + { + return true; + } + + get usesActiveStartTime() + { + return true; + } + + get startTime() + { + return this._resource.timingData.startTime; + } + + get activeStartTime() + { + return this._resource.timingData.responseStart; + } + + get endTime() + { + return this._resource.timingData.responseEnd; + } + + // Private + + _dispatchUpdatedEvent() + { + this.dispatchEventToListeners(WebInspector.TimelineRecord.Event.Updated); + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Models/ResourceTimingData.js b/Source/WebInspectorUI/UserInterface/Models/ResourceTimingData.js new file mode 100644 index 000000000..2affdf73a --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Models/ResourceTimingData.js @@ -0,0 +1,107 @@ +/* + * Copyright (C) 2016 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.ResourceTimingData = class ResourceTimingData extends WebInspector.Object +{ + constructor(resource, data) + { + super(); + + data = data || {}; + + console.assert(isNaN(data.domainLookupStart) === isNaN(data.domainLookupEnd)); + console.assert(isNaN(data.connectStart) === isNaN(data.connectEnd)); + + this._resource = resource; + + this._startTime = data.startTime || NaN; + this._domainLookupStart = data.domainLookupStart || NaN; + this._domainLookupEnd = data.domainLookupEnd || NaN; + this._connectStart = data.connectStart || NaN; + this._connectEnd = data.connectEnd || NaN; + this._secureConnectionStart = data.secureConnectionStart || NaN; + this._requestStart = data.requestStart || NaN; + this._responseStart = data.responseStart || NaN; + this._responseEnd = data.responseEnd || NaN; + + if (this._domainLookupStart >= this._domainLookupEnd) + this._domainLookupStart = this._domainLookupEnd = NaN; + + if (this._connectStart >= this._connectEnd) + this._connectStart = this._connectEnd = NaN; + } + + // Static + + static fromPayload(payload, resource) + { + payload = payload || {}; + + // COMPATIBILITY (iOS 10): Resource Timing data was incomplete and incorrect. Do not use it. + // iOS 7 sent a requestTime and iOS 8-9.3 sent a navigationStart time. + if (typeof payload.requestTime === "number" || typeof payload.navigationStart === "number") + payload = {}; + + function offsetToTimestamp(offset) { + return offset > 0 ? payload.startTime + offset / 1000 : NaN; + } + + let data = { + startTime: payload.startTime, + domainLookupStart: offsetToTimestamp(payload.domainLookupStart), + domainLookupEnd: offsetToTimestamp(payload.domainLookupEnd), + connectStart: offsetToTimestamp(payload.connectStart), + connectEnd: offsetToTimestamp(payload.connectEnd), + secureConnectionStart: offsetToTimestamp(payload.secureConnectionStart), + requestStart: offsetToTimestamp(payload.requestStart), + responseStart: offsetToTimestamp(payload.responseStart), + responseEnd: offsetToTimestamp(payload.responseEnd) + }; + + // COMPATIBILITY (iOS 8): connectStart is zero if a secure connection is used. + if (isNaN(data.connectStart) && !isNaN(data.secureConnectionStart)) + data.connectStart = data.secureConnectionStart; + + return new WebInspector.ResourceTimingData(resource, data); + } + + // Public + + get startTime() { return this._startTime || this._resource.requestSentTimestamp; } + get domainLookupStart() { return this._domainLookupStart; } + get domainLookupEnd() { return this._domainLookupEnd; } + get connectStart() { return this._connectStart; } + get connectEnd() { return this._connectEnd; } + get secureConnectionStart() { return this._secureConnectionStart; } + get requestStart() { return this._requestStart || this._resource.requestSentTimestamp; } + get responseStart() { return this._responseStart || this._resource.responseReceivedTimestamp; } + get responseEnd() { return this._responseEnd || this._resource.finishedOrFailedTimestamp; } + + markResponseEndTime(responseEnd) + { + console.assert(typeof responseEnd === "number"); + this._responseEnd = responseEnd; + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Models/Revision.js b/Source/WebInspectorUI/UserInterface/Models/Revision.js new file mode 100644 index 000000000..83c51a7a3 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Models/Revision.js @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.Revision = class Revision extends WebInspector.Object +{ + // Public + + apply() + { + // Implemented by subclasses. + console.error("Needs to be implemented by a subclass."); + } + + revert() + { + // Implemented by subclasses. + console.error("Needs to be implemented by a subclass."); + } + + copy() + { + // Override by subclasses. + return this; + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Models/ScopeChainNode.js b/Source/WebInspectorUI/UserInterface/Models/ScopeChainNode.js new file mode 100644 index 000000000..8e3811e80 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Models/ScopeChainNode.js @@ -0,0 +1,79 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.ScopeChainNode = class ScopeChainNode extends WebInspector.Object +{ + constructor(type, objects, name, location, empty) + { + super(); + + console.assert(typeof type === "string"); + console.assert(objects.every((x) => x instanceof WebInspector.RemoteObject)); + + if (type in WebInspector.ScopeChainNode.Type) + type = WebInspector.ScopeChainNode.Type[type]; + + this._type = type || null; + this._objects = objects || []; + this._name = name || ""; + this._location = location || null; + this._empty = empty || false; + } + + // Public + + get type() { return this._type; } + get objects() { return this._objects; } + get name() { return this._name; } + get location() { return this._location; } + get empty() { return this._empty; } + + get hash() + { + if (this._hash) + return this._hash; + + this._hash = this._name; + if (this._location) + this._hash += `:${this._location.scriptId}:${this._location.lineNumber}:${this._location.columnNumber}`; + return this._hash; + } + + convertToLocalScope() + { + this._type = WebInspector.ScopeChainNode.Type.Local; + } +}; + +WebInspector.ScopeChainNode.Type = { + Local: "scope-chain-type-local", + Global: "scope-chain-type-global", + GlobalLexicalEnvironment: "scope-chain-type-global-lexical-environment", + With: "scope-chain-type-with", + Closure: "scope-chain-type-closure", + Catch: "scope-chain-type-catch", + FunctionName: "scope-chain-type-function-name", + Block: "scope-chain-type-block", +}; diff --git a/Source/WebInspectorUI/UserInterface/Models/Script.js b/Source/WebInspectorUI/UserInterface/Models/Script.js new file mode 100644 index 000000000..22626ce47 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Models/Script.js @@ -0,0 +1,303 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.Script = class Script extends WebInspector.SourceCode +{ + constructor(target, id, range, url, sourceType, injected, sourceURL, sourceMapURL) + { + super(); + + console.assert(id); + console.assert(target instanceof WebInspector.Target); + console.assert(range instanceof WebInspector.TextRange); + + this._target = target; + this._id = id || null; + this._range = range || null; + this._url = url || null; + this._sourceType = sourceType || WebInspector.Script.SourceType.Program; + this._sourceURL = sourceURL || null; + this._sourceMappingURL = sourceMapURL || null; + this._injected = injected || false; + this._dynamicallyAddedScriptElement = false; + this._scriptSyntaxTree = null; + + this._resource = this._resolveResource(); + + // If this Script was a dynamically added "); +})(); diff --git a/Source/WebInspectorUI/UserInterface/Protocol/LoggingProtocolTracer.js b/Source/WebInspectorUI/UserInterface/Protocol/LoggingProtocolTracer.js new file mode 100644 index 000000000..c2c0fa6cc --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Protocol/LoggingProtocolTracer.js @@ -0,0 +1,120 @@ +/* + * Copyright (C) 2015, 2016 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.LoggingProtocolTracer = class LoggingProtocolTracer extends WebInspector.ProtocolTracer +{ + constructor() + { + super(); + + this._dumpMessagesToConsole = false; + this._dumpTimingDataToConsole = false; + this._logToConsole = window.InspectorTest ? InspectorFrontendHost.unbufferedLog.bind(InspectorFrontendHost) : console.log.bind(console); + } + + // Public + + set dumpMessagesToConsole(value) + { + this._dumpMessagesToConsole = !!value; + } + + get dumpMessagesToConsole() + { + return this._dumpMessagesToConsole; + } + + set dumpTimingDataToConsole(value) + { + this._dumpTimingDataToConsole = !!value; + } + + get dumpTimingDataToConsole() + { + return this._dumpTimingDataToConsole; + } + + logFrontendException(message, exception) + { + this._processEntry({type: "exception", message, exception}); + } + + logProtocolError(message, error) + { + this._processEntry({type: "error", message, error}); + } + + logFrontendRequest(message) + { + this._processEntry({type: "request", message}); + } + + logWillHandleResponse(message) + { + let entry = {type: "response", message}; + this._processEntry(entry); + } + + logDidHandleResponse(message, timings = null) + { + let entry = {type: "response", message}; + if (timings) + entry.timings = Object.shallowCopy(timings); + + this._processEntry(entry); + } + + logWillHandleEvent(message) + { + let entry = {type: "event", message}; + this._processEntry(entry); + } + + logDidHandleEvent(message, timings = null) + { + let entry = {type: "event", message}; + if (timings) + entry.timings = Object.shallowCopy(timings); + + this._processEntry(entry); + } + + _processEntry(entry) + { + if (this._dumpTimingDataToConsole && entry.timings) { + if (entry.timings.rtt && entry.timings.dispatch) + this._logToConsole(`time-stats: Handling: ${entry.timings.dispatch || NaN}ms; RTT: ${entry.timings.rtt}ms`); + else if (entry.timings.dispatch) + this._logToConsole(`time-stats: Handling: ${entry.timings.dispatch || NaN}ms`); + } else if (this._dumpMessagesToConsole && !entry.timings) { + this._logToConsole(`${entry.type}: ${JSON.stringify(entry.message)}`); + if (entry.exception) { + this._logToConsole(entry.exception); + if (entry.exception.stack) + this._logToConsole(entry.exception.stack); + } + } + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Protocol/MainTarget.js b/Source/WebInspectorUI/UserInterface/Protocol/MainTarget.js new file mode 100644 index 000000000..9dc969fe6 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Protocol/MainTarget.js @@ -0,0 +1,56 @@ +/* + * Copyright (C) 2016 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.MainTarget = class MainTarget extends WebInspector.Target +{ + constructor(connection) + { + super("main", "", WebInspector.Target.Type.Main, InspectorBackend.mainConnection); + + let displayName = WebInspector.debuggableType === WebInspector.DebuggableType.Web ? WebInspector.UIString("Main Frame") : this.displayName; + this._executionContext = new WebInspector.ExecutionContext(this, WebInspector.RuntimeManager.TopLevelContextExecutionIdentifier, displayName, true, null); + } + + // Protected (Target) + + get displayName() + { + switch (WebInspector.debuggableType) { + case WebInspector.DebuggableType.Web: + return WebInspector.UIString("Page"); + case WebInspector.DebuggableType.JavaScript: + return WebInspector.UIString("JavaScript Context"); + default: + console.error("Unexpected debuggable type: ", WebInspector.debuggableType); + return WebInspector.UIString("Main"); + } + } + + get mainResource() + { + let mainFrame = WebInspector.frameResourceManager.mainFrame; + return mainFrame ? mainFrame.mainResource : null; + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Protocol/MemoryObserver.js b/Source/WebInspectorUI/UserInterface/Protocol/MemoryObserver.js new file mode 100644 index 000000000..1b0b475cc --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Protocol/MemoryObserver.js @@ -0,0 +1,49 @@ +/* + * Copyright (C) 2016 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.MemoryObserver = class MemoryObserver +{ + // Events defined by the "Memory" domain. + + memoryPressure(timestamp, severity) + { + WebInspector.memoryManager.memoryPressure(timestamp, severity); + } + + trackingStart(timestamp) + { + WebInspector.timelineManager.memoryTrackingStart(timestamp); + } + + trackingUpdate(event) + { + WebInspector.timelineManager.memoryTrackingUpdate(event); + } + + trackingComplete() + { + WebInspector.timelineManager.memoryTrackingComplete(); + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Protocol/MessageDispatcher.js b/Source/WebInspectorUI/UserInterface/Protocol/MessageDispatcher.js new file mode 100644 index 000000000..807f7cfd3 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Protocol/MessageDispatcher.js @@ -0,0 +1,78 @@ +/* + * Copyright (C) 2013, 2015 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector._messagesToDispatch = []; + +WebInspector.dispatchNextQueuedMessageFromBackend = function() +{ + const startCount = WebInspector._messagesToDispatch.length; + const startTimestamp = timestamp(); + const timeLimitPerRunLoop = 10; // milliseconds + + let i = 0; + for (; i < WebInspector._messagesToDispatch.length; ++i) { + // Defer remaining messages if we have taken too long. In practice, single + // messages like Page.getResourceContent blow through the time budget. + if (timestamp() - startTimestamp > timeLimitPerRunLoop) + break; + + InspectorBackend.dispatch(WebInspector._messagesToDispatch[i]); + } + + if (i === WebInspector._messagesToDispatch.length) { + WebInspector._messagesToDispatch = []; + WebInspector._dispatchTimeout = null; + } else { + WebInspector._messagesToDispatch = WebInspector._messagesToDispatch.slice(i); + WebInspector._dispatchTimeout = setTimeout(WebInspector.dispatchNextQueuedMessageFromBackend, 0); + } + + if (InspectorBackend.dumpInspectorTimeStats) { + let messageDuration = (timestamp() - startTimestamp).toFixed(3); + let dispatchedCount = startCount - WebInspector._messagesToDispatch.length; + let remainingCount = WebInspector._messagesToDispatch.length; + console.log(`time-stats: --- RunLoop duration: ${messageDuration}ms; dispatched: ${dispatchedCount}; remaining: ${remainingCount}`); + } +}; + +WebInspector.dispatchMessageFromBackend = function(message) +{ + // Enforce asynchronous interaction between the backend and the frontend by queueing messages. + // The messages are dequeued on a zero delay timeout. + + this._messagesToDispatch.push(message); + + // If something has gone wrong and the uncaught exception sheet is showing, + // then don't try to dispatch more messages. Dispatching causes spurious uncaught + // exceptions and cause the sheet to overflow with hundreds of logged exceptions. + if (window.__uncaughtExceptions && window.__uncaughtExceptions.length) + return; + + if (this._dispatchTimeout) + return; + + this._dispatchTimeout = setTimeout(this.dispatchNextQueuedMessageFromBackend, 0); +}; diff --git a/Source/WebInspectorUI/UserInterface/Protocol/NetworkObserver.js b/Source/WebInspectorUI/UserInterface/Protocol/NetworkObserver.js new file mode 100644 index 000000000..70f234682 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Protocol/NetworkObserver.js @@ -0,0 +1,99 @@ +/* + * Copyright (C) 2013, 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.NetworkObserver = class NetworkObserver +{ + // Events defined by the "Network" domain. + + requestWillBeSent(requestId, frameId, loaderId, documentURL, request, timestamp, initiator, redirectResponse, type, targetId) + { + WebInspector.frameResourceManager.resourceRequestWillBeSent(requestId, frameId, loaderId, request, type, redirectResponse, timestamp, initiator, targetId); + } + + requestServedFromCache(requestId) + { + WebInspector.frameResourceManager.markResourceRequestAsServedFromMemoryCache(requestId); + } + + responseReceived(requestId, frameId, loaderId, timestamp, type, response) + { + WebInspector.frameResourceManager.resourceRequestDidReceiveResponse(requestId, frameId, loaderId, type, response, timestamp); + } + + dataReceived(requestId, timestamp, dataLength, encodedDataLength) + { + WebInspector.frameResourceManager.resourceRequestDidReceiveData(requestId, dataLength, encodedDataLength, timestamp); + } + + loadingFinished(requestId, timestamp, sourceMapURL) + { + WebInspector.frameResourceManager.resourceRequestDidFinishLoading(requestId, timestamp, sourceMapURL); + } + + loadingFailed(requestId, timestamp, errorText, canceled) + { + WebInspector.frameResourceManager.resourceRequestDidFailLoading(requestId, canceled, timestamp); + } + + requestServedFromMemoryCache(requestId, frameId, loaderId, documentURL, timestamp, initiator, resource) + { + WebInspector.frameResourceManager.resourceRequestWasServedFromMemoryCache(requestId, frameId, loaderId, resource, timestamp, initiator); + } + + webSocketWillSendHandshakeRequest(requestId, timestamp, request) + { + // FIXME: Not implemented. + } + + webSocketHandshakeResponseReceived(requestId, timestamp, response) + { + // FIXME: Not implemented. + } + + webSocketCreated(requestId, url) + { + // FIXME: Not implemented. + } + + webSocketClosed(requestId, timestamp) + { + // FIXME: Not implemented. + } + + webSocketFrameReceived(requestId, timestamp, response) + { + // FIXME: Not implemented. + } + + webSocketFrameError(requestId, timestamp, errorMessage) + { + // FIXME: Not implemented. + } + + webSocketFrameSent(requestId, timestamp, response) + { + // FIXME: Not implemented. + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Protocol/PageObserver.js b/Source/WebInspectorUI/UserInterface/Protocol/PageObserver.js new file mode 100644 index 000000000..c136e5367 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Protocol/PageObserver.js @@ -0,0 +1,84 @@ +/* + * Copyright (C) 2013, 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.PageObserver = class PageObserver +{ + // Events defined by the "Page" domain. + + domContentEventFired(timestamp) + { + WebInspector.timelineManager.pageDOMContentLoadedEventFired(timestamp); + } + + loadEventFired(timestamp) + { + WebInspector.timelineManager.pageLoadEventFired(timestamp); + } + + frameNavigated(frame, loaderId) + { + WebInspector.frameResourceManager.frameDidNavigate(frame, loaderId); + } + + frameDetached(frameId) + { + WebInspector.frameResourceManager.frameDidDetach(frameId); + } + + frameStartedLoading(frameId) + { + // Not handled yet. + } + + frameStoppedLoading(frameId) + { + // Not handled yet. + } + + frameScheduledNavigation(frameId, delay) + { + // Not handled yet. + } + + frameClearedScheduledNavigation(frameId) + { + // Not handled yet. + } + + javascriptDialogOpening(message) + { + // COMPATIBILITY (iOS 10): Page.javascriptDialogOpening was removed after iOS 10. + } + + javascriptDialogClosed() + { + // COMPATIBILITY (iOS 10): Page.javascriptDialogClosed was removed after iOS 10. + } + + scriptsEnabled(enabled) + { + // COMPATIBILITY (iOS 10): Page.scriptsEnabled was removed after iOS 10. + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Protocol/ProtocolTracer.js b/Source/WebInspectorUI/UserInterface/Protocol/ProtocolTracer.js new file mode 100644 index 000000000..c186bd278 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Protocol/ProtocolTracer.js @@ -0,0 +1,74 @@ +/* + * Copyright (C) 2015, 2016 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.ProtocolTracer = class ProtocolTracer extends WebInspector.Object +{ + // Public + + logStarted() + { + // To be overridden by subclasses. + } + + logFrontendException(message, exception) + { + // To be overridden by subclasses. + } + + logProtocolError(message, error) + { + // To be overridden by subclasses. + } + + logFrontendRequest(message) + { + // To be overridden by subclasses. + } + + logWillHandleResponse(message) + { + // To be overridden by subclasses. + } + + logDidHandleResponse(message, timings = null) + { + // To be overridden by subclasses. + } + + logWillHandleEvent(message) + { + // To be overridden by subclasses. + } + + logDidHandleEvent(message, timings = null) + { + // To be overridden by subclasses. + } + + logFinished() + { + // To be overridden by subclasses. + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Protocol/RemoteObject.js b/Source/WebInspectorUI/UserInterface/Protocol/RemoteObject.js new file mode 100644 index 000000000..f4c99fbec --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Protocol/RemoteObject.js @@ -0,0 +1,679 @@ +/* + * Copyright (C) 2009 Google Inc. All rights reserved. + * Copyright (C) 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.RemoteObject = class RemoteObject +{ + constructor(target, objectId, type, subtype, value, description, size, classPrototype, className, preview) + { + console.assert(type); + console.assert(!preview || preview instanceof WebInspector.ObjectPreview); + console.assert(!target || target instanceof WebInspector.Target); + + this._target = target || WebInspector.mainTarget; + this._type = type; + this._subtype = subtype; + + if (objectId) { + // Object, Function, or Symbol. + console.assert(!subtype || typeof subtype === "string"); + console.assert(!description || typeof description === "string"); + console.assert(!value); + + this._objectId = objectId; + this._description = description || ""; + this._hasChildren = type !== "symbol"; + this._size = size; + this._classPrototype = classPrototype; + this._preview = preview; + + if (subtype === "class") { + this._functionDescription = this._description; + this._description = "class " + className; + } + } else { + // Primitive or null. + console.assert(type !== "object" || value === null); + console.assert(!preview); + + this._description = description || (value + ""); + this._hasChildren = false; + this._value = value; + } + } + + // Static + + static createFakeRemoteObject() + { + return new WebInspector.RemoteObject(undefined, WebInspector.RemoteObject.FakeRemoteObjectId, "object"); + } + + static fromPrimitiveValue(value) + { + return new WebInspector.RemoteObject(undefined, undefined, typeof value, undefined, value, undefined, undefined, undefined, undefined); + } + + static fromPayload(payload, target) + { + console.assert(typeof payload === "object", "Remote object payload should only be an object"); + + if (payload.subtype === "array") { + // COMPATIBILITY (iOS 8): Runtime.RemoteObject did not have size property, + // instead it was tacked onto the end of the description, like "Array[#]". + var match = payload.description.match(/\[(\d+)\]$/); + if (match) { + payload.size = parseInt(match[1]); + payload.description = payload.description.replace(/\[\d+\]$/, ""); + } + } + + if (payload.classPrototype) + payload.classPrototype = WebInspector.RemoteObject.fromPayload(payload.classPrototype, target); + + if (payload.preview) { + // COMPATIBILITY (iOS 8): iOS 7 and 8 did not have type/subtype/description on + // Runtime.ObjectPreview. Copy them over from the RemoteObject. + if (!payload.preview.type) { + payload.preview.type = payload.type; + payload.preview.subtype = payload.subtype; + payload.preview.description = payload.description; + payload.preview.size = payload.size; + } + + payload.preview = WebInspector.ObjectPreview.fromPayload(payload.preview); + } + + return new WebInspector.RemoteObject(target, payload.objectId, payload.type, payload.subtype, payload.value, payload.description, payload.size, payload.classPrototype, payload.className, payload.preview); + } + + static createCallArgument(valueOrObject) + { + if (valueOrObject instanceof WebInspector.RemoteObject) { + if (valueOrObject.objectId) + return {objectId: valueOrObject.objectId}; + return {value: valueOrObject.value}; + } + + return {value: valueOrObject}; + } + + static resolveNode(node, objectGroup, callback) + { + DOMAgent.resolveNode(node.id, objectGroup, function(error, object) { + if (!callback) + return; + + if (error || !object) + callback(null); + else + callback(WebInspector.RemoteObject.fromPayload(object, WebInspector.mainTarget)); + }); + } + + static type(remoteObject) + { + if (remoteObject === null) + return "null"; + + var type = typeof remoteObject; + if (type !== "object" && type !== "function") + return type; + + return remoteObject.type; + } + + // Public + + get target() + { + return this._target; + } + + get objectId() + { + return this._objectId; + } + + get type() + { + return this._type; + } + + get subtype() + { + return this._subtype; + } + + get description() + { + return this._description; + } + + get functionDescription() + { + console.assert(this.type === "function"); + + return this._functionDescription || this._description; + } + + get hasChildren() + { + return this._hasChildren; + } + + get value() + { + return this._value; + } + + get size() + { + return this._size || 0; + } + + get classPrototype() + { + return this._classPrototype; + } + + get preview() + { + return this._preview; + } + + hasSize() + { + return this.isArray() || this.isCollectionType(); + } + + hasValue() + { + return "_value" in this; + } + + getOwnPropertyDescriptors(callback) + { + this._getPropertyDescriptors(true, callback); + } + + getAllPropertyDescriptors(callback) + { + this._getPropertyDescriptors(false, callback); + } + + getDisplayablePropertyDescriptors(callback) + { + if (!this._objectId || this._isSymbol() || this._isFakeObject()) { + callback([]); + return; + } + + // COMPATIBILITY (iOS 8): RuntimeAgent.getDisplayableProperties did not exist. + // Here we do our best to reimplement it by getting all properties and reducing them down. + if (!RuntimeAgent.getDisplayableProperties) { + this._target.RuntimeAgent.getProperties(this._objectId, function(error, allProperties) { + var ownOrGetterPropertiesList = []; + if (allProperties) { + for (var property of allProperties) { + if (property.isOwn || property.name === "__proto__") { + // Own property or getter property in prototype chain. + ownOrGetterPropertiesList.push(property); + } else if (property.value && property.name !== property.name.toUpperCase()) { + var type = property.value.type; + if (type && type !== "function" && property.name !== "constructor") { + // Possible native binding getter property converted to a value. Also, no CONSTANT name style and not "constructor". + // There is no way of knowing if this is native or not, so just go with it. + ownOrGetterPropertiesList.push(property); + } + } + } + } + + this._getPropertyDescriptorsResolver(callback, error, ownOrGetterPropertiesList); + }.bind(this)); + return; + } + + this._target.RuntimeAgent.getDisplayableProperties(this._objectId, true, this._getPropertyDescriptorsResolver.bind(this, callback)); + } + + // FIXME: Phase out these deprecated functions. They return DeprecatedRemoteObjectProperty instead of PropertyDescriptors. + deprecatedGetOwnProperties(callback) + { + this._deprecatedGetProperties(true, callback); + } + + deprecatedGetAllProperties(callback) + { + this._deprecatedGetProperties(false, callback); + } + + deprecatedGetDisplayableProperties(callback) + { + if (!this._objectId || this._isSymbol() || this._isFakeObject()) { + callback([]); + return; + } + + // COMPATIBILITY (iOS 8): RuntimeAgent.getProperties did not support ownerAndGetterProperties. + // Here we do our best to reimplement it by getting all properties and reducing them down. + if (!RuntimeAgent.getDisplayableProperties) { + this._target.RuntimeAgent.getProperties(this._objectId, function(error, allProperties) { + var ownOrGetterPropertiesList = []; + if (allProperties) { + for (var property of allProperties) { + if (property.isOwn || property.get || property.name === "__proto__") { + // Own property or getter property in prototype chain. + ownOrGetterPropertiesList.push(property); + } else if (property.value && property.name !== property.name.toUpperCase()) { + var type = property.value.type; + if (type && type !== "function" && property.name !== "constructor") { + // Possible native binding getter property converted to a value. Also, no CONSTANT name style and not "constructor". + ownOrGetterPropertiesList.push(property); + } + } + } + } + + this._deprecatedGetPropertiesResolver(callback, error, ownOrGetterPropertiesList); + }.bind(this)); + return; + } + + this._target.RuntimeAgent.getDisplayableProperties(this._objectId, this._deprecatedGetPropertiesResolver.bind(this, callback)); + } + + setPropertyValue(name, value, callback) + { + if (!this._objectId || this._isSymbol() || this._isFakeObject()) { + callback("Can't set a property of non-object."); + return; + } + + // FIXME: It doesn't look like setPropertyValue is used yet. This will need to be tested when it is again (editable ObjectTrees). + this._target.RuntimeAgent.evaluate.invoke({expression: appendWebInspectorSourceURL(value), doNotPauseOnExceptionsAndMuteConsole: true}, evaluatedCallback.bind(this), this._target.RuntimeAgent); + + function evaluatedCallback(error, result, wasThrown) + { + if (error || wasThrown) { + callback(error || result.description); + return; + } + + function setPropertyValue(propertyName, propertyValue) + { + this[propertyName] = propertyValue; + } + + delete result.description; // Optimize on traffic. + + this._target.RuntimeAgent.callFunctionOn(this._objectId, appendWebInspectorSourceURL(setPropertyValue.toString()), [{value: name}, result], true, undefined, propertySetCallback.bind(this)); + + if (result._objectId) + this._target.RuntimeAgent.releaseObject(result._objectId); + } + + function propertySetCallback(error, result, wasThrown) + { + if (error || wasThrown) { + callback(error || result.description); + return; + } + + callback(); + } + } + + isUndefined() + { + return this._type === "undefined"; + } + + isNode() + { + return this._subtype === "node"; + } + + isArray() + { + return this._subtype === "array"; + } + + isClass() + { + return this._subtype === "class"; + } + + isCollectionType() + { + return this._subtype === "map" || this._subtype === "set" || this._subtype === "weakmap" || this._subtype === "weakset"; + } + + isWeakCollection() + { + return this._subtype === "weakmap" || this._subtype === "weakset"; + } + + getCollectionEntries(start, numberToFetch, callback) + { + start = typeof start === "number" ? start : 0; + numberToFetch = typeof numberToFetch === "number" ? numberToFetch : 100; + + console.assert(start >= 0); + console.assert(numberToFetch >= 0); + console.assert(this.isCollectionType()); + + // WeakMaps and WeakSets are not ordered. We should never send a non-zero start. + console.assert((this._subtype === "weakmap" && start === 0) || this._subtype !== "weakmap"); + console.assert((this._subtype === "weakset" && start === 0) || this._subtype !== "weakset"); + + let objectGroup = this.isWeakCollection() ? this._weakCollectionObjectGroup() : ""; + + this._target.RuntimeAgent.getCollectionEntries(this._objectId, objectGroup, start, numberToFetch, (error, entries) => { + entries = entries.map((x) => WebInspector.CollectionEntry.fromPayload(x, this._target)); + callback(entries); + }); + } + + releaseWeakCollectionEntries() + { + console.assert(this.isWeakCollection()); + + this._target.RuntimeAgent.releaseObjectGroup(this._weakCollectionObjectGroup()); + } + + pushNodeToFrontend(callback) + { + if (this._objectId) + WebInspector.domTreeManager.pushNodeToFrontend(this._objectId, callback); + else + callback(0); + } + + getProperty(propertyName, callback) + { + function inspectedPage_object_getProperty(property) { + return this[property]; + } + + this.callFunction(inspectedPage_object_getProperty, [propertyName], true, callback); + } + + callFunction(functionDeclaration, args, generatePreview, callback) + { + function mycallback(error, result, wasThrown) + { + result = result ? WebInspector.RemoteObject.fromPayload(result, this._target) : null; + + if (callback && typeof callback === "function") + callback(error, result, wasThrown); + } + + if (args) + args = args.map(WebInspector.RemoteObject.createCallArgument); + + this._target.RuntimeAgent.callFunctionOn(this._objectId, appendWebInspectorSourceURL(functionDeclaration.toString()), args, true, undefined, !!generatePreview, mycallback.bind(this)); + } + + callFunctionJSON(functionDeclaration, args, callback) + { + function mycallback(error, result, wasThrown) + { + callback((error || wasThrown) ? null : result.value); + } + + this._target.RuntimeAgent.callFunctionOn(this._objectId, appendWebInspectorSourceURL(functionDeclaration.toString()), args, true, true, mycallback); + } + + invokeGetter(getterRemoteObject, callback) + { + console.assert(getterRemoteObject instanceof WebInspector.RemoteObject); + + function backendInvokeGetter(getter) + { + return getter ? getter.call(this) : undefined; + } + + this.callFunction(backendInvokeGetter, [getterRemoteObject], true, callback); + } + + getOwnPropertyDescriptor(propertyName, callback) + { + function backendGetOwnPropertyDescriptor(propertyName) + { + return this[propertyName]; + } + + function wrappedCallback(error, result, wasThrown) + { + if (error || wasThrown || !(result instanceof WebInspector.RemoteObject)) { + callback(null); + return; + } + + var fakeDescriptor = {name: propertyName, value: result, writable: true, configurable: true, enumerable: false}; + var fakePropertyDescriptor = new WebInspector.PropertyDescriptor(fakeDescriptor, null, true, false, false, false); + callback(fakePropertyDescriptor); + } + + // FIXME: Implement a real RuntimeAgent.getOwnPropertyDescriptor? + this.callFunction(backendGetOwnPropertyDescriptor, [propertyName], false, wrappedCallback.bind(this)); + } + + release() + { + if (this._objectId && !this._isFakeObject()) + this._target.RuntimeAgent.releaseObject(this._objectId); + } + + arrayLength() + { + if (this._subtype !== "array") + return 0; + + var matches = this._description.match(/\[([0-9]+)\]/); + if (!matches) + return 0; + + return parseInt(matches[1], 10); + } + + asCallArgument() + { + return WebInspector.RemoteObject.createCallArgument(this); + } + + findFunctionSourceCodeLocation() + { + var result = new WebInspector.WrappedPromise; + + if (!this._isFunction() || !this._objectId) { + result.resolve(WebInspector.RemoteObject.SourceCodeLocationPromise.MissingObjectId); + return result.promise; + } + + this._target.DebuggerAgent.getFunctionDetails(this._objectId, (error, response) => { + if (error) { + result.reject(error); + return; + } + + var location = response.location; + var sourceCode = WebInspector.debuggerManager.scriptForIdentifier(location.scriptId, this._target); + + if (!sourceCode || (!WebInspector.isDebugUIEnabled() && isWebKitInternalScript(sourceCode.sourceURL))) { + result.resolve(WebInspector.RemoteObject.SourceCodeLocationPromise.NoSourceFound); + return; + } + + var sourceCodeLocation = sourceCode.createSourceCodeLocation(location.lineNumber, location.columnNumber || 0); + result.resolve(sourceCodeLocation); + }); + + return result.promise; + } + + // Private + + _isFakeObject() + { + return this._objectId === WebInspector.RemoteObject.FakeRemoteObjectId; + } + + _isSymbol() + { + return this._type === "symbol"; + } + + _isFunction() + { + return this._type === "function"; + } + + _weakCollectionObjectGroup() + { + return JSON.stringify(this._objectId) + "-" + this._subtype; + } + + _getPropertyDescriptors(ownProperties, callback) + { + if (!this._objectId || this._isSymbol() || this._isFakeObject()) { + callback([]); + return; + } + + this._target.RuntimeAgent.getProperties(this._objectId, ownProperties, true, this._getPropertyDescriptorsResolver.bind(this, callback)); + } + + getOwnPropertyDescriptorsAsObject(callback) + { + this.getOwnPropertyDescriptors(function(properties) { + var propertiesResult = {}; + var internalPropertiesResult = {}; + for (var propertyDescriptor of properties) { + var object = propertyDescriptor.isInternalProperty ? internalPropertiesResult : propertiesResult; + object[propertyDescriptor.name] = propertyDescriptor; + } + callback(propertiesResult, internalPropertiesResult); + }); + } + + _getPropertyDescriptorsResolver(callback, error, properties, internalProperties) + { + if (error) { + callback(null); + return; + } + + let descriptors = properties.map((payload) => { + return WebInspector.PropertyDescriptor.fromPayload(payload, false, this._target); + }); + + if (internalProperties) { + descriptors = descriptors.concat(internalProperties.map((payload) => { + return WebInspector.PropertyDescriptor.fromPayload(payload, true, this._target); + })); + } + + callback(descriptors); + } + + // FIXME: Phase out these deprecated functions. They return DeprecatedRemoteObjectProperty instead of PropertyDescriptors. + _deprecatedGetProperties(ownProperties, callback) + { + if (!this._objectId || this._isSymbol() || this._isFakeObject()) { + callback([]); + return; + } + + this._target.RuntimeAgent.getProperties(this._objectId, ownProperties, this._deprecatedGetPropertiesResolver.bind(this, callback)); + } + + _deprecatedGetPropertiesResolver(callback, error, properties, internalProperties) + { + if (error) { + callback(null); + return; + } + + if (internalProperties) { + properties = properties.concat(internalProperties.map(function(descriptor) { + descriptor.writable = false; + descriptor.configurable = false; + descriptor.enumerable = false; + descriptor.isOwn = true; + return descriptor; + })); + } + + var result = []; + for (var i = 0; properties && i < properties.length; ++i) { + var property = properties[i]; + if (property.get || property.set) { + if (property.get) + result.push(new WebInspector.DeprecatedRemoteObjectProperty("get " + property.name, WebInspector.RemoteObject.fromPayload(property.get, this._target), property)); + if (property.set) + result.push(new WebInspector.DeprecatedRemoteObjectProperty("set " + property.name, WebInspector.RemoteObject.fromPayload(property.set, this._target), property)); + } else + result.push(new WebInspector.DeprecatedRemoteObjectProperty(property.name, WebInspector.RemoteObject.fromPayload(property.value, this._target), property)); + } + + callback(result); + } +}; + +WebInspector.RemoteObject.FakeRemoteObjectId = "fake-remote-object"; + +WebInspector.RemoteObject.SourceCodeLocationPromise = { + NoSourceFound: "remote-object-source-code-location-promise-no-source-found", + MissingObjectId: "remote-object-source-code-location-promise-missing-object-id" +}; + +// FIXME: Phase out this deprecated class. +WebInspector.DeprecatedRemoteObjectProperty = class DeprecatedRemoteObjectProperty +{ + constructor(name, value, descriptor) + { + this.name = name; + this.value = value; + this.enumerable = descriptor ? !!descriptor.enumerable : true; + this.writable = descriptor ? !!descriptor.writable : true; + if (descriptor && descriptor.wasThrown) + this.wasThrown = true; + } + + // Static + + fromPrimitiveValue(name, value) + { + return new WebInspector.DeprecatedRemoteObjectProperty(name, WebInspector.RemoteObject.fromPrimitiveValue(value)); + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Protocol/ReplayObserver.js b/Source/WebInspectorUI/UserInterface/Protocol/ReplayObserver.js new file mode 100644 index 000000000..e0a86719a --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Protocol/ReplayObserver.js @@ -0,0 +1,120 @@ +/* + * Copyright (C) 2013 University of Washington. All rights reserved. + * Copyright (C) 2014 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +// FIXME: This ReplayPosition class shouldn't be here, no matter how simple it is. +WebInspector.ReplayPosition = class ReplayPosition +{ + constructor(segmentOffset, inputOffset) + { + this.segmentOffset = segmentOffset; + this.inputOffset = inputOffset; + } +}; + +WebInspector.ReplayObserver = class ReplayObserver +{ + // Events defined by the "Replay" domain. + + captureStarted() + { + WebInspector.replayManager.captureStarted(); + } + + captureStopped() + { + WebInspector.replayManager.captureStopped(); + } + + playbackStarted() + { + WebInspector.replayManager.playbackStarted(); + } + + playbackHitPosition(replayPosition, timestamp) + { + WebInspector.replayManager.playbackHitPosition(new WebInspector.ReplayPosition(replayPosition.segmentOffset, replayPosition.inputOffset), timestamp); + } + + playbackPaused(replayPosition) + { + WebInspector.replayManager.playbackPaused(new WebInspector.ReplayPosition(replayPosition.segmentOffset, replayPosition.inputOffset)); + } + + playbackFinished() + { + WebInspector.replayManager.playbackFinished(); + } + + inputSuppressionChanged(willSuppress) + { + // Not handled yet. + } + + sessionCreated(sessionId) + { + WebInspector.replayManager.sessionCreated(sessionId); + } + + sessionModified(sessionId) + { + WebInspector.replayManager.sessionModified(sessionId); + } + + sessionRemoved(sessionId) + { + WebInspector.replayManager.sessionRemoved(sessionId); + } + + sessionLoaded(sessionId) + { + WebInspector.replayManager.sessionLoaded(sessionId); + } + + segmentCreated(segmentId) + { + WebInspector.replayManager.segmentCreated(segmentId); + } + + segmentRemoved(segmentId) + { + WebInspector.replayManager.segmentRemoved(segmentId); + } + + segmentCompleted(segmentId) + { + WebInspector.replayManager.segmentCompleted(segmentId); + } + + segmentLoaded(segmentId) + { + WebInspector.replayManager.segmentLoaded(segmentId); + } + + segmentUnloaded() + { + WebInspector.replayManager.segmentUnloaded(); + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Protocol/RuntimeObserver.js b/Source/WebInspectorUI/UserInterface/Protocol/RuntimeObserver.js new file mode 100644 index 000000000..e09baa480 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Protocol/RuntimeObserver.js @@ -0,0 +1,34 @@ +/* + * Copyright (C) 2013, 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.RuntimeObserver = class RuntimeObserver +{ + // Events defined by the "Runtime" domain. + + executionContextCreated(contextPayload) + { + WebInspector.frameResourceManager.executionContextCreated(contextPayload); + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Protocol/ScriptProfilerObserver.js b/Source/WebInspectorUI/UserInterface/Protocol/ScriptProfilerObserver.js new file mode 100644 index 000000000..0d299547f --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Protocol/ScriptProfilerObserver.js @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.ScriptProfilerObserver = class ScriptProfilerObserver +{ + // Events defined by the "ScriptProfiler" domain. + + trackingStart(timestamp) + { + WebInspector.timelineManager.scriptProfilerTrackingStarted(timestamp); + } + + trackingUpdate(event) + { + WebInspector.timelineManager.scriptProfilerTrackingUpdated(event); + } + + trackingComplete(samples) + { + WebInspector.timelineManager.scriptProfilerTrackingCompleted(samples); + } + + programmaticCaptureStarted() + { + WebInspector.timelineManager.scriptProfilerProgrammaticCaptureStarted(); + } + + programmaticCaptureStopped() + { + WebInspector.timelineManager.scriptProfilerProgrammaticCaptureStopped(); + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Protocol/Target.js b/Source/WebInspectorUI/UserInterface/Protocol/Target.js new file mode 100644 index 000000000..ffc77b420 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Protocol/Target.js @@ -0,0 +1,95 @@ +/* + * Copyright (C) 2016 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.Target = class Target extends WebInspector.Object +{ + constructor(identifier, name, type, connection) + { + super(); + + this._identifier = identifier; + this._name = name; + this._type = type; + this._connection = connection; + this._executionContext = null; + this._mainResource = null; + this._resourceCollection = new WebInspector.ResourceCollection; + this._extraScriptCollection = new WebInspector.Collection(WebInspector.Collection.TypeVerifier.Script); + + this._connection.target = this; + } + + // Agents + + get RuntimeAgent() { return this._connection._agents.Runtime; } + get ConsoleAgent() { return this._connection._agents.Console; } + get DebuggerAgent() { return this._connection._agents.Debugger; } + get HeapAgent() { return this._connection._agents.Heap; } + + // Public + + get identifier() { return this._identifier; } + get name() { return this._name; } + get type() { return this._type; } + get connection() { return this._connection; } + get executionContext() { return this._executionContext; } + + get resourceCollection() { return this._resourceCollection; } + get extraScriptCollection() { return this._extraScriptCollection; } + + get mainResource() { return this._mainResource; } + set mainResource(resource) { this._mainResource = resource; } + + addResource(resource) + { + this._resourceCollection.add(resource); + + this.dispatchEventToListeners(WebInspector.Target.Event.ResourceAdded, {resource}); + } + + adoptResource(resource) + { + resource._target = this; + + this.addResource(resource); + } + + addScript(script) + { + this._extraScriptCollection.add(script); + + this.dispatchEventToListeners(WebInspector.Target.Event.ScriptAdded, {script}); + } +}; + +WebInspector.Target.Type = { + Main: Symbol("main"), + Worker: Symbol("worker"), +}; + +WebInspector.Target.Event = { + ResourceAdded: "target-resource-added", + ScriptAdded: "target-script-added", +}; diff --git a/Source/WebInspectorUI/UserInterface/Protocol/TimelineObserver.js b/Source/WebInspectorUI/UserInterface/Protocol/TimelineObserver.js new file mode 100644 index 000000000..99dfb9763 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Protocol/TimelineObserver.js @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2013, 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.TimelineObserver = class TimelineObserver +{ + // Events defined by the "Timeline" domain. + + eventRecorded(record) + { + WebInspector.timelineManager.eventRecorded(record); + } + + recordingStarted(startTime) + { + WebInspector.timelineManager.capturingStarted(startTime); + } + + recordingStopped(endTime) + { + WebInspector.timelineManager.capturingStopped(endTime); + } + + autoCaptureStarted() + { + WebInspector.timelineManager.autoCaptureStarted(); + } + + programmaticCaptureStarted() + { + WebInspector.timelineManager.programmaticCaptureStarted(); + } + + programmaticCaptureStopped() + { + WebInspector.timelineManager.programmaticCaptureStopped(); + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Protocol/WorkerObserver.js b/Source/WebInspectorUI/UserInterface/Protocol/WorkerObserver.js new file mode 100644 index 000000000..9a1a8db83 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Protocol/WorkerObserver.js @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2016 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.WorkerObserver = class WorkerObserver +{ + // Events defined by the "Worker" domain. + + workerCreated(workerId, url) + { + WebInspector.workerManager.workerCreated(workerId, url); + } + + workerTerminated(workerId) + { + WebInspector.workerManager.workerTerminated(workerId); + } + + dispatchMessageFromWorker(workerId, message) + { + WebInspector.workerManager.dispatchMessageFromWorker(workerId, message); + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Protocol/WorkerTarget.js b/Source/WebInspectorUI/UserInterface/Protocol/WorkerTarget.js new file mode 100644 index 000000000..fbafb8c61 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Protocol/WorkerTarget.js @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2016 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.WorkerTarget = class WorkerTarget extends WebInspector.Target +{ + constructor(workerId, name, connection) + { + super(workerId, name, WebInspector.Target.Type.Worker, connection); + + WebInspector.frameResourceManager.adoptOrphanedResourcesForTarget(this); + + if (this.RuntimeAgent) { + this._executionContext = new WebInspector.ExecutionContext(this, WebInspector.RuntimeManager.TopLevelContextExecutionIdentifier, this.displayName, false, null); + this.RuntimeAgent.enable(); + if (WebInspector.showJavaScriptTypeInformationSetting && WebInspector.showJavaScriptTypeInformationSetting.value) + this.RuntimeAgent.enableTypeProfiler(); + if (WebInspector.enableControlFlowProfilerSetting && WebInspector.enableControlFlowProfilerSetting.value) + this.RuntimeAgent.enableControlFlowProfiler(); + } + + if (this.DebuggerAgent) + WebInspector.debuggerManager.initializeTarget(this); + + if (this.ConsoleAgent) + this.ConsoleAgent.enable(); + + if (this.HeapAgent) + this.HeapAgent.enable(); + } + + // Protected (Target) + + get displayName() + { + return WebInspector.displayNameForURL(this._name); + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Proxies/FormatterWorkerProxy.js b/Source/WebInspectorUI/UserInterface/Proxies/FormatterWorkerProxy.js new file mode 100644 index 000000000..96159fb87 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Proxies/FormatterWorkerProxy.js @@ -0,0 +1,91 @@ +/* + * Copyright (C) 2016 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.FormatterWorkerProxy = class FormatterWorkerProxy extends WebInspector.Object +{ + constructor() + { + super(); + + this._formatterWorker = new Worker("Workers/Formatter/FormatterWorker.js"); + this._formatterWorker.addEventListener("message", this._handleMessage.bind(this)); + + this._nextCallId = 1; + this._callbacks = new Map; + } + + // Static + + static singleton() + { + if (!FormatterWorkerProxy.instance) + FormatterWorkerProxy.instance = new FormatterWorkerProxy; + return FormatterWorkerProxy.instance; + } + + // Actions + + formatJavaScript(sourceText, isModule, indentString, includeSourceMapData) + { + this.performAction("formatJavaScript", ...arguments); + } + + // Public + + performAction(actionName) + { + let callId = this._nextCallId++; + let callback = arguments[arguments.length - 1]; + let actionArguments = Array.prototype.slice.call(arguments, 1, arguments.length - 1); + + console.assert(typeof actionName === "string", "performAction should always have an actionName"); + console.assert(typeof callback === "function", "performAction should always have a callback"); + + this._callbacks.set(callId, callback); + this._postMessage({callId, actionName, actionArguments}); + } + + // Private + + _postMessage() + { + this._formatterWorker.postMessage(...arguments); + } + + _handleMessage(event) + { + let data = event.data; + + // Action response. + if (data.callId) { + let callback = this._callbacks.get(data.callId); + this._callbacks.delete(data.callId); + callback(data.result); + return; + } + + console.error("Unexpected FormatterWorker message", data); + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Proxies/HeapSnapshotDiffProxy.js b/Source/WebInspectorUI/UserInterface/Proxies/HeapSnapshotDiffProxy.js new file mode 100644 index 000000000..4dc62ed61 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Proxies/HeapSnapshotDiffProxy.js @@ -0,0 +1,107 @@ +/* + * Copyright (C) 2016 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.HeapSnapshotDiffProxy = class HeapSnapshotDiffProxy extends WebInspector.Object +{ + constructor(snapshotDiffObjectId, snapshot1, snapshot2, totalSize, totalObjectCount, categories) + { + super(); + + this._proxyObjectId = snapshotDiffObjectId; + + console.assert(snapshot1 instanceof WebInspector.HeapSnapshotProxy); + console.assert(snapshot2 instanceof WebInspector.HeapSnapshotProxy); + + this._snapshot1 = snapshot1; + this._snapshot2 = snapshot2; + this._totalSize = totalSize; + this._totalObjectCount = totalObjectCount; + this._categories = Map.fromObject(categories); + } + + // Static + + static deserialize(objectId, serializedSnapshotDiff) + { + let {snapshot1: serializedSnapshot1, snapshot2: serializedSnapshot2, totalSize, totalObjectCount, categories} = serializedSnapshotDiff; + // FIXME: The objectId for these snapshots is the snapshotDiff's objectId. Currently these + // snapshots are only used for static data so the proxing doesn't matter. However, + // should we serialize the objectId with the snapshot so we have the right objectId? + let snapshot1 = WebInspector.HeapSnapshotProxy.deserialize(objectId, serializedSnapshot1); + let snapshot2 = WebInspector.HeapSnapshotProxy.deserialize(objectId, serializedSnapshot2); + return new WebInspector.HeapSnapshotDiffProxy(objectId, snapshot1, snapshot2, totalSize, totalObjectCount, categories); + } + + // Public + + get snapshot1() { return this._snapshot1; } + get snapshot2() { return this._snapshot2; } + get totalSize() { return this._totalSize; } + get totalObjectCount() { return this._totalObjectCount; } + get categories() { return this._categories; } + get invalid() { return this._snapshot1.invalid || this._snapshot2.invalid; } + + updateForCollectionEvent(event) + { + console.assert(!this.invalid); + if (!event.data.affectedSnapshots.includes(this._snapshot2._identifier)) + return; + + this.update(() => { + this.dispatchEventToListeners(WebInspector.HeapSnapshotProxy.Event.CollectedNodes, event.data); + }); + } + + allocationBucketCounts(bucketSizes, callback) + { + console.assert(!this.invalid); + WebInspector.HeapSnapshotWorkerProxy.singleton().callMethod(this._proxyObjectId, "allocationBucketCounts", bucketSizes, callback); + } + + instancesWithClassName(className, callback) + { + console.assert(!this.invalid); + WebInspector.HeapSnapshotWorkerProxy.singleton().callMethod(this._proxyObjectId, "instancesWithClassName", className, (serializedNodes) => { + callback(serializedNodes.map(WebInspector.HeapSnapshotNodeProxy.deserialize.bind(null, this._proxyObjectId))); + }); + } + + update(callback) + { + console.assert(!this.invalid); + WebInspector.HeapSnapshotWorkerProxy.singleton().callMethod(this._proxyObjectId, "update", ({liveSize, categories}) => { + this._categories = Map.fromObject(categories); + callback(); + }); + } + + nodeWithIdentifier(nodeIdentifier, callback) + { + console.assert(!this.invalid); + WebInspector.HeapSnapshotWorkerProxy.singleton().callMethod(this._proxyObjectId, "nodeWithIdentifier", nodeIdentifier, (serializedNode) => { + callback(WebInspector.HeapSnapshotNodeProxy.deserialize(this._proxyObjectId, serializedNode)); + }); + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Proxies/HeapSnapshotEdgeProxy.js b/Source/WebInspectorUI/UserInterface/Proxies/HeapSnapshotEdgeProxy.js new file mode 100644 index 000000000..e4d44b176 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Proxies/HeapSnapshotEdgeProxy.js @@ -0,0 +1,67 @@ +/* + * Copyright (C) 2016 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +// Directed edge between two HeapSnapshotNodes 'from' and 'to'. + +WebInspector.HeapSnapshotEdgeProxy = class HeapSnapshotEdgeProxy +{ + constructor(objectId, fromIdentifier, toIdentifier, type, data) + { + this._proxyObjectId = objectId; + + console.assert(type in WebInspector.HeapSnapshotEdgeProxy.EdgeType); + + this.fromIdentifier = fromIdentifier; + this.toIdentifier = toIdentifier; + this.type = type; + this.data = data; + + this.from = null; + this.to = null; + } + + isPrivateSymbol() + { + if (WebInspector.isDebugUIEnabled()) + return false; + + return typeof this.data === "string" && this.data.startsWith("PrivateSymbol"); + } + + // Static + + static deserialize(objectId, serializedEdge) + { + let {from, to, type, data} = serializedEdge; + return new WebInspector.HeapSnapshotEdgeProxy(objectId, from, to, type, data); + } +}; + +WebInspector.HeapSnapshotEdgeProxy.EdgeType = { + Internal: "Internal", // No data. + Property: "Property", // data is string property name. + Index: "Index", // data is numeric index. + Variable: "Variable", // data is string variable name. +}; diff --git a/Source/WebInspectorUI/UserInterface/Proxies/HeapSnapshotNodeProxy.js b/Source/WebInspectorUI/UserInterface/Proxies/HeapSnapshotNodeProxy.js new file mode 100644 index 000000000..908400d0e --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Proxies/HeapSnapshotNodeProxy.js @@ -0,0 +1,99 @@ +/* + * Copyright (C) 2016 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.HeapSnapshotNodeProxy = class HeapSnapshotNodeProxy +{ + constructor(snapshotObjectId, identifier, className, size, retainedSize, internal, gcRoot, dead, dominatorNodeIdentifier, hasChildren) + { + this._proxyObjectId = snapshotObjectId; + + this.id = identifier; + this.className = className; + this.size = size; + this.retainedSize = retainedSize; + this.internal = internal; + this.gcRoot = gcRoot; + this.dead = dead; + this.dominatorNodeIdentifier = dominatorNodeIdentifier; + this.hasChildren = hasChildren; + } + + // Static + + static deserialize(objectId, serializedNode) + { + let {id, className, size, retainedSize, internal, gcRoot, dead, dominatorNodeIdentifier, hasChildren} = serializedNode; + return new WebInspector.HeapSnapshotNodeProxy(objectId, id, className, size, retainedSize, internal, gcRoot, dead, dominatorNodeIdentifier, hasChildren); + } + + // Proxied + + shortestGCRootPath(callback) + { + WebInspector.HeapSnapshotWorkerProxy.singleton().callMethod(this._proxyObjectId, "shortestGCRootPath", this.id, (serializedPath) => { + let isNode = false; + let path = serializedPath.map((component) => { + isNode = !isNode; + if (isNode) + return WebInspector.HeapSnapshotNodeProxy.deserialize(this._proxyObjectId, component); + return WebInspector.HeapSnapshotEdgeProxy.deserialize(this._proxyObjectId, component); + }); + + for (let i = 1; i < path.length; i += 2) { + console.assert(path[i] instanceof WebInspector.HeapSnapshotEdgeProxy); + let edge = path[i]; + edge.from = path[i - 1]; + edge.to = path[i + 1]; + } + + callback(path); + }); + } + + dominatedNodes(callback) + { + WebInspector.HeapSnapshotWorkerProxy.singleton().callMethod(this._proxyObjectId, "dominatedNodes", this.id, (serializedNodes) => { + callback(serializedNodes.map(WebInspector.HeapSnapshotNodeProxy.deserialize.bind(null, this._proxyObjectId))); + }); + } + + retainedNodes(callback) + { + WebInspector.HeapSnapshotWorkerProxy.singleton().callMethod(this._proxyObjectId, "retainedNodes", this.id, ({retainedNodes: serializedNodes, edges: serializedEdges}) => { + let deserializedNodes = serializedNodes.map(WebInspector.HeapSnapshotNodeProxy.deserialize.bind(null, this._proxyObjectId)); + let deserializedEdges = serializedEdges.map(WebInspector.HeapSnapshotEdgeProxy.deserialize.bind(null, this._proxyObjectId)); + callback(deserializedNodes, deserializedEdges); + }); + } + + retainers(callback) + { + WebInspector.HeapSnapshotWorkerProxy.singleton().callMethod(this._proxyObjectId, "retainers", this.id, ({retainers: serializedNodes, edges: serializedEdges}) => { + let deserializedNodes = serializedNodes.map(WebInspector.HeapSnapshotNodeProxy.deserialize.bind(null, this._proxyObjectId)); + let deserializedEdges = serializedEdges.map(WebInspector.HeapSnapshotEdgeProxy.deserialize.bind(null, this._proxyObjectId)); + callback(deserializedNodes, deserializedEdges); + }); + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Proxies/HeapSnapshotProxy.js b/Source/WebInspectorUI/UserInterface/Proxies/HeapSnapshotProxy.js new file mode 100644 index 000000000..1c8ed63a7 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Proxies/HeapSnapshotProxy.js @@ -0,0 +1,135 @@ +/* + * Copyright (C) 2016 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.HeapSnapshotProxy = class HeapSnapshotProxy extends WebInspector.Object +{ + constructor(snapshotObjectId, identifier, title, totalSize, totalObjectCount, liveSize, categories) + { + super(); + + this._proxyObjectId = snapshotObjectId; + + this._identifier = identifier; + this._title = title; + this._totalSize = totalSize; + this._totalObjectCount = totalObjectCount; + this._liveSize = liveSize; + this._categories = Map.fromObject(categories); + + console.assert(!this.invalid); + + if (!WebInspector.HeapSnapshotProxy.ValidSnapshotProxies) + WebInspector.HeapSnapshotProxy.ValidSnapshotProxies = []; + WebInspector.HeapSnapshotProxy.ValidSnapshotProxies.push(this); + } + + // Static + + static deserialize(objectId, serializedSnapshot) + { + let {identifier, title, totalSize, totalObjectCount, liveSize, categories} = serializedSnapshot; + return new WebInspector.HeapSnapshotProxy(objectId, identifier, title, totalSize, totalObjectCount, liveSize, categories); + } + + static invalidateSnapshotProxies() + { + if (!WebInspector.HeapSnapshotProxy.ValidSnapshotProxies) + return; + + for (let snapshotProxy of WebInspector.HeapSnapshotProxy.ValidSnapshotProxies) + snapshotProxy._invalidate(); + + WebInspector.HeapSnapshotProxy.ValidSnapshotProxies = null; + } + + // Public + + get proxyObjectId() { return this._proxyObjectId; } + get identifier() { return this._identifier; } + get title() { return this._title; } + get totalSize() { return this._totalSize; } + get totalObjectCount() { return this._totalObjectCount; } + get liveSize() { return this._liveSize; } + get categories() { return this._categories; } + get invalid() { return this._proxyObjectId === 0; } + + updateForCollectionEvent(event) + { + console.assert(!this.invalid); + if (!event.data.affectedSnapshots.includes(this._identifier)) + return; + + this.update(() => { + this.dispatchEventToListeners(WebInspector.HeapSnapshotProxy.Event.CollectedNodes, event.data); + }); + } + + allocationBucketCounts(bucketSizes, callback) + { + console.assert(!this.invalid); + WebInspector.HeapSnapshotWorkerProxy.singleton().callMethod(this._proxyObjectId, "allocationBucketCounts", bucketSizes, callback); + } + + instancesWithClassName(className, callback) + { + console.assert(!this.invalid); + WebInspector.HeapSnapshotWorkerProxy.singleton().callMethod(this._proxyObjectId, "instancesWithClassName", className, (serializedNodes) => { + callback(serializedNodes.map(WebInspector.HeapSnapshotNodeProxy.deserialize.bind(null, this._proxyObjectId))); + }); + } + + update(callback) + { + console.assert(!this.invalid); + WebInspector.HeapSnapshotWorkerProxy.singleton().callMethod(this._proxyObjectId, "update", ({liveSize, categories}) => { + this._liveSize = liveSize; + this._categories = Map.fromObject(categories); + callback(); + }); + } + + nodeWithIdentifier(nodeIdentifier, callback) + { + console.assert(!this.invalid); + WebInspector.HeapSnapshotWorkerProxy.singleton().callMethod(this._proxyObjectId, "nodeWithIdentifier", nodeIdentifier, (serializedNode) => { + callback(WebInspector.HeapSnapshotNodeProxy.deserialize(this._proxyObjectId, serializedNode)); + }); + } + + // Private + + _invalidate() + { + this._proxyObjectId = 0; + this._liveSize = 0; + + this.dispatchEventToListeners(WebInspector.HeapSnapshotProxy.Event.Invalidated); + } +}; + +WebInspector.HeapSnapshotProxy.Event = { + CollectedNodes: "heap-snapshot-proxy-collected-nodes", + Invalidated: "heap-snapshot-proxy-invalidated", +}; diff --git a/Source/WebInspectorUI/UserInterface/Proxies/HeapSnapshotWorkerProxy.js b/Source/WebInspectorUI/UserInterface/Proxies/HeapSnapshotWorkerProxy.js new file mode 100644 index 000000000..c47993c5e --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Proxies/HeapSnapshotWorkerProxy.js @@ -0,0 +1,140 @@ +/* + * Copyright (C) 2016 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.HeapSnapshotWorkerProxy = class HeapSnapshotWorkerProxy extends WebInspector.Object +{ + constructor() + { + super(); + + this._heapSnapshotWorker = new Worker("Workers/HeapSnapshot/HeapSnapshotWorker.js"); + this._heapSnapshotWorker.addEventListener("message", this._handleMessage.bind(this)); + + this._nextCallId = 1; + this._callbacks = new Map; + + WebInspector.Frame.addEventListener(WebInspector.Frame.Event.MainResourceDidChange, this._mainResourceDidChange, this); + } + + // Static + + static singleton() + { + if (!HeapSnapshotWorkerProxy.instance) + HeapSnapshotWorkerProxy.instance = new HeapSnapshotWorkerProxy; + return HeapSnapshotWorkerProxy.instance; + } + + // Actions + + clearSnapshots(callback) + { + this.performAction("clearSnapshots", callback); + } + + createSnapshot(snapshotStringData, callback) + { + this.performAction("createSnapshot", ...arguments); + } + + createSnapshotDiff(objectId1, objectId2, callback) + { + this.performAction("createSnapshotDiff", ...arguments); + } + + // Public + + performAction(actionName) + { + let callId = this._nextCallId++; + let callback = arguments[arguments.length - 1]; + let actionArguments = Array.prototype.slice.call(arguments, 1, arguments.length - 1); + + console.assert(typeof actionName === "string", "performAction should always have an actionName"); + console.assert(typeof callback === "function", "performAction should always have a callback"); + + this._callbacks.set(callId, callback); + this._postMessage({callId, actionName, actionArguments}); + } + + callMethod(objectId, methodName) + { + let callId = this._nextCallId++; + let callback = arguments[arguments.length - 1]; + let methodArguments = Array.prototype.slice.call(arguments, 2, arguments.length - 1); + + console.assert(typeof objectId === "number", "callMethod should always have an objectId"); + console.assert(typeof methodName === "string", "callMethod should always have a methodName"); + console.assert(typeof callback === "function", "callMethod should always have a callback"); + + this._callbacks.set(callId, callback); + this._postMessage({callId, objectId, methodName, methodArguments}); + } + + // Private + + _mainResourceDidChange(event) + { + if (!event.target.isMainFrame()) + return; + + this.clearSnapshots(() => { + WebInspector.HeapSnapshotProxy.invalidateSnapshotProxies(); + }); + } + + _postMessage() + { + this._heapSnapshotWorker.postMessage(...arguments); + } + + _handleMessage(event) + { + let data = event.data; + + // Error. + if (data.error) { + console.assert(data.callId); + this._callbacks.delete(data.callId); + return; + } + + // Event. + if (data.eventName) { + this.dispatchEventToListeners(data.eventName, data.eventData); + return; + } + + // Action or Method Response. + if (data.callId) { + let callback = this._callbacks.get(data.callId); + this._callbacks.delete(data.callId); + callback(data.result); + return; + } + + console.error("Unexpected HeapSnapshotWorker message", data); + } +}; diff --git a/Source/WebInspectorUI/UserInterface/QuickConsole.css b/Source/WebInspectorUI/UserInterface/QuickConsole.css deleted file mode 100644 index 67642493c..000000000 --- a/Source/WebInspectorUI/UserInterface/QuickConsole.css +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.quick-console { - position: relative; - - display: -webkit-flex; - -webkit-align-items: flex-end; - - background-color: white; - border-top: 1px solid rgb(190, 190, 190); - - outline: none; - overflow: hidden; - - font-family: Menlo, monospace; - font-size: 11px; -} - -.quick-console.showing-log { - border-top-color: rgb(240, 240, 240); -} - -.quick-console > .console-prompt { - display: -webkit-flex; - -webkit-flex: 1; - - -webkit-align-items: flex-start; - - max-height: 150px; - - overflow-y: auto; - overflow-x: hidden; -} - -.quick-console > .console-prompt::before { - position: relative; - z-index: 1; - - top: 5px; - left: 4px; - - margin-right: 1px; - - width: 10px; - height: 10px; - - content: url(Images/UserInputPrompt.svg); -} - -.quick-console > .console-prompt > .CodeMirror { - margin: 4px 0 3px; -} - -.quick-console > .navigation-bar { - background: transparent; - border: none; - - height: 21px; -} diff --git a/Source/WebInspectorUI/UserInterface/QuickConsole.js b/Source/WebInspectorUI/UserInterface/QuickConsole.js deleted file mode 100644 index aba23af74..000000000 --- a/Source/WebInspectorUI/UserInterface/QuickConsole.js +++ /dev/null @@ -1,352 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.QuickConsole = function(element) -{ - WebInspector.Object.call(this); - - this._toggleOrFocusKeyboardShortcut = new WebInspector.KeyboardShortcut(null, WebInspector.KeyboardShortcut.Key.Escape, this._toggleOrFocus.bind(this)); - - var mainFrameExecutionContext = new WebInspector.ExecutionContext(WebInspector.QuickConsole.MainFrameContextExecutionIdentifier, WebInspector.UIString("Main Frame"), true, null); - this._mainFrameExecutionContextPathComponent = this._createExecutionContextPathComponent(mainFrameExecutionContext.name, mainFrameExecutionContext.identifier); - this._selectedExecutionContextPathComponent = this._mainFrameExecutionContextPathComponent; - - this._otherExecutionContextPathComponents = []; - this._frameIdentifierToExecutionContextPathComponentMap = {}; - - this._element = element || document.createElement("div"); - this._element.classList.add(WebInspector.QuickConsole.StyleClassName); - - this.prompt = new WebInspector.ConsolePrompt(null, "text/javascript"); - this.prompt.element.classList.add(WebInspector.QuickConsole.TextPromptStyleClassName); - this._element.appendChild(this.prompt.element); - - this.prompt.shown(); - - this._navigationBar = new WebInspector.QuickConsoleNavigationBar; - this._element.appendChild(this._navigationBar.element); - - this._executionContextSelectorItem = new WebInspector.HierarchicalPathNavigationItem; - this._executionContextSelectorItem.showSelectorArrows = true; - this._navigationBar.addNavigationItem(this._executionContextSelectorItem); - - this._executionContextSelectorDivider = new WebInspector.DividerNavigationItem; - this._navigationBar.addNavigationItem(this._executionContextSelectorDivider); - - this._rebuildExecutionContextPathComponents(); - - // COMPATIBILITY (iOS 6): Execution contexts did not exist, evaluation worked with frame ids. - if (WebInspector.ExecutionContext.supported()) { - WebInspector.Frame.addEventListener(WebInspector.Frame.Event.PageExecutionContextChanged, this._framePageExecutionContextsChanged, this); - WebInspector.Frame.addEventListener(WebInspector.Frame.Event.ExecutionContextsCleared, this._frameExecutionContextsCleared, this); - } else { - WebInspector.frameResourceManager.addEventListener(WebInspector.FrameResourceManager.Event.FrameWasAdded, this._frameAdded, this); - WebInspector.frameResourceManager.addEventListener(WebInspector.FrameResourceManager.Event.FrameWasRemoved, this._frameRemoved, this); - WebInspector.Frame.addEventListener(WebInspector.Frame.Event.MainResourceDidChange, this._frameMainResourceChanged, this); - } - - WebInspector.debuggerManager.addEventListener(WebInspector.DebuggerManager.Event.ActiveCallFrameDidChange, this._debuggerActiveCallFrameDidChange, this); -}; - -WebInspector.QuickConsole.StyleClassName = "quick-console"; -WebInspector.QuickConsole.ShowingLogClassName = "showing-log"; -WebInspector.QuickConsole.NavigationBarContainerStyleClassName = "navigation-bar-container"; -WebInspector.QuickConsole.NavigationBarSpacerStyleClassName = "navigation-bar-spacer"; -WebInspector.QuickConsole.TextPromptStyleClassName = "text-prompt"; - -WebInspector.QuickConsole.ToolbarSingleLineHeight = 21; -WebInspector.QuickConsole.ToolbarPromptPadding = 4; -WebInspector.QuickConsole.ToolbarTopBorder = 1; - -WebInspector.QuickConsole.MainFrameContextExecutionIdentifier = undefined; - -WebInspector.QuickConsole.Event = { - DidResize: "quick-console-did-resize" -}; - -WebInspector.QuickConsole.prototype = { - constructor: WebInspector.QuickConsole, - - // Public - - get element() - { - return this._element; - }, - - get navigationBar() - { - return this._navigationBar; - }, - - get executionContextIdentifier() - { - return this._selectedExecutionContextPathComponent._executionContextIdentifier; - }, - - updateLayout: function() - { - // A hard maximum size of 33% of the window. - const maximumAllowedHeight = Math.round(window.innerHeight * 0.33); - this.prompt.element.style.maxHeight = maximumAllowedHeight + "px"; - }, - - consoleLogVisibilityChanged: function(visible) - { - if (visible) - this.element.classList.add(WebInspector.QuickConsole.ShowingLogClassName); - else - this.element.classList.remove(WebInspector.QuickConsole.ShowingLogClassName); - - this.dispatchEventToListeners(WebInspector.QuickConsole.Event.DidResize); - }, - - // Private - - _executionContextPathComponentsToDisplay: function() - { - // If we are in the debugger the console will use the active call frame, don't show the selector. - if (WebInspector.debuggerManager.activeCallFrame) - return []; - - // If there is only the Main Frame, don't show the selector. - if (!this._otherExecutionContextPathComponents.length) - return []; - - return [this._selectedExecutionContextPathComponent]; - }, - - _rebuildExecutionContextPathComponents: function() - { - var components = this._executionContextPathComponentsToDisplay(); - var isEmpty = !components.length; - - this._executionContextSelectorItem.components = components; - - this._executionContextSelectorItem.hidden = isEmpty; - this._executionContextSelectorDivider.hidden = isEmpty; - }, - - _framePageExecutionContextsChanged: function(event) - { - var frame = event.target; - - var shouldAutomaticallySelect = this._restoreSelectedExecutionContextForFrame === frame; - - var newExecutionContextPathComponent = this._insertExecutionContextPathComponentForFrame(frame, shouldAutomaticallySelect); - - if (shouldAutomaticallySelect) { - delete this._restoreSelectedExecutionContextForFrame; - this._selectedExecutionContextPathComponent = newExecutionContextPathComponent; - this._rebuildExecutionContextPathComponents(); - } - }, - - _frameExecutionContextsCleared: function(event) - { - var frame = event.target; - - // If this frame is navigating and it is selected in the UI we want to reselect its new item after navigation. - if (event.data.committingProvisionalLoad && !this._restoreSelectedExecutionContextForFrame) { - var executionContextPathComponent = this._frameIdentifierToExecutionContextPathComponentMap[frame.id]; - if (this._selectedExecutionContextPathComponent === executionContextPathComponent) { - this._restoreSelectedExecutionContextForFrame = frame; - // As a fail safe, if the frame never gets an execution context, clear the restore value. - setTimeout(function() { delete this._restoreSelectedExecutionContextForFrame; }.bind(this), 10); - } - } - - this._removeExecutionContextPathComponentForFrame(frame); - }, - - _frameAdded: function(event) - { - var frame = event.data.frame; - this._insertExecutionContextPathComponentForFrame(frame); - }, - - _frameRemoved: function(event) - { - var frame = event.data.frame; - this._removeExecutionContextPathComponentForFrame(frame); - }, - - _frameMainResourceChanged: function(event) - { - var frame = event.target; - this._updateExecutionContextPathComponentForFrame(frame); - }, - - _createExecutionContextPathComponent: function(name, identifier) - { - var pathComponent = new WebInspector.HierarchicalPathComponent(name, "execution-context", identifier, true, true); - pathComponent.addEventListener(WebInspector.HierarchicalPathComponent.Event.SiblingWasSelected, this._pathComponentSelected, this); - pathComponent.addEventListener(WebInspector.HierarchicalPathComponent.Event.Clicked, this._pathComponentClicked, this); - pathComponent.truncatedDisplayNameLength = 50; - pathComponent._executionContextIdentifier = identifier; - return pathComponent; - }, - - _createExecutionContextPathComponentFromFrame: function(frame) - { - var name = frame.name ? frame.name + " \u2014 " + frame.mainResource.displayName : frame.mainResource.displayName; - var identifier = WebInspector.ExecutionContext.supported() ? frame.pageExecutionContext.id : frame.id; - - var pathComponent = this._createExecutionContextPathComponent(name, identifier); - pathComponent._frame = frame; - - return pathComponent; - }, - - _compareExecutionContextPathComponents: function(a, b) - { - // "Main Frame" always on top. - if (!a._frame) - return -1; - if (!b._frame) - return 1; - - // Frames with a name above frames without a name. - if (a._frame.name && !b._frame.name) - return -1; - if (!a._frame.name && b._frame.name) - return 1; - - return a.displayName.localeCompare(b.displayName); - }, - - _insertExecutionContextPathComponentForFrame: function(frame, skipRebuild) - { - if (frame.isMainFrame()) - return; - - console.assert(!this._frameIdentifierToExecutionContextPathComponentMap[frame.id]); - if (this._frameIdentifierToExecutionContextPathComponentMap[frame.id]) - return; - - var executionContextPathComponent = this._createExecutionContextPathComponentFromFrame(frame); - - var index = insertionIndexForObjectInListSortedByFunction(executionContextPathComponent, this._otherExecutionContextPathComponents, this._compareExecutionContextPathComponents); - - var prev = index > 0 ? this._otherExecutionContextPathComponents[index - 1] : this._mainFrameExecutionContextPathComponent; - var next = this._otherExecutionContextPathComponents[index] || null; - if (prev) { - prev.nextSibling = executionContextPathComponent; - executionContextPathComponent.previousSibling = prev; - } - if (next) { - next.previousSibling = executionContextPathComponent; - executionContextPathComponent.nextSibling = next; - } - - this._otherExecutionContextPathComponents.splice(index, 0, executionContextPathComponent); - this._frameIdentifierToExecutionContextPathComponentMap[frame.id] = executionContextPathComponent; - - if (!skipRebuild) - this._rebuildExecutionContextPathComponents(); - - return executionContextPathComponent; - }, - - _removeExecutionContextPathComponentForFrame: function(frame, skipRebuild) - { - if (frame.isMainFrame()) - return; - - var executionContextPathComponent = this._frameIdentifierToExecutionContextPathComponentMap[frame.id]; - console.assert(executionContextPathComponent); - if (!executionContextPathComponent) - return; - - executionContextPathComponent.removeEventListener(WebInspector.HierarchicalPathComponent.Event.SiblingWasSelected, this._pathComponentSelected, this); - executionContextPathComponent.removeEventListener(WebInspector.HierarchicalPathComponent.Event.Clicked, this._pathComponentClicked, this); - - var prev = executionContextPathComponent.previousSibling; - var next = executionContextPathComponent.nextSibling; - if (prev) - prev.nextSibling = next; - if (next) - next.previousSibling = prev; - - if (this._selectedExecutionContextPathComponent === executionContextPathComponent) - this._selectedExecutionContextPathComponent = this._mainFrameExecutionContextPathComponent; - - this._otherExecutionContextPathComponents.remove(executionContextPathComponent, true); - delete this._frameIdentifierToExecutionContextPathComponentMap[frame.id]; - - if (!skipRebuild) - this._rebuildExecutionContextPathComponents(); - }, - - _updateExecutionContextPathComponentForFrame: function(frame) - { - if (frame.isMainFrame()) - return; - - var executionContextPathComponent = this._frameIdentifierToExecutionContextPathComponentMap[frame.id]; - if (!executionContextPathComponent) - return; - - var wasSelected = this._selectedExecutionContextPathComponent === executionContextPathComponent; - - this._removeExecutionContextPathComponentForFrame(frame, true); - var newExecutionContextPathComponent = this._insertExecutionContextPathComponentForFrame(frame, true); - - if (wasSelected) - this._selectedExecutionContextPathComponent = newExecutionContextPathComponent; - - this._rebuildExecutionContextPathComponents(); - }, - - _pathComponentSelected: function(event) - { - if (event.data.pathComponent === this._selectedExecutionContextPathComponent) - return; - - this._selectedExecutionContextPathComponent = event.data.pathComponent; - - this._rebuildExecutionContextPathComponents(); - }, - - _pathComponentClicked: function(event) - { - this.prompt.focus(); - }, - - _debuggerActiveCallFrameDidChange: function(event) - { - this._rebuildExecutionContextPathComponents(); - }, - - _toggleOrFocus: function(event) - { - if (this.prompt.focused) - WebInspector.toggleSplitConsole(); - else if (!WebInspector.isEditingAnyField() && !WebInspector.isEventTargetAnEditableField(event)) - this.prompt.focus(); - } -}; - -WebInspector.QuickConsole.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/QuickConsoleNavigationBar.js b/Source/WebInspectorUI/UserInterface/QuickConsoleNavigationBar.js deleted file mode 100644 index 29108e7a9..000000000 --- a/Source/WebInspectorUI/UserInterface/QuickConsoleNavigationBar.js +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.QuickConsoleNavigationBar = function(element, navigationItems) -{ - WebInspector.NavigationBar.call(this, element, navigationItems); -}; - -WebInspector.QuickConsoleNavigationBar.prototype = { - constructor: WebInspector.QuickConsoleNavigationBar, - - get sizesToFit() - { - return true; - }, - - addNavigationItem: function(navigationItem) - { - // Add new navigation items to the left. - return this.insertNavigationItem(navigationItem, 0); - } -}; - -WebInspector.QuickConsoleNavigationBar.prototype.__proto__ = WebInspector.NavigationBar.prototype; diff --git a/Source/WebInspectorUI/UserInterface/RadioButtonNavigationItem.css b/Source/WebInspectorUI/UserInterface/RadioButtonNavigationItem.css deleted file mode 100644 index 6660361a5..000000000 --- a/Source/WebInspectorUI/UserInterface/RadioButtonNavigationItem.css +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.navigation-bar .item.radio.button:not(.text-only) { - width: 32px; -} - -.navigation-bar.collapsed .item.radio.button:not(.text-only) { - width: 24px; -} - -.navigation-bar .item.radio.button.text-only.selected { - background-repeat: no-repeat; - background-image: -webkit-linear-gradient(top, rgba(0, 0, 0, 0.15), rgba(0, 0, 0, 0.09) 12%, rgba(0, 0, 0, 0.06) 12%, transparent), -webkit-linear-gradient(top, rgba(0, 0, 0, 0.45), transparent), - -webkit-linear-gradient(top, rgba(0, 0, 0, 0.45), transparent); - background-size: 100% 100%, 1px 100%, 1px 100%; - background-position: left top, left top, right top; - - font-weight: bold; -} diff --git a/Source/WebInspectorUI/UserInterface/RadioButtonNavigationItem.js b/Source/WebInspectorUI/UserInterface/RadioButtonNavigationItem.js deleted file mode 100644 index ac82d99e1..000000000 --- a/Source/WebInspectorUI/UserInterface/RadioButtonNavigationItem.js +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.RadioButtonNavigationItem = function(identifier, toolTip, image, imageWidth, imageHeight) { - WebInspector.ButtonNavigationItem.call(this, identifier, toolTip, image, imageWidth, imageHeight, null, "tab"); -}; - -WebInspector.RadioButtonNavigationItem.StyleClassName = "radio"; -WebInspector.RadioButtonNavigationItem.ActiveStyleClassName = "active"; -WebInspector.RadioButtonNavigationItem.SelectedStyleClassName = "selected"; - -WebInspector.RadioButtonNavigationItem.prototype = { - constructor: WebInspector.RadioButtonNavigationItem, - - // Public - - get selected() - { - return this.element.classList.contains(WebInspector.RadioButtonNavigationItem.SelectedStyleClassName); - }, - - set selected(flag) - { - if (flag) { - this.element.classList.add(WebInspector.RadioButtonNavigationItem.SelectedStyleClassName); - this.element.setAttribute("aria-selected", "true"); - } else { - this.element.classList.remove(WebInspector.RadioButtonNavigationItem.SelectedStyleClassName); - this.element.setAttribute("aria-selected", "false"); - } - }, - - get active() - { - return this.element.classList.contains(WebInspector.RadioButtonNavigationItem.ActiveStyleClassName); - }, - - set active(flag) - { - if (flag) - this.element.classList.add(WebInspector.RadioButtonNavigationItem.ActiveStyleClassName); - else - this.element.classList.remove(WebInspector.RadioButtonNavigationItem.ActiveStyleClassName); - }, - - generateStyleText: function(parentSelector) - { - var classNames = this._classNames.join("."); - - // Default state. - var styleText = parentSelector + " ." + classNames + " > .glyph { background-image: -webkit-canvas(" + this._canvasIdentifier() + "); background-size: " + this._imageWidth + "px " + this._imageHeight + "px; }\n"; - - // Selected state. - styleText += parentSelector + " ." + classNames + ".selected:not(.disabled) > .glyph { background-image: -webkit-canvas(" + this._canvasIdentifier(WebInspector.ButtonNavigationItem.States.Focus) + "); }\n"; - - // Selected and pressed state. - styleText += parentSelector + " ." + classNames + ".selected:not(.disabled):active > .glyph { background-image: -webkit-canvas(" + this._canvasIdentifier(WebInspector.ButtonNavigationItem.States.ActiveFocus) + "); }\n"; - - return styleText; - }, - - updateLayout: function(expandOnly) - { - if (expandOnly) - return; - - var isSelected = this.selected; - - if (!isSelected) { - this.element.classList.add(WebInspector.RadioButtonNavigationItem.SelectedStyleClassName); - this.element.setAttribute("aria-selected", "true"); - } - - var selectedWidth = this.element.offsetWidth; - if (selectedWidth) - this.element.style.minWidth = selectedWidth + "px"; - - if (!isSelected) { - this.element.classList.remove(WebInspector.RadioButtonNavigationItem.SelectedStyleClassName); - this.element.setAttribute("aria-selected", "false"); - } - }, - - // Private - - _additionalClassNames: [WebInspector.RadioButtonNavigationItem.StyleClassName, WebInspector.ButtonNavigationItem.StyleClassName], -}; - -WebInspector.RadioButtonNavigationItem.prototype.__proto__ = WebInspector.ButtonNavigationItem.prototype; diff --git a/Source/WebInspectorUI/UserInterface/RemoteObject.js b/Source/WebInspectorUI/UserInterface/RemoteObject.js deleted file mode 100644 index 9a9a1d304..000000000 --- a/Source/WebInspectorUI/UserInterface/RemoteObject.js +++ /dev/null @@ -1,492 +0,0 @@ -/* - * Copyright (C) 2009 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/** - * @constructor - * @param {string|undefined} objectId - * @param {string} type - * @param {string|undefined} subtype - * @param {*} value - * @param {string=} description - */ -WebInspector.RemoteObject = function(objectId, type, subtype, value, description) -{ - this._type = type; - this._subtype = subtype; - if (objectId) { - // handle - this._objectId = objectId; - this._description = description; - this._hasChildren = true; - } else { - // Primitive or null object. - console.assert(type !== "object" || value === null); - this._description = description || (value + ""); - this._hasChildren = false; - this.value = value; - } -} - -/** - * @param {number|string|boolean} value - * @return {WebInspector.RemoteObject} - */ -WebInspector.RemoteObject.fromPrimitiveValue = function(value) -{ - return new WebInspector.RemoteObject(undefined, typeof value, undefined, value); -} - -/** - * @param {Object} value - * @return {WebInspector.RemoteObject} - */ -WebInspector.RemoteObject.fromLocalObject = function(value) -{ - return new WebInspector.LocalJSONObject(value); -} - -/** - * @param {WebInspector.DOMNode} node - * @param {string} objectGroup - * @param {function(?WebInspector.RemoteObject)} callback - */ -WebInspector.RemoteObject.resolveNode = function(node, objectGroup, callback) -{ - /** - * @param {?Protocol.Error} error - * @param {RuntimeAgent.RemoteObject} object - */ - function mycallback(error, object) - { - if (!callback) - return; - - if (error || !object) - callback(null); - else - callback(WebInspector.RemoteObject.fromPayload(object)); - } - DOMAgent.resolveNode(node.id, objectGroup, mycallback); -} - -/** - * @param {RuntimeAgent.RemoteObject} payload - * @return {WebInspector.RemoteObject} - */ -WebInspector.RemoteObject.fromPayload = function(payload) -{ - console.assert(typeof payload === "object", "Remote object payload should only be an object"); - - return new WebInspector.RemoteObject(payload.objectId, payload.type, payload.subtype, payload.value, payload.description); -} - -/** - * @param {WebInspector.RemoteObject} remoteObject - * @return {string} - */ -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.prototype = { - /** @return {RuntimeAgent.RemoteObjectId} */ - get objectId() - { - return this._objectId; - }, - - /** @return {string} */ - get type() - { - return this._type; - }, - - /** @return {string|undefined} */ - get subtype() - { - return this._subtype; - }, - - /** @return {string|undefined} */ - get description() - { - return this._description; - }, - - /** @return {boolean} */ - get hasChildren() - { - return this._hasChildren; - }, - - /** - * @param {function(Array.)} callback - */ - getOwnProperties: function(callback) - { - this._getProperties(true, callback); - }, - - /** - * @param {function(Array.)} callback - */ - getAllProperties: function(callback) - { - this._getProperties(false, callback); - }, - - /** - * @param {boolean} ownProperties - * @param {function(Array.)} callback - */ - _getProperties: function(ownProperties, callback) - { - if (!this._objectId) { - callback([]); - return; - } - - /** - * @param {?Protocol.Error} error - * @param {Array.} properties - */ - function remoteObjectBinder(error, properties) - { - if (error) { - callback(null); - return; - } - var result = []; - for (var i = 0; properties && i < properties.length; ++i) { - var property = properties[i]; - if (property.get || property.set) { - if (property.get) - result.push(new WebInspector.RemoteObjectProperty("get " + property.name, WebInspector.RemoteObject.fromPayload(property.get), property)); - if (property.set) - result.push(new WebInspector.RemoteObjectProperty("set " + property.name, WebInspector.RemoteObject.fromPayload(property.set), property)); - } else - result.push(new WebInspector.RemoteObjectProperty(property.name, WebInspector.RemoteObject.fromPayload(property.value), property)); - } - callback(result); - } - RuntimeAgent.getProperties(this._objectId, ownProperties, remoteObjectBinder); - }, - - /** - * @param {string} name - * @param {string} value - * @param {function(string=)} callback - */ - setPropertyValue: function(name, value, callback) - { - if (!this._objectId) { - callback("Can't set a property of non-object."); - return; - } - - RuntimeAgent.evaluate.invoke({expression:value, doNotPauseOnExceptionsAndMuteConsole:true}, evaluatedCallback.bind(this)); - - /** - * @param {?Protocol.Error} error - * @param {RuntimeAgent.RemoteObject} result - * @param {boolean=} wasThrown - */ - function evaluatedCallback(error, result, wasThrown) - { - if (error || wasThrown) { - callback(error || result.description); - return; - } - - function setPropertyValue(propertyName, propertyValue) - { - this[propertyName] = propertyValue; - } - - delete result.description; // Optimize on traffic. - RuntimeAgent.callFunctionOn(this._objectId, setPropertyValue.toString(), [{ value:name }, result], true, undefined, propertySetCallback.bind(this)); - if (result._objectId) - RuntimeAgent.releaseObject(result._objectId); - } - - /** - * @param {?Protocol.Error} error - * @param {RuntimeAgent.RemoteObject} result - * @param {boolean=} wasThrown - */ - function propertySetCallback(error, result, wasThrown) - { - if (error || wasThrown) { - callback(error || result.description); - return; - } - callback(); - } - }, - - /** - * @param {function(DOMAgent.NodeId)} callback - */ - pushNodeToFrontend: function(callback) - { - if (this._objectId) - WebInspector.domTreeManager.pushNodeToFrontend(this._objectId, callback); - else - callback(0); - }, - - /** - * @param {string} functionDeclaration - * @param {function(?WebInspector.RemoteObject)} callback - */ - callFunction: function(functionDeclaration, args, callback) - { - function mycallback(error, result, wasThrown) - { - callback((error || wasThrown) ? null : WebInspector.RemoteObject.fromPayload(result)); - } - - RuntimeAgent.callFunctionOn(this._objectId, functionDeclaration.toString(), args, true, undefined, mycallback); - }, - - /** - * @param {string} functionDeclaration - * @param {function(*)} callback - */ - callFunctionJSON: function(functionDeclaration, args, callback) - { - function mycallback(error, result, wasThrown) - { - callback((error || wasThrown) ? null : result.value); - } - - RuntimeAgent.callFunctionOn(this._objectId, functionDeclaration.toString(), args, true, true, mycallback); - }, - - release: function() - { - RuntimeAgent.releaseObject(this._objectId); - }, - - /** - * @return {number} - */ - arrayLength: function() - { - if (this.subtype !== "array") - return 0; - - var matches = this._description.match(/\[([0-9]+)\]/); - if (!matches) - return 0; - return parseInt(matches[1], 10); - } -} - -/** - * @constructor - * @param {string} name - * @param {WebInspector.RemoteObject} value - * @param {Object=} descriptor - */ -WebInspector.RemoteObjectProperty = function(name, value, descriptor) -{ - this.name = name; - this.value = value; - this.enumerable = descriptor ? !!descriptor.enumerable : true; - this.writable = descriptor ? !!descriptor.writable : true; - if (descriptor && descriptor.wasThrown) - this.wasThrown = true; -} - -/** - * @param {string} name - * @param {string} value - * @return {WebInspector.RemoteObjectProperty} - */ -WebInspector.RemoteObjectProperty.fromPrimitiveValue = function(name, value) -{ - return new WebInspector.RemoteObjectProperty(name, WebInspector.RemoteObject.fromPrimitiveValue(value)); -} - -// The below is a wrapper around a local object that provides an interface comaptible -// with RemoteObject, to be used by the UI code (primarily ObjectPropertiesSection). -// Note that only JSON-compliant objects are currently supported, as there's no provision -// for traversing prototypes, extracting class names via constuctor, handling properties -// or functions. - -/** - * @constructor - * @extends {WebInspector.RemoteObject} - * @param {Object} value - */ -WebInspector.LocalJSONObject = function(value) -{ - this._value = value; -} - -WebInspector.LocalJSONObject.prototype = { - /** - * @return {string} - */ - get description() - { - if (this._cachedDescription) - return this._cachedDescription; - - if (this.type === "object") { - switch (this.subtype) { - case "array": - function formatArrayItem(property) - { - return property.value.description; - } - this._cachedDescription = this._concatenate("[", "]", formatArrayItem); - break; - case "null": - this._cachedDescription = "null"; - break; - default: - function formatObjectItem(property) - { - return property.name + ":" + property.value.description; - } - this._cachedDescription = this._concatenate("{", "}", formatObjectItem); - } - } else - this._cachedDescription = String(this._value); - - return this._cachedDescription; - }, - - /** - * @param {string} prefix - * @param {string} suffix - * @return {string} - */ - _concatenate: function(prefix, suffix, formatProperty) - { - const previewChars = 100; - - var buffer = prefix; - var children = this._children(); - for (var i = 0; i < children.length; ++i) { - var itemDescription = formatProperty(children[i]); - if (buffer.length + itemDescription.length > previewChars) { - buffer += ",\u2026"; - break; - } - if (i) - buffer += ", "; - buffer += itemDescription; - } - buffer += suffix; - return buffer; - }, - - /** - * @return {string} - */ - get type() - { - return typeof this._value; - }, - - /** - * @return {string|undefined} - */ - get subtype() - { - if (this._value === null) - return "null"; - - if (this._value instanceof Array) - return "array"; - - return undefined; - }, - - /** - * @return {boolean} - */ - get hasChildren() - { - return typeof this._value === "object" && this._value !== null && !isEmptyObject(this._value); - }, - - /** - * @param {function(Array.)} callback - */ - getOwnProperties: function(callback) - { - callback(this._children()); - }, - - /** - * @param {function(Array.)} callback - */ - getAllProperties: function(callback) - { - callback(this._children()); - }, - - /** - * @return {Array.} - */ - _children: function() - { - if (!this.hasChildren) - return []; - - function buildProperty(propName) - { - return new WebInspector.RemoteObjectProperty(propName, new WebInspector.LocalJSONObject(this._value[propName])); - } - if (!this._cachedChildren) - this._cachedChildren = Object.keys(this._value || {}).map(buildProperty.bind(this)); - return this._cachedChildren; - }, - - /** - * @return {boolean} - */ - isError: function() - { - return false; - } -} diff --git a/Source/WebInspectorUI/UserInterface/Resource.js b/Source/WebInspectorUI/UserInterface/Resource.js deleted file mode 100644 index 019d53acd..000000000 --- a/Source/WebInspectorUI/UserInterface/Resource.js +++ /dev/null @@ -1,707 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.Resource = function(url, mimeType, type, loaderIdentifier, requestIdentifier, requestMethod, requestHeaders, requestData, requestSentTimestamp, initiatorSourceCodeLocation) -{ - WebInspector.SourceCode.call(this); - - console.assert(url); - - if (type in WebInspector.Resource.Type) - type = WebInspector.Resource.Type[type]; - - this._url = url; - this._mimeType = mimeType; - this._type = type || WebInspector.Resource.Type.fromMIMEType(mimeType); - this._loaderIdentifier = loaderIdentifier || null; - this._requestIdentifier = requestIdentifier || null; - this._requestMethod = requestMethod || null; - this._requestData = requestData || null; - this._requestHeaders = requestHeaders || {}; - this._responseHeaders = {}; - this._parentFrame = null; - this._initiatorSourceCodeLocation = initiatorSourceCodeLocation || null; - this._requestSentTimestamp = requestSentTimestamp || NaN; - this._responseReceivedTimestamp = NaN; - this._lastRedirectReceivedTimestamp = NaN; - this._lastDataReceivedTimestamp = NaN; - this._finishedOrFailedTimestamp = NaN; - this._size = NaN; - this._transferSize = NaN; - this._cached = false; -}; - -WebInspector.Object.addConstructorFunctions(WebInspector.Resource); - -WebInspector.Resource.TypeIdentifier = "resource"; -WebInspector.Resource.URLCookieKey = "resource-url"; -WebInspector.Resource.MainResourceCookieKey = "resource-is-main-resource"; - -WebInspector.Resource.Event = { - URLDidChange: "resource-url-did-change", - MIMETypeDidChange: "resource-mime-type-did-change", - TypeDidChange: "resource-type-did-change", - RequestHeadersDidChange: "resource-request-headers-did-change", - ResponseReceived: "resource-response-received", - LoadingDidFinish: "resource-loading-did-finish", - LoadingDidFail: "resource-loading-did-fail", - TimestampsDidChange: "resource-timestamps-did-change", - SizeDidChange: "resource-size-did-change", - TransferSizeDidChange: "resource-transfer-size-did-change", - CacheStatusDidChange: "resource-cached-did-change" -}; - -// Keep these in sync with the "ResourceType" enum defined by the "Page" domain. -WebInspector.Resource.Type = { - Document: "resource-type-document", - Stylesheet: "resource-type-stylesheet", - Image: "resource-type-image", - Font: "resource-type-font", - Script: "resource-type-script", - XHR: "resource-type-xhr", - WebSocket: "resource-type-websocket", - Other: "resource-type-other" -}; - -// This MIME Type map is private, use WebInspector.Resource.Type.fromMIMEType(). -WebInspector.Resource.Type._mimeTypeMap = { - "text/html": WebInspector.Resource.Type.Document, - "text/xml": WebInspector.Resource.Type.Document, - "text/plain": WebInspector.Resource.Type.Document, - "application/xhtml+xml": WebInspector.Resource.Type.Document, - "image/svg+xml": WebInspector.Resource.Type.Document, - - "text/css": WebInspector.Resource.Type.Stylesheet, - "text/xsl": WebInspector.Resource.Type.Stylesheet, - "text/x-less": WebInspector.Resource.Type.Stylesheet, - "text/x-sass": WebInspector.Resource.Type.Stylesheet, - "text/x-scss": WebInspector.Resource.Type.Stylesheet, - - "application/pdf": WebInspector.Resource.Type.Image, - - "application/x-font-type1": WebInspector.Resource.Type.Font, - "application/x-font-ttf": WebInspector.Resource.Type.Font, - "application/x-font-woff": WebInspector.Resource.Type.Font, - "application/x-truetype-font": WebInspector.Resource.Type.Font, - - "text/javascript": WebInspector.Resource.Type.Script, - "text/ecmascript": WebInspector.Resource.Type.Script, - "application/javascript": WebInspector.Resource.Type.Script, - "application/ecmascript": WebInspector.Resource.Type.Script, - "application/x-javascript": WebInspector.Resource.Type.Script, - "application/json": WebInspector.Resource.Type.Script, - "application/x-json": WebInspector.Resource.Type.Script, - "text/x-javascript": WebInspector.Resource.Type.Script, - "text/x-json": WebInspector.Resource.Type.Script, - "text/javascript1.1": WebInspector.Resource.Type.Script, - "text/javascript1.2": WebInspector.Resource.Type.Script, - "text/javascript1.3": WebInspector.Resource.Type.Script, - "text/jscript": WebInspector.Resource.Type.Script, - "text/livescript": WebInspector.Resource.Type.Script, - "text/x-livescript": WebInspector.Resource.Type.Script, - "text/typescript": WebInspector.Resource.Type.Script, - "text/x-clojure": WebInspector.Resource.Type.Script, - "text/x-coffeescript": WebInspector.Resource.Type.Script -}; - -WebInspector.Resource.Type.fromMIMEType = function(mimeType) -{ - if (!mimeType) - return WebInspector.Resource.Type.Other; - - mimeType = parseMIMEType(mimeType).type; - - if (mimeType in WebInspector.Resource.Type._mimeTypeMap) - return WebInspector.Resource.Type._mimeTypeMap[mimeType]; - - if (mimeType.startsWith("image/")) - return WebInspector.Resource.Type.Image; - - if (mimeType.startsWith("font/")) - return WebInspector.Resource.Type.Font; - - return WebInspector.Resource.Type.Other; -}; - -WebInspector.Resource.Type.displayName = function(type, plural) -{ - switch(type) { - case WebInspector.Resource.Type.Document: - if (plural) - return WebInspector.UIString("Documents"); - return WebInspector.UIString("Document"); - case WebInspector.Resource.Type.Stylesheet: - if (plural) - return WebInspector.UIString("Stylesheets"); - return WebInspector.UIString("Stylesheet"); - case WebInspector.Resource.Type.Image: - if (plural) - return WebInspector.UIString("Images"); - return WebInspector.UIString("Image"); - case WebInspector.Resource.Type.Font: - if (plural) - return WebInspector.UIString("Fonts"); - return WebInspector.UIString("Font"); - case WebInspector.Resource.Type.Script: - if (plural) - return WebInspector.UIString("Scripts"); - return WebInspector.UIString("Script"); - case WebInspector.Resource.Type.XHR: - if (plural) - return WebInspector.UIString("XHRs"); - return WebInspector.UIString("XHR"); - case WebInspector.Resource.Type.WebSocket: - if (plural) - return WebInspector.UIString("Sockets"); - return WebInspector.UIString("Socket"); - case WebInspector.Resource.Type.Other: - return WebInspector.UIString("Other"); - default: - console.error("Unknown resource type: ", type); - return null; - } -}; - -WebInspector.Resource.prototype = { - constructor: WebInspector.Resource, - - // Public - - get url() - { - return this._url; - }, - - get urlComponents() - { - if (!this._urlComponents) - this._urlComponents = parseURL(this._url); - return this._urlComponents; - }, - - get displayName() - { - return WebInspector.displayNameForURL(this._url, this.urlComponents); - }, - - get initiatorSourceCodeLocation() - { - return this._initiatorSourceCodeLocation; - }, - - get type() - { - return this._type; - }, - - get mimeType() - { - return this._mimeType; - }, - - get mimeTypeComponents() - { - if (!this._mimeTypeComponents) - this._mimeTypeComponents = parseMIMEType(this._mimeType); - return this._mimeTypeComponents; - }, - - get syntheticMIMEType() - { - // Resources are often transferred with a MIME-type that doesn't match the purpose the - // resource was loaded for, which is what WebInspector.Resource.Type represents. - // This getter generates a MIME-type, if needed, that matches the resource type. - - // If the type matches the Resource.Type of the MIME-type, then return the actual MIME-type. - if (this._type === WebInspector.Resource.Type.fromMIMEType(this._mimeType)) - return this._mimeType; - - // Return the default MIME-types for the Resource.Type, since the current MIME-type - // does not match what is expected for the Resource.Type. - switch (this._type) { - case WebInspector.Resource.Type.Document: - return "text/html"; - case WebInspector.Resource.Type.Stylesheet: - return "text/css"; - case WebInspector.Resource.Type.Script: - return "text/javascript"; - } - - // Return the actual MIME-type since we don't have a better synthesized one to return. - return this._mimeType; - }, - - get contentURL() - { - const maximumDataURLSize = 1024 * 1024; // 1 MiB - - // If content is not available or won't fit a data URL, fallback to using original URL. - var content = this.content; - if (content === null || content.length > maximumDataURLSize) - return this._url; - - return "data:" + this.mimeTypeComponents.type + (this.contentIsBase64Encoded ? ";base64," + content : "," + encodeURIComponent(content)); - }, - - isMainResource: function() - { - return this._parentFrame ? this._parentFrame.mainResource === this : false; - }, - - get parentFrame() - { - return this._parentFrame; - }, - - get loaderIdentifier() - { - return this._loaderIdentifier; - }, - - get requestIdentifier() - { - return this._requestIdentifier; - }, - - get finished() - { - return this._finished; - }, - - get failed() - { - return this._failed; - }, - - get canceled() - { - return this._canceled; - }, - - get requestMethod() - { - return this._requestMethod; - }, - - get requestData() - { - return this._requestData; - }, - - get requestDataContentType() - { - return this._requestHeaders.valueForCaseInsensitiveKey("Content-Type") || null; - }, - - get requestHeaders() - { - return this._requestHeaders; - }, - - get responseHeaders() - { - return this._responseHeaders; - }, - - get requestSentTimestamp() - { - return this._requestSentTimestamp; - }, - - get lastRedirectReceivedTimestamp() - { - return this._lastRedirectReceivedTimestamp; - }, - - get responseReceivedTimestamp() - { - return this._responseReceivedTimestamp; - }, - - get lastDataReceivedTimestamp() - { - return this._lastDataReceivedTimestamp; - }, - - get finishedOrFailedTimestamp() - { - return this._finishedOrFailedTimestamp; - }, - - get firstTimestamp() - { - return this.requestSentTimestamp || this.lastRedirectReceivedTimestamp || this.responseReceivedTimestamp || this.lastDataReceivedTimestamp || this.finishedOrFailedTimestamp; - }, - - get lastTimestamp() - { - return this.finishedOrFailedTimestamp || this.lastDataReceivedTimestamp || this.responseReceivedTimestamp || this.lastRedirectReceivedTimestamp || this.requestSentTimestamp; - }, - - get duration() - { - return this._finishedOrFailedTimestamp - this._requestSentTimestamp; - }, - - get latency() - { - return this._responseReceivedTimestamp - this._requestSentTimestamp; - }, - - get receiveDuration() - { - return this._finishedOrFailedTimestamp - this._responseReceivedTimestamp; - }, - - get cached() - { - return this._cached; - }, - - get statusCode() - { - return this._statusCode; - }, - - get statusText() - { - return this._statusText; - }, - - get size() - { - return this._size; - }, - - get encodedSize() - { - if (!isNaN(this._transferSize)) - return this._transferSize; - - // If we did not receive actual transfer size from network - // stack, we prefer using Content-Length over resourceSize as - // resourceSize may differ from actual transfer size if platform's - // network stack performed decoding (e.g. gzip decompression). - // The Content-Length, though, is expected to come from raw - // response headers and will reflect actual transfer length. - // This won't work for chunked content encoding, so fall back to - // resourceSize when we don't have Content-Length. This still won't - // work for chunks with non-trivial encodings. We need a way to - // get actual transfer size from the network stack. - - return Number(this._responseHeaders.valueForCaseInsensitiveKey("Content-Length") || this._size); - }, - - get transferSize() - { - if (this.statusCode === 304) // Not modified - return this._responseHeadersSize; - - if (this._cached) - return 0; - - return this._responseHeadersSize + this.encodedSize; - }, - - get compressed() - { - var contentEncoding = this._responseHeaders.valueForCaseInsensitiveKey("Content-Encoding"); - return contentEncoding && /\b(?:gzip|deflate)\b/.test(contentEncoding); - }, - - get scripts() - { - return this._scripts || []; - }, - - scriptForLocation: function(sourceCodeLocation) - { - console.assert(!(this instanceof WebInspector.SourceMapResource)); - console.assert(sourceCodeLocation.sourceCode === this, "SourceCodeLocation must be in this Resource"); - if (sourceCodeLocation.sourceCode !== this) - return null; - - var lineNumber = sourceCodeLocation.lineNumber; - var columnNumber = sourceCodeLocation.columnNumber; - for (var i = 0; i < this._scripts.length; ++i) { - var script = this._scripts[i]; - if (script.range.startLine <= lineNumber && script.range.endLine >= lineNumber) { - if (script.range.startLine === lineNumber && columnNumber < script.range.startColumn) - continue; - if (script.range.endLine === lineNumber && columnNumber > script.range.endColumn) - continue; - return script; - } - } - - return null; - }, - - updateForRedirectResponse: function(url, requestHeaders, timestamp) - { - console.assert(!this._finished); - console.assert(!this._failed); - console.assert(!this._canceled); - - var oldURL = this._url; - - this._url = url; - this._requestHeaders = requestHeaders || {}; - this._lastRedirectReceivedTimestamp = timestamp || NaN; - - if (oldURL !== url) { - // Delete the URL components so the URL is re-parsed the next time it is requested. - delete this._urlComponents; - - this.dispatchEventToListeners(WebInspector.Resource.Event.URLDidChange, {oldURL: oldURL}); - } - - this.dispatchEventToListeners(WebInspector.Resource.Event.RequestHeadersDidChange); - this.dispatchEventToListeners(WebInspector.Resource.Event.TimestampsDidChange); - }, - - updateForResponse: function(url, mimeType, type, responseHeaders, statusCode, statusText, timestamp) - { - console.assert(!this._finished); - console.assert(!this._failed); - console.assert(!this._canceled); - - var oldURL = this._url; - var oldMIMEType = this._mimeType; - var oldType = this._type; - - if (type in WebInspector.Resource.Type) - type = WebInspector.Resource.Type[type]; - - this._url = url; - this._mimeType = mimeType; - this._type = type || WebInspector.Resource.Type.fromMIMEType(mimeType); - this._statusCode = statusCode; - this._statusText = statusText; - this._responseHeaders = responseHeaders || {}; - this._responseReceivedTimestamp = timestamp || NaN; - - this._responseHeadersSize = String(this._statusCode).length + this._statusText.length + 12; // Extra length is for "HTTP/1.1 ", " ", and "\r\n". - for (var name in this._responseHeaders) - this._responseHeadersSize += name.length + this._responseHeaders[name].length + 4; // Extra length is for ": ", and "\r\n". - - if (statusCode === 304 && !this._cached) - this.markAsCached(); - - if (oldURL !== url) { - // Delete the URL components so the URL is re-parsed the next time it is requested. - delete this._urlComponents; - - this.dispatchEventToListeners(WebInspector.Resource.Event.URLDidChange, {oldURL: oldURL}); - } - - if (oldMIMEType !== mimeType) { - // Delete the MIME-type components so the MIME-type is re-parsed the next time it is requested. - delete this._mimeTypeComponents; - - this.dispatchEventToListeners(WebInspector.Resource.Event.MIMETypeDidChange, {oldMIMEType: oldMIMEType}); - } - - if (oldType !== type) - this.dispatchEventToListeners(WebInspector.Resource.Event.TypeDidChange, {oldType: oldType}); - - console.assert(isNaN(this._size)); - console.assert(isNaN(this._transferSize)); - - // The transferSize becomes 0 when status is 304 or Content-Length is available, so - // notify listeners of that change. - if (statusCode === 304 || this._responseHeaders.valueForCaseInsensitiveKey("Content-Length")) - this.dispatchEventToListeners(WebInspector.Resource.Event.TransferSizeDidChange); - - this.dispatchEventToListeners(WebInspector.Resource.Event.ResponseReceived); - this.dispatchEventToListeners(WebInspector.Resource.Event.TimestampsDidChange); - }, - - canRequestContentFromBackend: function() - { - return this._finished; - }, - - requestContentFromBackend: function(callback) - { - // If we have the requestIdentifier we can get the actual response for this specific resource. - // Otherwise the content will be cached resource data, which might not exist anymore. - if (this._requestIdentifier) { - NetworkAgent.getResponseBody(this._requestIdentifier, callback); - return true; - } - - if (this._parentFrame) { - PageAgent.getResourceContent(this._parentFrame.id, this._url, callback); - return true; - } - - // There is no request identifier or frame to request content from. Return false to cause the - // pending callbacks to get null content. - return false; - }, - - increaseSize: function(dataLength, timestamp) - { - console.assert(dataLength >= 0); - - if (isNaN(this._size)) - this._size = 0; - - var previousSize = this._size; - - this._size += dataLength; - - this._lastDataReceivedTimestamp = timestamp || NaN; - - this.dispatchEventToListeners(WebInspector.Resource.Event.SizeDidChange, {previousSize: previousSize}); - - // The transferSize is based off of size when status is not 304 or Content-Length is missing. - if (isNaN(this._transferSize) && this._statusCode !== 304 && !this._responseHeaders.valueForCaseInsensitiveKey("Content-Length")) - this.dispatchEventToListeners(WebInspector.Resource.Event.TransferSizeDidChange); - }, - - increaseTransferSize: function(encodedDataLength) - { - console.assert(encodedDataLength >= 0); - - if (isNaN(this._transferSize)) - this._transferSize = 0; - this._transferSize += encodedDataLength; - - this.dispatchEventToListeners(WebInspector.Resource.Event.TransferSizeDidChange); - }, - - markAsCached: function() - { - this._cached = true; - - this.dispatchEventToListeners(WebInspector.Resource.Event.CacheStatusDidChange); - - // The transferSize is starts returning 0 when cached is true, unless status is 304. - if (this._statusCode !== 304) - this.dispatchEventToListeners(WebInspector.Resource.Event.TransferSizeDidChange); - }, - - markAsFinished: function(timestamp) - { - console.assert(!this._failed); - console.assert(!this._canceled); - - this._finished = true; - this._finishedOrFailedTimestamp = timestamp || NaN; - - this.dispatchEventToListeners(WebInspector.Resource.Event.LoadingDidFinish); - this.dispatchEventToListeners(WebInspector.Resource.Event.TimestampsDidChange); - - if (this.canRequestContentFromBackend()) - this.requestContentFromBackendIfNeeded(); - }, - - markAsFailed: function(canceled, timestamp) - { - console.assert(!this._finished); - - this._failed = true; - this._canceled = canceled; - this._finishedOrFailedTimestamp = timestamp || NaN; - - this.dispatchEventToListeners(WebInspector.Resource.Event.LoadingDidFail); - this.dispatchEventToListeners(WebInspector.Resource.Event.TimestampsDidChange); - - // Force the content requests to be serviced. They will get null as the content. - this.servicePendingContentRequests(true); - }, - - revertMarkAsFinished: function(timestamp) - { - console.assert(!this._failed); - console.assert(!this._canceled); - console.assert(this._finished); - - this._finished = false; - this._finishedOrFailedTimestamp = NaN; - }, - - getImageSize: function(callback) - { - // Throw an error in the case this resource is not an image. - if (this.type !== WebInspector.Resource.Type.Image) - throw "Resource is not an image."; - - // See if we've already computed and cached the image size, - // in which case we can provide them directly. - if (this._imageSize) { - callback(this._imageSize); - return; - } - - // Event handler for the image "load" event. - function imageDidLoad() - { - // Cache the image metrics. - this._imageSize = { - width: image.width, - height: image.height - }; - - callback(this._imageSize); - }; - - // Create an element that we'll use to load the image resource - // so that we can query its intrinsic size. - var image = new Image; - image.addEventListener("load", imageDidLoad.bind(this), false); - - // Set the image source once we've obtained the base64-encoded URL for it. - this.requestContent(function() { - image.src = this.contentURL; - }.bind(this)); - }, - - associateWithScript: function(script) - { - if (!this._scripts) - this._scripts = [] - - this._scripts.push(script); - - // COMPATIBILITY (iOS 6): Resources did not know their type until a response - // was received. We can set the Resource type to be Script here. - if (this._type === WebInspector.Resource.Type.Other) { - var oldType = this._type; - this._type = WebInspector.Resource.Type.Script; - this.dispatchEventToListeners(WebInspector.Resource.Event.TypeDidChange, {oldType: oldType}); - } - }, - - saveIdentityToCookie: function(cookie) - { - cookie[WebInspector.Resource.URLCookieKey] = this.url; - cookie[WebInspector.Resource.MainResourceCookieKey] = this.isMainResource(); - } -}; - -WebInspector.Resource.prototype.__proto__ = WebInspector.SourceCode.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ResourceClusterContentView.js b/Source/WebInspectorUI/UserInterface/ResourceClusterContentView.js deleted file mode 100644 index fa542ac0d..000000000 --- a/Source/WebInspectorUI/UserInterface/ResourceClusterContentView.js +++ /dev/null @@ -1,272 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ResourceClusterContentView = function(resource) -{ - WebInspector.ClusterContentView.call(this, resource); - - this._resource = resource; - this._resource.addEventListener(WebInspector.Resource.Event.TypeDidChange, this._resourceTypeDidChange, this); - this._resource.addEventListener(WebInspector.Resource.Event.LoadingDidFinish, this._resourceLoadingDidFinish, this); - - function createPathComponent(displayName, className, identifier) - { - var pathComponent = new WebInspector.HierarchicalPathComponent(displayName, className, identifier, false, true); - pathComponent.addEventListener(WebInspector.HierarchicalPathComponent.Event.SiblingWasSelected, this._pathComponentSelected, this); - return pathComponent; - } - - this._requestPathComponent = createPathComponent.call(this, WebInspector.UIString("Request"), WebInspector.ResourceClusterContentView.RequestIconStyleClassName, WebInspector.ResourceClusterContentView.RequestIdentifier); - this._responsePathComponent = createPathComponent.call(this, WebInspector.UIString("Response"), WebInspector.ResourceClusterContentView.ResponseIconStyleClassName, WebInspector.ResourceClusterContentView.ResponseIdentifier); - - this._requestPathComponent.nextSibling = this._responsePathComponent; - this._responsePathComponent.previousSibling = this._requestPathComponent; - - this._currentContentViewSetting = new WebInspector.Setting("resource-current-view-" + this._resource.url.hash, WebInspector.ResourceClusterContentView.ResponseIdentifier); -}; - -WebInspector.ResourceClusterContentView.ContentViewIdentifierCookieKey = "resource-cluster-content-view-identifier"; - -WebInspector.ResourceClusterContentView.RequestIconStyleClassName = "request-icon"; -WebInspector.ResourceClusterContentView.ResponseIconStyleClassName = "response-icon"; -WebInspector.ResourceClusterContentView.RequestIdentifier = "request"; -WebInspector.ResourceClusterContentView.ResponseIdentifier = "response"; - -WebInspector.ResourceClusterContentView.prototype = { - constructor: WebInspector.ResourceClusterContentView, - - // Public - - get resource() - { - return this._resource; - }, - - get responseContentView() - { - if (this._responseContentView) - return this._responseContentView; - - switch (this._resource.type) { - case WebInspector.Resource.Type.Document: - case WebInspector.Resource.Type.Script: - case WebInspector.Resource.Type.Stylesheet: - case WebInspector.Resource.Type.XHR: - this._responseContentView = new WebInspector.TextResourceContentView(this._resource); - break; - - case WebInspector.Resource.Type.Image: - this._responseContentView = new WebInspector.ImageResourceContentView(this._resource); - break; - - case WebInspector.Resource.Type.Font: - this._responseContentView = new WebInspector.FontResourceContentView(this._resource); - break; - - default: - this._responseContentView = new WebInspector.GenericResourceContentView(this._resource); - break; - } - - return this._responseContentView; - }, - - get requestContentView() - { - if (!this._canShowRequestContentView()) - return null; - - if (this._requestContentView) - return this._requestContentView; - - this._requestContentView = new WebInspector.TextContentView(this._resource.requestData || "", this._resource.requestDataContentType); - - return this._requestContentView; - }, - - get selectionPathComponents() - { - var currentContentView = this._contentViewContainer.currentContentView; - if (!currentContentView) - return []; - - if (!this._canShowRequestContentView()) - return currentContentView.selectionPathComponents; - - // Append the current view's path components to the path component representing the current view. - var components = [this._pathComponentForContentView(currentContentView)]; - return components.concat(currentContentView.selectionPathComponents); - }, - - shown: function() - { - WebInspector.ClusterContentView.prototype.shown.call(this); - - if (this._shownInitialContent) - return; - - this._showContentViewForIdentifier(this._currentContentViewSetting.value); - }, - - closed: function() - { - WebInspector.ClusterContentView.prototype.closed.call(this); - - this._shownInitialContent = false; - }, - - saveToCookie: function(cookie) - { - cookie[WebInspector.ResourceClusterContentView.ContentViewIdentifierCookieKey] = this._currentContentViewSetting.value; - }, - - restoreFromCookie: function(cookie) - { - var contentView = this._showContentViewForIdentifier(cookie[WebInspector.ResourceClusterContentView.ContentViewIdentifierCookieKey]); - if (typeof contentView.revealPosition === "function" && "lineNumber" in cookie && "columnNumber" in cookie) - contentView.revealPosition(new WebInspector.SourceCodePosition(cookie.lineNumber, cookie.columnNumber)); - }, - - showRequest: function() - { - this._shownInitialContent = true; - - return this._showContentViewForIdentifier(WebInspector.ResourceClusterContentView.RequestIdentifier); - }, - - showResponse: function(positionToReveal, textRangeToSelect, forceUnformatted) - { - this._shownInitialContent = true; - - if (!this._resource.finished) { - this._positionToReveal = positionToReveal; - this._textRangeToSelect = textRangeToSelect; - this._forceUnformatted = forceUnformatted; - } - - var responseContentView = this._showContentViewForIdentifier(WebInspector.ResourceClusterContentView.ResponseIdentifier); - if (typeof responseContentView.revealPosition === "function") - responseContentView.revealPosition(positionToReveal, textRangeToSelect, forceUnformatted); - return responseContentView; - }, - - // Private - - _canShowRequestContentView: function() - { - var requestData = this._resource.requestData; - if (!requestData) - return false; - - var requestDataContentType = this._resource.requestDataContentType; - if (requestDataContentType && requestDataContentType.match(/^application\/x-www-form-urlencoded\s*(;.*)?$/i)) - return false; - - return true; - }, - - _pathComponentForContentView: function(contentView) - { - console.assert(contentView); - if (!contentView) - return null; - if (contentView === this._requestContentView) - return this._requestPathComponent; - if (contentView === this._responseContentView) - return this._responsePathComponent; - console.error("Unknown contentView."); - return null; - }, - - _identifierForContentView: function(contentView) - { - console.assert(contentView); - if (!contentView) - return null; - if (contentView === this._requestContentView) - return WebInspector.ResourceClusterContentView.RequestIdentifier; - if (contentView === this._responseContentView) - return WebInspector.ResourceClusterContentView.ResponseIdentifier; - console.error("Unknown contentView."); - return null; - }, - - _showContentViewForIdentifier: function(identifier) - { - var contentViewToShow = null; - - switch (identifier) { - case WebInspector.ResourceClusterContentView.RequestIdentifier: - contentViewToShow = this._canShowRequestContentView() ? this.requestContentView : null; - break; - case WebInspector.ResourceClusterContentView.ResponseIdentifier: - contentViewToShow = this.responseContentView; - break; - } - - if (!contentViewToShow) - contentViewToShow = this.responseContentView; - - console.assert(contentViewToShow); - - this._currentContentViewSetting.value = this._identifierForContentView(contentViewToShow); - - return this.contentViewContainer.showContentView(contentViewToShow); - }, - - _pathComponentSelected: function(event) - { - this._showContentViewForIdentifier(event.data.pathComponent.representedObject); - }, - - _resourceTypeDidChange: function(event) - { - // Since resource views are based on the type, we need to make a new content view and tell the container to replace this - // content view with the new one. Make a new ResourceContentView which will use the new resource type to make the correct - // concrete ResourceContentView subclass. - - var currentResponseContentView = this._responseContentView; - if (!currentResponseContentView) - return; - - delete this._responseContentView; - - this.contentViewContainer.replaceContentView(currentResponseContentView, this.responseContentView); - }, - - _resourceLoadingDidFinish: function(event) - { - if ("_positionToReveal" in this) { - if (this._contentViewContainer.currentContentView === this._responseContentView) - this._responseContentView.revealPosition(this._positionToReveal, this._textRangeToSelect, this._forceUnformatted); - - delete this._positionToReveal; - delete this._textRangeToSelect; - delete this._forceUnformatted; - } - } -}; - -WebInspector.ResourceClusterContentView.prototype.__proto__ = WebInspector.ClusterContentView.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ResourceCollection.js b/Source/WebInspectorUI/UserInterface/ResourceCollection.js deleted file mode 100644 index e68334a8e..000000000 --- a/Source/WebInspectorUI/UserInterface/ResourceCollection.js +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ResourceCollection = function() -{ - WebInspector.Object.call(this); - - this._resources = []; - this._resourceURLMap = {}; - this._resourcesTypeMap = {}; -}; - -WebInspector.ResourceCollection.prototype = { - constructor: WebInspector.ResourceCollection, - - // Public - - get resources() - { - return this._resources; - }, - - resourceForURL: function(url) - { - return this._resourceURLMap[url] || null; - }, - - resourcesWithType: function(type) - { - return this._resourcesTypeMap[type] || []; - }, - - addResource: function(resource) - { - console.assert(resource instanceof WebInspector.Resource); - if (!(resource instanceof WebInspector.Resource)) - return; - - this._associateWithResource(resource); - }, - - removeResource: function(resourceOrURL) - { - console.assert(resourceOrURL); - - if (resourceOrURL instanceof WebInspector.Resource) - var url = resourceOrURL.url; - else - var url = resourceOrURL; - - // Fetch the resource by URL even if we were passed a WebInspector.Resource. - // We do this incase the WebInspector.Resource is a new object that isn't in _resources, - // but the URL is a valid resource. - var resource = this.resourceForURL(url); - console.assert(resource instanceof WebInspector.Resource); - if (!(resource instanceof WebInspector.Resource)) - return null; - - this._disassociateWithResource(resource); - - return resource; - }, - - removeAllResources: function() - { - if (!this._resources.length) - return; - - for (var i = 0; i < this._resources.length; ++i) - this._disassociateWithResource(this._resources[i], true); - - this._resources = []; - this._resourceURLMap = {}; - this._resourcesTypeMap = {}; - }, - - // Private - - _associateWithResource: function(resource) - { - this._resources.push(resource); - this._resourceURLMap[resource.url] = resource; - - if (!this._resourcesTypeMap[resource.type]) - this._resourcesTypeMap[resource.type] = []; - this._resourcesTypeMap[resource.type].push(resource); - - resource.addEventListener(WebInspector.Resource.Event.URLDidChange, this._resourceURLDidChange, this); - resource.addEventListener(WebInspector.Resource.Event.TypeDidChange, this._resourceTypeDidChange, this); - }, - - _disassociateWithResource: function(resource, skipRemoval) - { - if (skipRemoval) { - this._resources.remove(resource); - if (this._resourcesTypeMap[resource.type]) - this._resourcesTypeMap[resource.type].remove(resource); - delete this._resourceURLMap[resource.url]; - } - - resource.removeEventListener(WebInspector.Resource.Event.URLDidChange, this._resourceURLDidChange, this); - resource.removeEventListener(WebInspector.Resource.Event.TypeDidChange, this._resourceTypeDidChange, this); - }, - - _resourceURLDidChange: function(event) - { - var resource = event.target; - console.assert(resource instanceof WebInspector.Resource); - if (!(resource instanceof WebInspector.Resource)) - return; - - var oldURL = event.data.oldURL; - console.assert(oldURL); - if (!oldURL) - return; - - this._resourceURLMap[resource.url] = resource; - delete this._resourceURLMap[oldURL]; - }, - - _resourceTypeDidChange: function(event) - { - var resource = event.target; - console.assert(resource instanceof WebInspector.Resource); - if (!(resource instanceof WebInspector.Resource)) - return; - - var oldType = event.data.oldType; - console.assert(oldType); - if (!oldType) - return; - - if (!this._resourcesTypeMap[resource.type]) - this._resourcesTypeMap[resource.type] = []; - this._resourcesTypeMap[resource.type].push(resource); - - if (this._resourcesTypeMap[oldType]) - this._resourcesTypeMap[oldType].remove(resource); - } -}; - -WebInspector.ResourceCollection.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ResourceContentView.js b/Source/WebInspectorUI/UserInterface/ResourceContentView.js deleted file mode 100644 index 0b994adfd..000000000 --- a/Source/WebInspectorUI/UserInterface/ResourceContentView.js +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ResourceContentView = function(resource, styleClassName) -{ - console.assert(resource); - console.assert(styleClassName); - - WebInspector.ContentView.call(this, resource); - - this._resource = resource; - - this.element.classList.add(WebInspector.ResourceContentView.StyleClassName); - this.element.classList.add(styleClassName); - - // Append a spinner while waiting for contentAvailable. The subclasses are responsible for removing - // the spinner before showing the resource content. - var spinner = new WebInspector.IndeterminateProgressSpinner; - this.element.appendChild(spinner.element); - - this.element.addEventListener("click", this._mouseWasClicked.bind(this), false); - - // Request content last so the spinner will always be removed in case the content is immediately available. - resource.requestContent(this._contentAvailable.bind(this)); - - if (!this.managesOwnIssues) { - WebInspector.issueManager.addEventListener(WebInspector.IssueManager.Event.IssueWasAdded, this._issueWasAdded, this); - - var issues = WebInspector.issueManager.issuesForSourceCode(resource); - for (var i = 0; i < issues.length; ++i) - this.addIssue(issues[i]); - } -}; - -WebInspector.ResourceContentView.StyleClassName = "resource"; - -WebInspector.ResourceContentView.prototype = { - constructor: WebInspector.ResourceContentView, - - // Public - - get resource() - { - return this._resource; - }, - - contentAvailable: function(content, base64Encoded) - { - // Implemented by subclasses. - }, - - addIssue: function(issue) - { - // This generically shows only the last issue, subclasses can override for better handling. - this.element.removeChildren(); - this.element.appendChild(WebInspector.createMessageTextView(issue.text, issue.level === WebInspector.IssueMessage.Level.Error)); - }, - - closed: function() - { - if (!this.managesOwnIssues) - WebInspector.issueManager.removeEventListener(WebInspector.IssueManager.Event.IssueWasAdded, this._issueWasAdded, this); - }, - - // Private - - _contentAvailable: function(resource, content, base64Encoded) - { - // Check for failed loads. - if (this.resource.failed) { - // Don't show an error message if there is already an error message showing (like one added by addIssue.) - if (this.element.querySelector(".message-text-view.error")) - return; - - this.element.removeChildren(); - this.element.appendChild(WebInspector.createMessageTextView(WebInspector.UIString("An error occurred trying to load the resource."), true)); - return; - } - - // Content is ready to show, call the public method now. - this.contentAvailable(content, base64Encoded); - }, - - _issueWasAdded: function(event) - { - console.assert(!this.managesOwnIssues); - - var issue = event.data.issue; - - // FIXME: Check more than just the issue URL (the document could have multiple resources with the same URL). - if (issue.url !== this.resource.url) - return; - - this.addIssue(issue); - }, - - _mouseWasClicked: function(event) - { - WebInspector.handlePossibleLinkClick(event, this.resource.parentFrame); - } -}; - -WebInspector.ResourceContentView.prototype.__proto__ = WebInspector.ContentView.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ResourceDetailsSidebarPanel.js b/Source/WebInspectorUI/UserInterface/ResourceDetailsSidebarPanel.js deleted file mode 100644 index 885c8d1ba..000000000 --- a/Source/WebInspectorUI/UserInterface/ResourceDetailsSidebarPanel.js +++ /dev/null @@ -1,484 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ResourceDetailsSidebarPanel = function() { - WebInspector.DetailsSidebarPanel.call(this, "resource-details", WebInspector.UIString("Resource"), WebInspector.UIString("Resource"), "Images/NavigationItemFile.svg", "1"); - - this.element.classList.add(WebInspector.ResourceDetailsSidebarPanel.StyleClassName); - - this._resource = null; - - this._typeMIMETypeRow = new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("MIME Type")); - this._typeResourceTypeRow = new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("Resource Type")); - - this._typeSection = new WebInspector.DetailsSection("resource-type", WebInspector.UIString("Type")); - this._typeSection.groups = [new WebInspector.DetailsSectionGroup([this._typeMIMETypeRow, this._typeResourceTypeRow])]; - - this._locationFullURLRow = new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("Full URL")); - this._locationSchemeRow = new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("Scheme")); - this._locationHostRow = new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("Host")); - this._locationPortRow = new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("Port")); - this._locationPathRow = new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("Path")); - this._locationQueryStringRow = new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("Query String")); - this._locationFragmentRow = new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("Fragment")); - this._locationFilenameRow = new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("Filename")); - this._initiatorRow = new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("Initiator")); - - var firstGroup = [this._locationFullURLRow]; - var secondGroup = [this._locationSchemeRow, this._locationHostRow, this._locationPortRow, this._locationPathRow, - this._locationQueryStringRow, this._locationFragmentRow, this._locationFilenameRow]; - var thirdGroup = [this._initiatorRow]; - - this._fullURLGroup = new WebInspector.DetailsSectionGroup(firstGroup); - this._locationURLComponentsGroup = new WebInspector.DetailsSectionGroup(secondGroup); - this._initiatorGroup = new WebInspector.DetailsSectionGroup(thirdGroup); - - this._locationSection = new WebInspector.DetailsSection("resource-location", WebInspector.UIString("Location"), [this._fullURLGroup, this._locationURLComponentsGroup, this._initiatorGroup]); - - this._queryParametersRow = new WebInspector.DetailsSectionDataGridRow(null, WebInspector.UIString("No Query Parameters")); - this._queryParametersSection = new WebInspector.DetailsSection("resource-query-parameters", WebInspector.UIString("Query Parameters")); - this._queryParametersSection.groups = [new WebInspector.DetailsSectionGroup([this._queryParametersRow])]; - - this._requestDataSection = new WebInspector.DetailsSection("resource-request-data", WebInspector.UIString("Request Data")); - - this._requestMethodRow = new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("Method")); - this._cachedRow = new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("Cached")); - - this._statusTextRow = new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("Status")); - this._statusCodeRow = new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("Code")); - - this._encodedSizeRow = new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("Encoded")); - this._decodedSizeRow = new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("Decoded")); - this._transferSizeRow = new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("Transfered")); - - this._compressedRow = new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("Compressed")); - this._compressionRow = new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("Compression")); - - var requestGroup = new WebInspector.DetailsSectionGroup([this._requestMethodRow, this._cachedRow]); - var statusGroup = new WebInspector.DetailsSectionGroup([this._statusTextRow, this._statusCodeRow]); - var sizeGroup = new WebInspector.DetailsSectionGroup([this._encodedSizeRow, this._decodedSizeRow, this._transferSizeRow]); - var compressionGroup = new WebInspector.DetailsSectionGroup([this._compressedRow, this._compressionRow]); - - this._requestAndResponseSection = new WebInspector.DetailsSection("resource-request-response", WebInspector.UIString("Request & Response"), [requestGroup, statusGroup, sizeGroup, compressionGroup]); - - this._requestHeadersRow = new WebInspector.DetailsSectionDataGridRow(null, WebInspector.UIString("No Request Headers")); - this._requestHeadersSection = new WebInspector.DetailsSection("resource-request-headers", WebInspector.UIString("Request Headers")); - this._requestHeadersSection.groups = [new WebInspector.DetailsSectionGroup([this._requestHeadersRow])]; - - this._responseHeadersRow = new WebInspector.DetailsSectionDataGridRow(null, WebInspector.UIString("No Response Headers")); - this._responseHeadersSection = new WebInspector.DetailsSection("resource-response-headers", WebInspector.UIString("Response Headers")); - this._responseHeadersSection.groups = [new WebInspector.DetailsSectionGroup([this._responseHeadersRow])]; - - // Rows for the "Image Size" section. - this._imageWidthRow = new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("Width")); - this._imageHeightRow = new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("Height")); - - // "Image Size" section where we display intrinsic metrics for image resources. - this._imageSizeSection = new WebInspector.DetailsSection("resource-type", WebInspector.UIString("Image Size")); - this._imageSizeSection.groups = [new WebInspector.DetailsSectionGroup([this._imageWidthRow, this._imageHeightRow])]; - - this.element.appendChild(this._typeSection.element); - this.element.appendChild(this._locationSection.element); - this.element.appendChild(this._requestAndResponseSection.element); - this.element.appendChild(this._requestHeadersSection.element); - this.element.appendChild(this._responseHeadersSection.element); -}; - -WebInspector.ResourceDetailsSidebarPanel.StyleClassName = "resource"; - -WebInspector.ResourceDetailsSidebarPanel.prototype = { - constructor: WebInspector.ResourceDetailsSidebarPanel, - - // Public - - inspect: function(objects) - { - // Convert to a single item array if needed. - if (!(objects instanceof Array)) - objects = [objects]; - - var resourceToInspect = null; - - // Iterate over the objects to find a WebInspector.Resource to inspect. - for (var i = 0; i < objects.length; ++i) { - if (objects[i] instanceof WebInspector.Resource) { - resourceToInspect = objects[i]; - break; - } - - if (objects[i] instanceof WebInspector.Frame) { - resourceToInspect = objects[i].mainResource; - break; - } - } - - this.resource = resourceToInspect; - - return !!this._resource; - }, - - get resource() - { - return this._resource; - }, - - set resource(resource) - { - if (resource === this._resource) - return; - - if (this._resource) { - this._resource.removeEventListener(WebInspector.Resource.Event.URLDidChange, this._refreshURL, this); - this._resource.removeEventListener(WebInspector.Resource.Event.MIMETypeDidChange, this._refreshMIMEType, this); - this._resource.removeEventListener(WebInspector.Resource.Event.TypeDidChange, this._refreshResourceType, this); - this._resource.removeEventListener(WebInspector.Resource.Event.RequestHeadersDidChange, this._refreshRequestHeaders, this); - this._resource.removeEventListener(WebInspector.Resource.Event.ResponseReceived, this._refreshRequestAndResponse, this); - this._resource.removeEventListener(WebInspector.Resource.Event.CacheStatusDidChange, this._refreshRequestAndResponse, this); - this._resource.removeEventListener(WebInspector.Resource.Event.SizeDidChange, this._refreshDecodedSize, this); - this._resource.removeEventListener(WebInspector.Resource.Event.TransferSizeDidChange, this._refreshTransferSize, this); - } - - this._resource = resource; - - if (this._resource) { - this._resource.addEventListener(WebInspector.Resource.Event.URLDidChange, this._refreshURL, this); - this._resource.addEventListener(WebInspector.Resource.Event.MIMETypeDidChange, this._refreshMIMEType, this); - this._resource.addEventListener(WebInspector.Resource.Event.TypeDidChange, this._refreshResourceType, this); - this._resource.addEventListener(WebInspector.Resource.Event.RequestHeadersDidChange, this._refreshRequestHeaders, this); - this._resource.addEventListener(WebInspector.Resource.Event.ResponseReceived, this._refreshRequestAndResponse, this); - this._resource.addEventListener(WebInspector.Resource.Event.CacheStatusDidChange, this._refreshRequestAndResponse, this); - this._resource.addEventListener(WebInspector.Resource.Event.SizeDidChange, this._refreshDecodedSize, this); - this._resource.addEventListener(WebInspector.Resource.Event.TransferSizeDidChange, this._refreshTransferSize, this); - } - - this.needsRefresh(); - }, - - refresh: function() - { - if (!this._resource) - return; - - this._refreshURL(); - this._refreshMIMEType(); - this._refreshResourceType(); - this._refreshRequestAndResponse(); - this._refreshDecodedSize(); - this._refreshTransferSize(); - this._refreshRequestHeaders(); - this._refreshImageSizeSection(); - this._refreshRequestDataSection(); - }, - - // Private - - _refreshURL: function() - { - if (!this._resource) - return; - - this._locationFullURLRow.value = this._resource.url.insertWordBreakCharacters(); - - var urlComponents = this._resource.urlComponents; - if (urlComponents.scheme) { - if (this._resource.initiatorSourceCodeLocation) - this._locationSection.groups = [this._fullURLGroup, this._locationURLComponentsGroup, this._initiatorGroup]; - else - this._locationSection.groups = [this._fullURLGroup, this._locationURLComponentsGroup]; - - this._locationSchemeRow.value = urlComponents.scheme ? urlComponents.scheme : null; - this._locationHostRow.value = urlComponents.host ? urlComponents.host : null; - this._locationPortRow.value = urlComponents.port ? urlComponents.port : null; - this._locationPathRow.value = urlComponents.path ? urlComponents.path.insertWordBreakCharacters() : null; - this._locationQueryStringRow.value = urlComponents.queryString ? urlComponents.queryString.insertWordBreakCharacters() : null; - this._locationFragmentRow.value = urlComponents.fragment ? urlComponents.fragment.insertWordBreakCharacters() : null; - this._locationFilenameRow.value = urlComponents.lastPathComponent ? urlComponents.lastPathComponent.insertWordBreakCharacters() : null; - } else { - if (this._resource.initiatorSourceCodeLocation) - this._locationSection.groups = [this._fullURLGroup, this._initiatorGroup]; - else - this._locationSection.groups = [this._fullURLGroup]; - } - - if (this._resource.initiatorSourceCodeLocation) - this._initiatorRow.value = WebInspector.createSourceCodeLocationLink(this._resource.initiatorSourceCodeLocation, true); - - if (urlComponents.queryString) { - // Ensure the "Query Parameters" section is displayed, right after the "Request & Response" section. - this.element.insertBefore(this._queryParametersSection.element, this._requestAndResponseSection.element.nextSibling); - - this._queryParametersRow.dataGrid = this._createNameValueDataGrid(parseQueryString(urlComponents.queryString, true)); - } else { - // Hide the "Query Parameters" section if we don't have a query string. - var queryParametersSectionElement = this._queryParametersSection.element; - if (queryParametersSectionElement.parentNode) - queryParametersSectionElement.parentNode.removeChild(queryParametersSectionElement); - } - }, - - _refreshResourceType: function() - { - if (!this._resource) - return; - - this._typeResourceTypeRow.value = WebInspector.Resource.Type.displayName(this._resource.type); - }, - - _refreshMIMEType: function() - { - if (!this._resource) - return; - - this._typeMIMETypeRow.value = this._resource.mimeType; - }, - - _refreshRequestAndResponse: function() - { - var resource = this._resource; - if (!resource) - return; - - // If we don't have a value, we set an em-dash to keep the row from hiding. - // This keeps the UI from shifting around as data comes in. - const emDash = "\u2014"; - - this._requestMethodRow.value = resource.requestMethod || emDash; - - this._cachedRow.value = resource.cached ? WebInspector.UIString("Yes") : WebInspector.UIString("No"); - - this._statusCodeRow.value = resource.statusCode || emDash; - this._statusTextRow.value = resource.statusText || emDash; - - this._refreshResponseHeaders(); - this._refreshCompressed(); - }, - - _valueForSize: function(size) - { - // If we don't have a value, we set an em-dash to keep the row from hiding. - // This keeps the UI from shifting around as data comes in. - const emDash = "\u2014"; - return size > 0 ? Number.bytesToString(size) : emDash; - }, - - _refreshCompressed: function() - { - this._compressedRow.value = this._resource.compressed ? WebInspector.UIString("Yes") : WebInspector.UIString("No"); - this._compressionRow.value = this._resource.compressed ? WebInspector.UIString("%.2f\u00d7").format(this._resource.size / this._resource.encodedSize) : null; - }, - - _refreshDecodedSize: function() - { - if (!this._resource) - return; - - this._encodedSizeRow.value = this._valueForSize(this._resource.encodedSize); - this._decodedSizeRow.value = this._valueForSize(this._resource.size); - - this._refreshCompressed(); - }, - - _refreshTransferSize: function() - { - if (!this._resource) - return; - - this._encodedSizeRow.value = this._valueForSize(this._resource.encodedSize); - this._transferSizeRow.value = this._valueForSize(this._resource.transferSize); - - this._refreshCompressed(); - }, - - _refreshRequestHeaders: function() - { - if (!this._resource) - return; - - this._requestHeadersRow.dataGrid = this._createNameValueDataGrid(this._resource.requestHeaders); - }, - - _refreshResponseHeaders: function() - { - if (!this._resource) - return; - - this._responseHeadersRow.dataGrid = this._createNameValueDataGrid(this._resource.responseHeaders); - }, - - _createNameValueDataGrid: function(data) - { - if (!data || data instanceof Array ? !data.length : isEmptyObject(data)) - return null; - - var dataGrid = new WebInspector.DataGrid({ - name: {title: WebInspector.UIString("Name"), width: "30%", sortable: true}, - value: {title: WebInspector.UIString("Value"), sortable: true} - }); - - function addDataGridNode(nodeValue) - { - console.assert(typeof nodeValue.name === "string"); - console.assert(!nodeValue.value || typeof nodeValue.value === "string"); - - var node = new WebInspector.DataGridNode({name: nodeValue.name, value: nodeValue.value || ""}, false); - node.selectable = true; - dataGrid.appendChild(node); - } - - if (data instanceof Array) { - for (var i = 0; i < data.length; ++i) - addDataGridNode(data[i]); - } else { - for (var name in data) - addDataGridNode({name: name, value: data[name] || ""}); - } - - dataGrid.addEventListener(WebInspector.DataGrid.Event.SortChanged, sortDataGrid, this); - - function sortDataGrid() - { - var nodes = dataGrid.children.slice(); - var sortColumnIdentifier = dataGrid.sortColumnIdentifier; - var sortDirection = dataGrid.sortOrder === "ascending" ? 1 : -1; - - function comparator(a, b) - { - var item1 = a.data[sortColumnIdentifier]; - var item2 = b.data[sortColumnIdentifier]; - return sortDirection * item1.localeCompare(item2); - } - - nodes.sort(comparator); - - dataGrid.removeChildren(); - for (var i = 0; i < nodes.length; i++) - dataGrid.appendChild(nodes[i]); - } - - return dataGrid; - }, - - _refreshImageSizeSection: function() - { - var resource = this._resource; - - if (!resource) - return; - - // Hide the section if we're not dealing with an image or if the load failed. - if (resource.type !== WebInspector.Resource.Type.Image || resource.failed) { - var imageSectionElement = this._imageSizeSection.element; - if (imageSectionElement.parentNode) - this.element.removeChild(imageSectionElement); - return; - } - - // Ensure the section is displayed, right before the "Location" section. - this.element.insertBefore(this._imageSizeSection.element, this._locationSection.element); - - // Get the metrics for this resource and fill in the metrics rows with that information. - resource.getImageSize(function(size) { - this._imageWidthRow.value = WebInspector.UIString("%fpx").format(size.width); - this._imageHeightRow.value = WebInspector.UIString("%fpx").format(size.height); - }.bind(this)); - }, - - _goToRequestDataClicked: function() - { - WebInspector.resourceSidebarPanel.showResourceRequest(this._resource); - }, - - _refreshRequestDataSection: function() - { - var resource = this._resource; - - if (!resource) - return; - - // Hide the section if we're not dealing with a request with data. - var requestData = resource.requestData; - if (!requestData) { - this._requestDataSection.element.remove(); - return; - } - - // Ensure the section is displayed, right before the "Request Headers" section. - this.element.insertBefore(this._requestDataSection.element, this._requestHeadersSection.element); - - var requestDataContentType = resource.requestDataContentType || ""; - if (requestDataContentType && requestDataContentType.match(/^application\/x-www-form-urlencoded\s*(;.*)?$/i)) { - // Simple form data that should be parsable like a query string. - var parametersRow = new WebInspector.DetailsSectionDataGridRow(null, WebInspector.UIString("No Parameters")); - parametersRow.dataGrid = this._createNameValueDataGrid(parseQueryString(requestData, true)); - - this._requestDataSection.groups = [new WebInspector.DetailsSectionGroup([parametersRow])]; - return; - } - - // Not simple form data, so we can really only show the size and type here. - // FIXME: Add a go-to arrow here to show the data in the content browser. - - var mimeTypeComponents = parseMIMEType(requestDataContentType); - - var mimeType = mimeTypeComponents.type; - var boundary = mimeTypeComponents.boundary; - var encoding = mimeTypeComponents.encoding; - - var rows = []; - - var mimeTypeRow = new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("MIME Type")); - mimeTypeRow.value = mimeType; - rows.push(mimeTypeRow); - - if (boundary) { - var boundryRow = new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("Boundary")); - boundryRow.value = boundary; - rows.push(boundryRow); - } - - if (encoding) { - var encodingRow = new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("Encoding")); - encodingRow.value = encoding; - rows.push(encodingRow); - } - - var sizeValue = Number.bytesToString(requestData.length); - - var dataValue = document.createDocumentFragment(); - - dataValue.appendChild(document.createTextNode(sizeValue)); - - var goToButton = dataValue.appendChild(WebInspector.createGoToArrowButton()); - goToButton.addEventListener("click", this._goToRequestDataClicked.bind(this)); - - var dataRow = new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("Data")); - dataRow.value = dataValue; - rows.push(dataRow); - - this._requestDataSection.groups = [new WebInspector.DetailsSectionGroup(rows)]; - } -}; - -WebInspector.ResourceDetailsSidebarPanel.prototype.__proto__ = WebInspector.DetailsSidebarPanel.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ResourceIcons.css b/Source/WebInspectorUI/UserInterface/ResourceIcons.css deleted file mode 100644 index 584dc6162..000000000 --- a/Source/WebInspectorUI/UserInterface/ResourceIcons.css +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.resource-icon .icon { - content: -webkit-image-set(url(Images/DocumentGeneric.png) 1x, url(Images/DocumentGeneric@2x.png) 2x); -} - -.resource-icon.resource-type-document .icon { - content: -webkit-image-set(url(Images/DocumentMarkup.png) 1x, url(Images/DocumentMarkup@2x.png) 2x); -} - -.resource-icon.resource-type-image .icon { - content: -webkit-image-set(url(Images/DocumentImage.png) 1x, url(Images/DocumentImage@2x.png) 2x); -} - -.resource-icon.resource-type-font .icon { - content: -webkit-image-set(url(Images/DocumentFont.png) 1x, url(Images/DocumentFont@2x.png) 2x); -} - -.resource-icon.resource-type-stylesheet .icon { - content: -webkit-image-set(url(Images/DocumentCSS.png) 1x, url(Images/DocumentCSS@2x.png) 2x); -} - -.resource-icon.resource-type-script .icon { - content: -webkit-image-set(url(Images/DocumentJS.png) 1x, url(Images/DocumentJS@2x.png) 2x); -} - -.anonymous-script-icon .icon { - content: -webkit-image-set(url(Images/ClippingJS.png) 1x, url(Images/ClippingJS@2x.png) 2x); -} - -.source-map-resource.resource-icon .icon { - content: -webkit-image-set(url(Images/ClippingGeneric.png) 1x, url(Images/ClippingGeneric@2x.png) 2x); -} - -.source-map-resource.resource-icon.resource-type-stylesheet .icon { - content: -webkit-image-set(url(Images/ClippingCSS.png) 1x, url(Images/ClippingCSS@2x.png) 2x); -} - -.source-map-resource.resource-icon.resource-type-script .icon { - content: -webkit-image-set(url(Images/ClippingJS.png) 1x, url(Images/ClippingJS@2x.png) 2x); -} diff --git a/Source/WebInspectorUI/UserInterface/ResourceSearchMatchObject.js b/Source/WebInspectorUI/UserInterface/ResourceSearchMatchObject.js deleted file mode 100644 index e58dbd582..000000000 --- a/Source/WebInspectorUI/UserInterface/ResourceSearchMatchObject.js +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ResourceSearchMatchObject = function(resource, lineText, searchTerm, textRange) -{ - console.assert(resource instanceof WebInspector.Resource); - - WebInspector.Object.call(this); - - this._resource = resource; - this._lineText = lineText; - this._searchTerm = searchTerm; - this._sourceCodeTextRange = resource.createSourceCodeTextRange(textRange); -}; - -WebInspector.ResourceSearchMatchObject.ResourceMatchIconStyleClassName = "resource-match-icon"; - -WebInspector.ResourceSearchMatchObject.prototype = { - constructor: WebInspector.ResourceSearchMatchObject, - - get resource() - { - return this._resource; - }, - - get title() - { - return this._lineText; - }, - - get className() - { - return WebInspector.ResourceSearchMatchObject.ResourceMatchIconStyleClassName; - }, - - get searchTerm() - { - return this._searchTerm; - }, - - get sourceCodeTextRange() - { - return this._sourceCodeTextRange; - } -}; - -WebInspector.ResourceSearchMatchObject.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ResourceSidebarPanel.css b/Source/WebInspectorUI/UserInterface/ResourceSidebarPanel.css deleted file mode 100644 index 948071dcd..000000000 --- a/Source/WebInspectorUI/UserInterface/ResourceSidebarPanel.css +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.sidebar > .panel.resource > .content, -.sidebar > .panel.resource > .empty-content-placeholder { - top: 21px; -} - -.sidebar > .panel.resource > .search-bar { - position: absolute; - top: 0; - left: 0; - right: 0; - - display: -webkit-flex; - - box-shadow: inset rgba(255, 255, 255, 0.2) 0 1px 0; - - height: 21px; - - white-space: nowrap; - overflow: hidden; -} - -.sidebar > .panel.resource > .search-bar > input[type="search"] { - display: -webkit-flex; - -webkit-flex: 1; - - margin: 1px 6px; -} diff --git a/Source/WebInspectorUI/UserInterface/ResourceSidebarPanel.js b/Source/WebInspectorUI/UserInterface/ResourceSidebarPanel.js deleted file mode 100644 index dac5a5c6d..000000000 --- a/Source/WebInspectorUI/UserInterface/ResourceSidebarPanel.js +++ /dev/null @@ -1,813 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ResourceSidebarPanel = function() { - WebInspector.NavigationSidebarPanel.call(this, "resource", WebInspector.UIString("Resources"), "Images/NavigationItemStorage.svg", "1", true, false, true); - - var searchElement = document.createElement("div"); - searchElement.classList.add("search-bar"); - this.element.appendChild(searchElement); - - this._inputElement = document.createElement("input"); - this._inputElement.type = "search"; - this._inputElement.spellcheck = false; - this._inputElement.addEventListener("search", this._searchFieldChanged.bind(this)); - this._inputElement.addEventListener("input", this._searchFieldInput.bind(this)); - this._inputElement.setAttribute("results", 5); - this._inputElement.setAttribute("autosave", "inspector-search"); - this._inputElement.setAttribute("placeholder", WebInspector.UIString("Search Resource Content")); - searchElement.appendChild(this._inputElement); - - this.filterBar.placeholder = WebInspector.UIString("Filter Resource List"); - - this._waitingForInitialMainFrame = true; - this._lastSearchedPageSetting = new WebInspector.Setting("last-searched-page", null); - - this._searchQuerySetting = new WebInspector.Setting("search-sidebar-query", ""); - this._inputElement.value = this._searchQuerySetting.value; - - this._searchKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl | WebInspector.KeyboardShortcut.Modifier.Shift, "F", this._focusSearchField.bind(this)); - - this._localStorageRootTreeElement = null; - this._sessionStorageRootTreeElement = null; - - this._databaseRootTreeElement = null; - this._databaseHostTreeElementMap = {}; - - this._cookieStorageRootTreeElement = null; - - this._applicationCacheRootTreeElement = null; - this._applicationCacheURLTreeElementMap = {}; - - WebInspector.storageManager.addEventListener(WebInspector.StorageManager.Event.CookieStorageObjectWasAdded, this._cookieStorageObjectWasAdded, this); - WebInspector.storageManager.addEventListener(WebInspector.StorageManager.Event.DOMStorageObjectWasAdded, this._domStorageObjectWasAdded, this); - WebInspector.storageManager.addEventListener(WebInspector.StorageManager.Event.DOMStorageObjectWasInspected, this._domStorageObjectWasInspected, this); - WebInspector.storageManager.addEventListener(WebInspector.StorageManager.Event.DatabaseWasAdded, this._databaseWasAdded, this); - WebInspector.storageManager.addEventListener(WebInspector.StorageManager.Event.DatabaseWasInspected, this._databaseWasInspected, this); - WebInspector.storageManager.addEventListener(WebInspector.StorageManager.Event.Cleared, this._storageCleared, this); - - WebInspector.applicationCacheManager.addEventListener(WebInspector.ApplicationCacheManager.Event.FrameManifestAdded, this._frameManifestAdded, this); - WebInspector.applicationCacheManager.addEventListener(WebInspector.ApplicationCacheManager.Event.FrameManifestRemoved, this._frameManifestRemoved, this); - - WebInspector.frameResourceManager.addEventListener(WebInspector.FrameResourceManager.Event.MainFrameDidChange, this._mainFrameDidChange, this); - WebInspector.frameResourceManager.addEventListener(WebInspector.FrameResourceManager.Event.FrameWasAdded, this._frameWasAdded, this); - - WebInspector.domTreeManager.addEventListener(WebInspector.DOMTreeManager.Event.DOMNodeWasInspected, this._domNodeWasInspected, this); - - WebInspector.debuggerManager.addEventListener(WebInspector.DebuggerManager.Event.ScriptAdded, this._scriptWasAdded, this); - WebInspector.debuggerManager.addEventListener(WebInspector.DebuggerManager.Event.ScriptsCleared, this._scriptsCleared, this); - - this._resourcesContentTreeOutline = this.contentTreeOutline; - this._searchContentTreeOutline = this.createContentTreeOutline(); - - this._resourcesContentTreeOutline.onselect = this._treeElementSelected.bind(this); - this._searchContentTreeOutline.onselect = this._treeElementSelected.bind(this); - - this._resourcesContentTreeOutline.includeSourceMapResourceChildren = true; - - if (WebInspector.debuggableType === WebInspector.DebuggableType.JavaScript) - this._resourcesContentTreeOutline.element.classList.add(WebInspector.NavigationSidebarPanel.HideDisclosureButtonsStyleClassName); -}; - -WebInspector.ResourceSidebarPanel.prototype = { - constructor: WebInspector.ResourceSidebarPanel, - - // Public - - get contentTreeOutlineToAutoPrune() - { - return this._searchContentTreeOutline; - }, - - showMainFrameDOMTree: function(nodeToSelect, preventFocusChange) - { - var contentView = WebInspector.contentBrowser.contentViewForRepresentedObject(WebInspector.frameResourceManager.mainFrame); - contentView.showDOMTree(nodeToSelect, preventFocusChange); - WebInspector.contentBrowser.showContentView(contentView); - }, - - showMainFrameSourceCode: function() - { - var contentView = WebInspector.contentBrowser.contentViewForRepresentedObject(WebInspector.frameResourceManager.mainFrame); - contentView.showSourceCode(); - WebInspector.contentBrowser.showContentView(contentView); - }, - - showContentFlowDOMTree: function(contentFlow, nodeToSelect, preventFocusChange) - { - var contentView = WebInspector.contentBrowser.contentViewForRepresentedObject(contentFlow); - if (nodeToSelect) - contentView.selectAndRevealDOMNode(nodeToSelect, preventFocusChange); - WebInspector.contentBrowser.showContentView(contentView); - }, - - showSourceCodeForFrame: function(frameIdentifier, revealAndSelectTreeElement) - { - delete this._frameIdentifierToShowSourceCodeWhenAvailable; - - // We can't show anything until we have the main frame in the sidebar. - // Otherwise the path components in the navigation bar would be missing. - var frame = WebInspector.frameResourceManager.frameForIdentifier(frameIdentifier); - if (!frame || !this._mainFrameTreeElement) { - this._frameIdentifierToShowSourceCodeWhenAvailable = frameIdentifier; - return; - } - - var contentView = WebInspector.contentBrowser.contentViewForRepresentedObject(frame); - console.assert(contentView); - if (!contentView) - return; - - contentView.showSourceCode(); - WebInspector.contentBrowser.showContentView(contentView); - - if (revealAndSelectTreeElement) - this.treeElementForRepresentedObject(frame).revealAndSelect(true, true, true, true); - }, - - showSourceCode: function(sourceCode, positionToReveal, textRangeToSelect, forceUnformatted) - { - console.assert(!positionToReveal || positionToReveal instanceof WebInspector.SourceCodePosition, positionToReveal); - var representedObject = sourceCode; - - if (representedObject instanceof WebInspector.Script) { - // A script represented by a resource should always show the resource. - representedObject = representedObject.resource || representedObject; - } - - // A main resource is always represented by its parent frame. - if (representedObject instanceof WebInspector.Resource && representedObject.isMainResource()) - representedObject = representedObject.parentFrame; - - var cookie = positionToReveal ? {lineNumber: positionToReveal.lineNumber, columnNumber: positionToReveal.columnNumber} : {}; - WebInspector.contentBrowser.showContentViewForRepresentedObject(representedObject, cookie); - }, - - showSourceCodeLocation: function(sourceCodeLocation) - { - this.showSourceCode(sourceCodeLocation.displaySourceCode, sourceCodeLocation.displayPosition()); - }, - - showOriginalUnformattedSourceCodeLocation: function(sourceCodeLocation) - { - this.showSourceCode(sourceCodeLocation.sourceCode, sourceCodeLocation.position(), undefined, true); - }, - - showOriginalOrFormattedSourceCodeLocation: function(sourceCodeLocation) - { - this.showSourceCode(sourceCodeLocation.sourceCode, sourceCodeLocation.formattedPosition()); - }, - - showSourceCodeTextRange: function(sourceCodeTextRange) - { - var textRangeToSelect = sourceCodeTextRange.displayTextRange; - this.showSourceCode(sourceCodeTextRange.displaySourceCode, textRangeToSelect.startPosition(), textRangeToSelect); - }, - - showOriginalOrFormattedSourceCodeTextRange: function(sourceCodeTextRange) - { - var textRangeToSelect = sourceCodeTextRange.formattedTextRange; - this.showSourceCode(sourceCodeTextRange.sourceCode, textRangeToSelect.startPosition(), textRangeToSelect); - }, - - showResource: function(resource) - { - WebInspector.contentBrowser.showContentViewForRepresentedObject(resource.isMainResource() ? resource.parentFrame : resource); - }, - - showResourceRequest: function(resource) - { - var contentView = WebInspector.contentBrowser.contentViewForRepresentedObject(resource.isMainResource() ? resource.parentFrame : resource); - - if (contentView instanceof WebInspector.FrameContentView) - var resourceContentView = contentView.showResource(); - else if (contentView instanceof WebInspector.ResourceClusterContentView) - var resourceContentView = contentView; - - console.assert(resourceContentView instanceof WebInspector.ResourceClusterContentView); - if (!(resourceContentView instanceof WebInspector.ResourceClusterContentView)) - return; - - resourceContentView.showRequest(); - - WebInspector.contentBrowser.showContentView(contentView); - }, - - treeElementForRepresentedObject: function(representedObject) - { - // A custom implementation is needed for this since the frames are populated lazily. - - // The Frame is used as the representedObject instead of the main resource in our tree. - if (representedObject instanceof WebInspector.Resource && representedObject.parentFrame && representedObject.parentFrame.mainResource === representedObject) - representedObject = representedObject.parentFrame; - - function isAncestor(ancestor, resourceOrFrame) - { - // SourceMapResources are descendants of another SourceCode object. - if (resourceOrFrame instanceof WebInspector.SourceMapResource) { - if (resourceOrFrame.sourceMap.originalSourceCode === ancestor) - return true; - - // Not a direct ancestor, so check the ancestors of the parent SourceCode object. - resourceOrFrame = resourceOrFrame.sourceMap.originalSourceCode; - } - - var currentFrame = resourceOrFrame.parentFrame; - while (currentFrame) { - if (currentFrame === ancestor) - return true; - currentFrame = currentFrame.parentFrame; - } - - return false; - } - - function getParent(resourceOrFrame) - { - // SourceMapResources are descendants of another SourceCode object. - if (resourceOrFrame instanceof WebInspector.SourceMapResource) - return resourceOrFrame.sourceMap.originalSourceCode; - return resourceOrFrame.parentFrame; - } - - var treeElement = this._resourcesContentTreeOutline.findTreeElement(representedObject, isAncestor, getParent); - if (treeElement) - return treeElement; - - // Only special case Script objects. - if (!(representedObject instanceof WebInspector.Script)) { - console.error("Didn't find a TreeElement for a representedObject associated with the ResourceSidebarPanel."); - return null; - } - - // If the Script has a URL we should have found it earlier. - if (representedObject.url) { - console.error("Didn't find a ScriptTreeElement for a Script with a URL."); - return null; - } - - // Since the Script does not have a URL we consider it an 'anonymous' script. These scripts happen from calls to - // window.eval() or browser features like Auto Fill and Reader. They are not normally added to the sidebar, but since - // we have a ScriptContentView asking for the tree element we will make a ScriptTreeElement on demand and add it. - - if (!this._anonymousScriptsFolderTreeElement) - this._anonymousScriptsFolderTreeElement = new WebInspector.FolderTreeElement(WebInspector.UIString("Anonymous Scripts")); - - if (!this._anonymousScriptsFolderTreeElement.parent) { - var index = insertionIndexForObjectInListSortedByFunction(this._anonymousScriptsFolderTreeElement, this._resourcesContentTreeOutline.children, this._compareTreeElements); - this._resourcesContentTreeOutline.insertChild(this._anonymousScriptsFolderTreeElement, index); - } - - var scriptTreeElement = new WebInspector.ScriptTreeElement(representedObject); - this._anonymousScriptsFolderTreeElement.appendChild(scriptTreeElement); - - return scriptTreeElement; - }, - - performSearch: function(searchTerm) - { - // Before performing a new search, clear the old search. - this._searchContentTreeOutline.removeChildren(); - - this._inputElement.value = searchTerm; - this._searchQuerySetting.value = searchTerm; - this._lastSearchedPageSetting.value = searchTerm && WebInspector.frameResourceManager.mainFrame ? WebInspector.frameResourceManager.mainFrame.url.hash : null; - - this.hideEmptyContentPlaceholder(); - - searchTerm = searchTerm.trim(); - if (!searchTerm.length) { - this.filterBar.placeholder = WebInspector.UIString("Filter Resource List"); - this.contentTreeOutline = this._resourcesContentTreeOutline; - return; - } - - this.filterBar.placeholder = WebInspector.UIString("Filter Search Results"); - this.contentTreeOutline = this._searchContentTreeOutline; - - var updateEmptyContentPlaceholderTimeout = null; - - function updateEmptyContentPlaceholderSoon() - { - if (updateEmptyContentPlaceholderTimeout) - return; - updateEmptyContentPlaceholderTimeout = setTimeout(updateEmptyContentPlaceholder.bind(this), 100); - } - - function updateEmptyContentPlaceholder() - { - if (updateEmptyContentPlaceholderTimeout) { - clearTimeout(updateEmptyContentPlaceholderTimeout); - updateEmptyContentPlaceholderTimeout = null; - } - - this.updateEmptyContentPlaceholder(WebInspector.UIString("No Search Results")); - } - - function resourcesCallback(error, result) - { - updateEmptyContentPlaceholderSoon.call(this); - - if (error) - return; - - for (var i = 0; i < result.length; ++i) { - var searchResult = result[i]; - if (!searchResult.url || !searchResult.frameId) - continue; - - function resourceCallback(url, error, resourceMatches) - { - updateEmptyContentPlaceholderSoon.call(this); - - if (error || !resourceMatches || !resourceMatches.length) - return; - - var frame = WebInspector.frameResourceManager.frameForIdentifier(searchResult.frameId); - if (!frame) - return; - - var resource = frame.url === url ? frame.mainResource : frame.resourceForURL(url); - if (!resource) - return; - - var resourceTreeElement = this._searchTreeElementForResource(resource); - - for (var i = 0; i < resourceMatches.length; ++i) { - var match = resourceMatches[i]; - - var lineMatch; - var searchRegex = new RegExp(searchTerm.escapeForRegExp(), "gi"); - while ((searchRegex.lastIndex < match.lineContent.length) && (lineMatch = searchRegex.exec(match.lineContent))) { - var matchObject = new WebInspector.ResourceSearchMatchObject(resource, match.lineContent, searchTerm, new WebInspector.TextRange(match.lineNumber, lineMatch.index, match.lineNumber, searchRegex.lastIndex)); - var matchTreeElement = new WebInspector.SearchResultTreeElement(matchObject); - resourceTreeElement.appendChild(matchTreeElement); - } - } - - updateEmptyContentPlaceholder.call(this); - } - - PageAgent.searchInResource(searchResult.frameId, searchResult.url, searchTerm, false, false, resourceCallback.bind(this, searchResult.url)); - } - } - - function domCallback(error, searchId, resultsCount) - { - updateEmptyContentPlaceholderSoon.call(this); - - if (error || !resultsCount) - return; - - this._domSearchIdentifier = searchId; - - function domSearchResults(error, nodeIds) - { - updateEmptyContentPlaceholderSoon.call(this); - - if (error) - return; - - for (var i = 0; i < nodeIds.length; ++i) { - // If someone started a new search, then return early and stop showing seach results from the old query. - if (this._domSearchIdentifier !== searchId) - return; - - var domNode = WebInspector.domTreeManager.nodeForId(nodeIds[i]); - if (!domNode || !domNode.ownerDocument) - continue; - - // We do not display the document node when the search query is "/". We don't have anything to display in the content view for it. - if (domNode.nodeType() === Node.DOCUMENT_NODE) - continue; - - // FIXME: Use this should use a frame to do resourceForURL, but DOMAgent does not provide a frameId. - var resource = WebInspector.frameResourceManager.resourceForURL(domNode.ownerDocument.documentURL); - if (!resource) - continue; - - var resourceTreeElement = this._searchTreeElementForResource(resource); - - var domNodeTitle = WebInspector.DOMSearchMatchObject.titleForDOMNode(domNode); - var searchRegex = new RegExp(searchTerm.escapeForRegExp(), "gi"); - - // Textual matches. - var lineMatch; - var didFindTextualMatch = false; - while ((searchRegex.lastIndex < domNodeTitle.length) && (lineMatch = searchRegex.exec(domNodeTitle))) { - var matchObject = new WebInspector.DOMSearchMatchObject(resource, domNode, domNodeTitle, searchTerm, new WebInspector.TextRange(0, lineMatch.index, 0, searchRegex.lastIndex)); - var matchTreeElement = new WebInspector.SearchResultTreeElement(matchObject); - resourceTreeElement.appendChild(matchTreeElement); - didFindTextualMatch = true; - } - - // Non-textual matches are CSS Selector or XPath matches. In such cases, display the node entirely highlighted. - if (!didFindTextualMatch) { - var matchObject = new WebInspector.DOMSearchMatchObject(resource, domNode, domNodeTitle, domNodeTitle, new WebInspector.TextRange(0, 0, 0, domNodeTitle.length)); - var matchTreeElement = new WebInspector.SearchResultTreeElement(matchObject); - resourceTreeElement.appendChild(matchTreeElement); - } - - updateEmptyContentPlaceholder.call(this); - } - } - - DOMAgent.getSearchResults(searchId, 0, resultsCount, domSearchResults.bind(this)); - } - - WebInspector.domTreeManager.requestDocument(); - - // FIXME: Should we be searching for regexes or just plain text? - PageAgent.searchInResources(searchTerm, false, false, resourcesCallback.bind(this)); - - if ("_domSearchIdentifier" in this) { - DOMAgent.discardSearchResults(this._domSearchIdentifier); - delete this._domSearchIdentifier; - } - - DOMAgent.performSearch(searchTerm, domCallback.bind(this)); - }, - - // Private - - _searchFieldChanged: function(event) - { - this.performSearch(event.target.value); - }, - - _searchFieldInput: function(event) - { - // If the search field is cleared, immediately clear the search results tree outline. - if (!event.target.value.length && this.contentTreeOutline === this._searchContentTreeOutline) - this.performSearch(""); - }, - - _searchTreeElementForResource: function(resource) - { - // FIXME: This should take a frame ID (if one is available) - so we can differentiate between multiple resources - // with the same URL. - - var resourceTreeElement = this._searchContentTreeOutline.getCachedTreeElement(resource); - if (!resourceTreeElement) { - resourceTreeElement = new WebInspector.ResourceTreeElement(resource); - resourceTreeElement.hasChildren = true; - resourceTreeElement.expand(); - - this._searchContentTreeOutline.appendChild(resourceTreeElement); - } - - return resourceTreeElement; - }, - - _focusSearchField: function(keyboardShortcut, event) - { - this.show(); - - this._inputElement.select(); - }, - - _mainFrameDidChange: function(event) - { - if (this._mainFrameTreeElement) { - this._mainFrameTreeElement.frame.removeEventListener(WebInspector.Frame.Event.MainResourceDidChange, this._mainFrameMainResourceDidChange, this); - this._resourcesContentTreeOutline.removeChild(this._mainFrameTreeElement); - this._mainFrameTreeElement = null; - } - - var newFrame = WebInspector.frameResourceManager.mainFrame; - if (newFrame) { - newFrame.addEventListener(WebInspector.Frame.Event.MainResourceDidChange, this._mainFrameMainResourceDidChange, this); - this._mainFrameTreeElement = new WebInspector.FrameTreeElement(newFrame); - this._resourcesContentTreeOutline.insertChild(this._mainFrameTreeElement, 0); - - // Select by default. Allow onselect if we aren't showing a content view. - if (!this._resourcesContentTreeOutline.selectedTreeElement) - this._mainFrameTreeElement.revealAndSelect(true, false, !!WebInspector.contentBrowser.currentContentView); - - if (this._frameIdentifierToShowSourceCodeWhenAvailable) - this.showSourceCodeForFrame(this._frameIdentifierToShowSourceCodeWhenAvailable, true); - } - - // We only care about the first time the main frame changes. - if (!this._waitingForInitialMainFrame) - return; - - // Only if there is a main frame. - if (!newFrame) - return; - - delete this._waitingForInitialMainFrame; - - // Only if the last page searched is the same as the current page. - if (this._lastSearchedPageSetting.value !== newFrame.url.hash) - return; - - // Search for whatever is in the input field. This was populated with the last used search term. - this.performSearch(this._inputElement.value); - }, - - _mainFrameMainResourceDidChange: function(event) - { - var currentContentView = WebInspector.contentBrowser.currentContentView; - var wasShowingResourceContentView = currentContentView instanceof WebInspector.ResourceContentView - || currentContentView instanceof WebInspector.FrameContentView || currentContentView instanceof WebInspector.ScriptContentView; - - // Close all resource and frame content views since the main frame has navigated and all resources are cleared. - WebInspector.contentBrowser.contentViewContainer.closeAllContentViewsOfPrototype(WebInspector.ResourceClusterContentView); - WebInspector.contentBrowser.contentViewContainer.closeAllContentViewsOfPrototype(WebInspector.FrameContentView); - WebInspector.contentBrowser.contentViewContainer.closeAllContentViewsOfPrototype(WebInspector.ScriptContentView); - - function delayedWork() - { - // Show the main frame since there is no content view showing or we were showing a resource before. - // FIXME: We could try to select the same resource that was selected before in the case of a reload. - if (!WebInspector.contentBrowser.currentContentView || wasShowingResourceContentView) - this._mainFrameTreeElement.revealAndSelect(true, false); - } - - // Delay this work because other listeners of this event might not have fired yet. So selecting the main frame - // before those listeners do their work might cause the content of the old page to show instead of the new page. - setTimeout(delayedWork.bind(this), 0); - }, - - _frameWasAdded: function(event) - { - if (!this._frameIdentifierToShowSourceCodeWhenAvailable) - return; - - var frame = event.data.frame; - if (frame.id !== this._frameIdentifierToShowSourceCodeWhenAvailable) - return; - - this.showSourceCodeForFrame(frame.id, true); - }, - - _scriptWasAdded: function(event) - { - var script = event.data.script; - - // We don't add scripts without URLs here. Those scripts can quickly clutter the interface and - // are usually more transient. They will get added if/when they need to be shown in a content view. - if (!script.url) - return; - - // Exclude inspector scripts. - if (script.url.indexOf("__WebInspector") === 0) - return; - - // If the script URL matches a resource we can assume it is part of that resource and does not need added. - if (script.resource) - return; - - var insertIntoTopLevel = false; - - if (script.injected) { - if (!this._extensionScriptsFolderTreeElement) - this._extensionScriptsFolderTreeElement = new WebInspector.FolderTreeElement(WebInspector.UIString("Extension Scripts")); - var parentFolderTreeElement = this._extensionScriptsFolderTreeElement; - } else { - if (WebInspector.debuggableType === WebInspector.DebuggableType.JavaScript) - insertIntoTopLevel = true; - else { - if (!this._extraScriptsFolderTreeElement) - this._extraScriptsFolderTreeElement = new WebInspector.FolderTreeElement(WebInspector.UIString("Extra Scripts")); - var parentFolderTreeElement = this._extraScriptsFolderTreeElement; - } - } - - var scriptTreeElement = new WebInspector.ScriptTreeElement(script); - - if (insertIntoTopLevel) { - var index = insertionIndexForObjectInListSortedByFunction(scriptTreeElement, this._resourcesContentTreeOutline.children, this._compareTreeElements); - this._resourcesContentTreeOutline.insertChild(scriptTreeElement, index); - } else { - if (!parentFolderTreeElement.parent) { - var index = insertionIndexForObjectInListSortedByFunction(parentFolderTreeElement, this._resourcesContentTreeOutline.children, this._compareTreeElements); - this._resourcesContentTreeOutline.insertChild(parentFolderTreeElement, index); - } - - parentFolderTreeElement.appendChild(scriptTreeElement); - } - }, - - _scriptsCleared: function(event) - { - if (this._extensionScriptsFolderTreeElement) { - if (this._extensionScriptsFolderTreeElement.parent) - this._extensionScriptsFolderTreeElement.parent.removeChild(this._extensionScriptsFolderTreeElement); - this._extensionScriptsFolderTreeElement = null; - } - - if (this._extraScriptsFolderTreeElement) { - if (this._extraScriptsFolderTreeElement.parent) - this._extraScriptsFolderTreeElement.parent.removeChild(this._extraScriptsFolderTreeElement); - this._extraScriptsFolderTreeElement = null; - } - - if (this._anonymousScriptsFolderTreeElement) { - if (this._anonymousScriptsFolderTreeElement.parent) - this._anonymousScriptsFolderTreeElement.parent.removeChild(this._anonymousScriptsFolderTreeElement); - this._anonymousScriptsFolderTreeElement = null; - } - }, - - _treeElementSelected: function(treeElement, selectedByUser) - { - if (treeElement instanceof WebInspector.FolderTreeElement || treeElement instanceof WebInspector.DatabaseHostTreeElement) - return; - - if (treeElement instanceof WebInspector.ResourceTreeElement || treeElement instanceof WebInspector.ScriptTreeElement || - treeElement instanceof WebInspector.StorageTreeElement || treeElement instanceof WebInspector.DatabaseTableTreeElement || - treeElement instanceof WebInspector.DatabaseTreeElement || treeElement instanceof WebInspector.ApplicationCacheFrameTreeElement || - treeElement instanceof WebInspector.ContentFlowTreeElement) { - WebInspector.contentBrowser.showContentViewForRepresentedObject(treeElement.representedObject); - return; - } - - console.assert(treeElement instanceof WebInspector.SearchResultTreeElement); - if (!(treeElement instanceof WebInspector.SearchResultTreeElement)) - return; - - if (treeElement.representedObject instanceof WebInspector.DOMSearchMatchObject) - this.showMainFrameDOMTree(treeElement.representedObject.domNode, true); - else if (treeElement.representedObject instanceof WebInspector.ResourceSearchMatchObject) - this.showOriginalOrFormattedSourceCodeTextRange(treeElement.representedObject.sourceCodeTextRange); - }, - - _domNodeWasInspected: function(event) - { - this.showMainFrameDOMTree(event.data.node); - }, - - _domStorageObjectWasAdded: function(event) - { - var domStorage = event.data.domStorage; - var storageElement = new WebInspector.DOMStorageTreeElement(domStorage); - - if (domStorage.isLocalStorage()) - this._localStorageRootTreeElement = this._addStorageChild(storageElement, this._localStorageRootTreeElement, WebInspector.UIString("Local Storage")); - else - this._sessionStorageRootTreeElement = this._addStorageChild(storageElement, this._sessionStorageRootTreeElement, WebInspector.UIString("Session Storage")); - }, - - _domStorageObjectWasInspected: function(event) - { - var domStorage = event.data.domStorage; - var treeElement = this.treeElementForRepresentedObject(domStorage); - treeElement.revealAndSelect(true); - }, - - _databaseWasAdded: function(event) - { - var database = event.data.database; - - console.assert(database instanceof WebInspector.DatabaseObject); - - if (!this._databaseHostTreeElementMap[database.host]) { - this._databaseHostTreeElementMap[database.host] = new WebInspector.DatabaseHostTreeElement(database.host); - this._databaseRootTreeElement = this._addStorageChild(this._databaseHostTreeElementMap[database.host], this._databaseRootTreeElement, WebInspector.UIString("Databases")); - } - - var databaseElement = new WebInspector.DatabaseTreeElement(database); - this._databaseHostTreeElementMap[database.host].appendChild(databaseElement); - }, - - _databaseWasInspected: function(event) - { - var database = event.data.database; - var treeElement = this.treeElementForRepresentedObject(database); - treeElement.revealAndSelect(true); - }, - - _cookieStorageObjectWasAdded: function(event) - { - console.assert(event.data.cookieStorage instanceof WebInspector.CookieStorageObject); - - var cookieElement = new WebInspector.CookieStorageTreeElement(event.data.cookieStorage); - this._cookieStorageRootTreeElement = this._addStorageChild(cookieElement, this._cookieStorageRootTreeElement, WebInspector.UIString("Cookies")); - }, - - _frameManifestAdded: function(event) - { - var frameManifest = event.data.frameManifest; - console.assert(frameManifest instanceof WebInspector.ApplicationCacheFrame); - - var manifest = frameManifest.manifest; - var manifestURL = manifest.manifestURL; - if (!this._applicationCacheURLTreeElementMap[manifestURL]) { - this._applicationCacheURLTreeElementMap[manifestURL] = new WebInspector.ApplicationCacheManifestTreeElement(manifest); - this._applicationCacheRootTreeElement = this._addStorageChild(this._applicationCacheURLTreeElementMap[manifestURL], this._applicationCacheRootTreeElement, WebInspector.UIString("Application Cache")); - } - - var frameCacheElement = new WebInspector.ApplicationCacheFrameTreeElement(frameManifest); - this._applicationCacheURLTreeElementMap[manifestURL].appendChild(frameCacheElement); - }, - - _frameManifestRemoved: function(event) - { - // FIXME: Implement this. - }, - - _compareTreeElements: function(a, b) - { - // Always sort the main frame element first. - if (a instanceof WebInspector.FrameTreeElement) - return -1; - if (b instanceof WebInspector.FrameTreeElement) - return 1; - - console.assert(a.mainTitle); - console.assert(b.mainTitle); - - return (a.mainTitle || "").localeCompare(b.mainTitle || ""); - }, - - _addStorageChild: function(childElement, parentElement, folderName) - { - if (!parentElement) { - childElement.flattened = true; - - this._resourcesContentTreeOutline.insertChild(childElement, insertionIndexForObjectInListSortedByFunction(childElement, this._resourcesContentTreeOutline.children, this._compareTreeElements)); - - return childElement; - } - - if (parentElement instanceof WebInspector.StorageTreeElement) { - console.assert(parentElement.flattened); - - var previousOnlyChild = parentElement; - previousOnlyChild.flattened = false; - this._resourcesContentTreeOutline.removeChild(previousOnlyChild); - - var folderElement = new WebInspector.FolderTreeElement(folderName, null, null); - this._resourcesContentTreeOutline.insertChild(folderElement, insertionIndexForObjectInListSortedByFunction(folderElement, this._resourcesContentTreeOutline.children, this._compareTreeElements)); - - folderElement.appendChild(previousOnlyChild); - folderElement.insertChild(childElement, insertionIndexForObjectInListSortedByFunction(childElement, folderElement.children, this._compareTreeElements)); - - return folderElement; - } - - console.assert(parentElement instanceof WebInspector.FolderTreeElement); - parentElement.insertChild(childElement, insertionIndexForObjectInListSortedByFunction(childElement, parentElement.children, this._compareTreeElements)); - - return parentElement; - }, - - _storageCleared: function(event) - { - // Close all DOM and cookie storage content views since the main frame has navigated and all storages are cleared. - WebInspector.contentBrowser.contentViewContainer.closeAllContentViewsOfPrototype(WebInspector.CookieStorageContentView); - WebInspector.contentBrowser.contentViewContainer.closeAllContentViewsOfPrototype(WebInspector.DOMStorageContentView); - WebInspector.contentBrowser.contentViewContainer.closeAllContentViewsOfPrototype(WebInspector.DatabaseTableContentView); - WebInspector.contentBrowser.contentViewContainer.closeAllContentViewsOfPrototype(WebInspector.DatabaseContentView); - WebInspector.contentBrowser.contentViewContainer.closeAllContentViewsOfPrototype(WebInspector.ApplicationCacheFrameContentView); - - if (this._localStorageRootTreeElement && this._localStorageRootTreeElement.parent) - this._localStorageRootTreeElement.parent.removeChild(this._localStorageRootTreeElement); - - if (this._sessionStorageRootTreeElement && this._sessionStorageRootTreeElement.parent) - this._sessionStorageRootTreeElement.parent.removeChild(this._sessionStorageRootTreeElement); - - if (this._databaseRootTreeElement && this._databaseRootTreeElement.parent) - this._databaseRootTreeElement.parent.removeChild(this._databaseRootTreeElement); - - if (this._cookieStorageRootTreeElement && this._cookieStorageRootTreeElement.parent) - this._cookieStorageRootTreeElement.parent.removeChild(this._cookieStorageRootTreeElement); - - if (this._applicationCacheRootTreeElement && this._applicationCacheRootTreeElement.parent) - this._applicationCacheRootTreeElement.parent.removeChild(this._applicationCacheRootTreeElement); - - this._localStorageRootTreeElement = null; - this._sessionStorageRootTreeElement = null; - this._databaseRootTreeElement = null; - this._databaseHostTreeElementMap = {}; - this._cookieStorageRootTreeElement = null; - this._applicationCacheRootTreeElement = null; - this._applicationCacheURLTreeElementMap = {}; - } -}; - -WebInspector.ResourceSidebarPanel.prototype.__proto__ = WebInspector.NavigationSidebarPanel.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ResourceTimelineDataGridNode.js b/Source/WebInspectorUI/UserInterface/ResourceTimelineDataGridNode.js deleted file mode 100644 index d9b829f47..000000000 --- a/Source/WebInspectorUI/UserInterface/ResourceTimelineDataGridNode.js +++ /dev/null @@ -1,192 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ResourceTimelineDataGridNode = function(resourceTimelineRecord, graphOnly, graphDataSource) -{ - WebInspector.TimelineDataGridNode.call(this, graphOnly, graphDataSource); - - this._resource = resourceTimelineRecord.resource; - this._record = resourceTimelineRecord; - - this._record.addEventListener(WebInspector.TimelineRecord.Event.Updated, graphOnly ? this._timelineRecordUpdated : this._needsRefresh, this); - - if (!graphOnly) { - this._resource.addEventListener(WebInspector.Resource.Event.URLDidChange, this._needsRefresh, this); - this._resource.addEventListener(WebInspector.Resource.Event.TypeDidChange, this._needsRefresh, this); - this._resource.addEventListener(WebInspector.Resource.Event.LoadingDidFinish, this._needsRefresh, this); - this._resource.addEventListener(WebInspector.Resource.Event.LoadingDidFail, this._needsRefresh, this); - this._resource.addEventListener(WebInspector.Resource.Event.SizeDidChange, this._needsRefresh, this); - this._resource.addEventListener(WebInspector.Resource.Event.TransferSizeDidChange, this._needsRefresh, this); - } -}; - -WebInspector.Object.addConstructorFunctions(WebInspector.ResourceTimelineDataGridNode); - -WebInspector.ResourceTimelineDataGridNode.IconStyleClassName = "icon"; -WebInspector.ResourceTimelineDataGridNode.ErrorStyleClassName = "error"; - -WebInspector.ResourceTimelineDataGridNode.prototype = { - constructor: WebInspector.ResourceTimelineDataGridNode, - __proto__: WebInspector.TimelineDataGridNode.prototype, - - // Public - - get records() - { - return [this._record]; - }, - - get resource() - { - return this._resource; - }, - - get data() - { - if (this._cachedData) - return this._cachedData; - - var resource = this._resource; - var data = {}; - - if (!this._graphOnly) { - var zeroTime = this.graphDataSource ? this.graphDataSource.zeroTime : 0; - - data.name = WebInspector.displayNameForURL(resource.url, resource.urlComponents); - data.domain = WebInspector.displayNameForHost(resource.urlComponents.host); - data.scheme = resource.urlComponents.scheme ? resource.urlComponents.scheme.toUpperCase() : ""; - data.method = resource.requestMethod; - data.type = resource.type; - data.statusCode = resource.statusCode; - data.cached = resource.cached; - data.size = resource.size; - data.transferSize = resource.transferSize; - data.requestSent = resource.requestSentTimestamp - zeroTime; - data.duration = resource.receiveDuration; - data.latency = resource.latency; - } - - data.graph = this._record.startTime; - - this._cachedData = data; - return data; - }, - - createCellContent: function(columnIdentifier, cell) - { - var resource = this._resource; - - if (resource.failed || resource.canceled || resource.statusCode >= 400) - cell.classList.add(WebInspector.ResourceTimelineDataGridNode.ErrorStyleClassName); - - const emptyValuePlaceholderString = "\u2014"; - var value = this.data[columnIdentifier]; - - switch (columnIdentifier) { - case "name": - cell.classList.add(WebInspector.ResourceTreeElement.ResourceIconStyleClassName); - cell.classList.add(resource.type); - - var fragment = document.createDocumentFragment(); - - var goToButton = WebInspector.createGoToArrowButton(); - goToButton.addEventListener("click", this._goToResource.bind(this)); - fragment.appendChild(goToButton); - - var icon = document.createElement("div"); - icon.className = WebInspector.ResourceTimelineDataGridNode.IconStyleClassName; - fragment.appendChild(icon); - - var text = document.createTextNode(value); - fragment.appendChild(text); - - cell.title = resource.url; - - return fragment; - - case "type": - return WebInspector.Resource.Type.displayName(value); - - case "statusCode": - cell.title = resource.statusText || ""; - return value || emptyValuePlaceholderString; - - case "cached": - return value ? WebInspector.UIString("Yes") : WebInspector.UIString("No"); - - case "domain": - return value || emptyValuePlaceholderString; - - case "size": - case "transferSize": - return isNaN(value) ? emptyValuePlaceholderString : Number.bytesToString(value); - - case "requestSent": - case "latency": - case "duration": - return isNaN(value) ? emptyValuePlaceholderString : Number.secondsToString(value); - } - - return WebInspector.TimelineDataGridNode.prototype.createCellContent.call(this, columnIdentifier, cell); - }, - - refresh: function() - { - if (this._scheduledRefreshIdentifier) { - cancelAnimationFrame(this._scheduledRefreshIdentifier); - delete this._scheduledRefreshIdentifier; - } - - delete this._cachedData; - - WebInspector.TimelineDataGridNode.prototype.refresh.call(this); - }, - - // Private - - _needsRefresh: function() - { - if (this.dataGrid instanceof WebInspector.TimelineDataGrid) { - this.dataGrid.dataGridNodeNeedsRefresh(this); - return; - } - - if (this._scheduledRefreshIdentifier) - return; - - this._scheduledRefreshIdentifier = requestAnimationFrame(this.refresh.bind(this)); - }, - - _goToResource: function(event) - { - WebInspector.resourceSidebarPanel.showSourceCode(this._resource); - }, - - _timelineRecordUpdated: function(event) - { - if (this.isRecordVisible(this._record)) - this.needsGraphRefresh(); - } -}; diff --git a/Source/WebInspectorUI/UserInterface/ResourceTimelineDataGridNodePathComponent.js b/Source/WebInspectorUI/UserInterface/ResourceTimelineDataGridNodePathComponent.js deleted file mode 100644 index a4322b9a2..000000000 --- a/Source/WebInspectorUI/UserInterface/ResourceTimelineDataGridNodePathComponent.js +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ResourceTimelineDataGridNodePathComponent = function(resourceTimelineDataGridNode) { - var resource = resourceTimelineDataGridNode.record.resource; - var classNames = [WebInspector.ResourceTreeElement.ResourceIconStyleClassName, resource.type]; - - WebInspector.HierarchicalPathComponent.call(this, resourceTimelineDataGridNode.data.name, classNames, resource); - - this._resourceTimelineDataGridNode = resourceTimelineDataGridNode; -}; - -WebInspector.ResourceTimelineDataGridNodePathComponent.prototype = { - constructor: WebInspector.ResourceTimelineDataGridNodePathComponent, - - // Public - - get resourceTimelineDataGridNode() - { - return this._resourceTimelineDataGridNode; - }, - - get previousSibling() - { - if (!this._resourceTimelineDataGridNode.previousSibling) - return null; - return new WebInspector.ResourceTimelineDataGridNodePathComponent(this._resourceTimelineDataGridNode.previousSibling); - }, - - get nextSibling() - { - if (!this._resourceTimelineDataGridNode.nextSibling) - return null; - return new WebInspector.ResourceTimelineDataGridNodePathComponent(this._resourceTimelineDataGridNode.nextSibling); - } -}; - -WebInspector.ResourceTimelineDataGridNodePathComponent.prototype.__proto__ = WebInspector.HierarchicalPathComponent.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ResourceTimelineRecord.js b/Source/WebInspectorUI/UserInterface/ResourceTimelineRecord.js deleted file mode 100644 index aada8fafe..000000000 --- a/Source/WebInspectorUI/UserInterface/ResourceTimelineRecord.js +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ResourceTimelineRecord = function(resource) -{ - WebInspector.TimelineRecord.call(this, WebInspector.TimelineRecord.Type.Network); - - this._resource = resource; - this._resource.addEventListener(WebInspector.Resource.Event.TimestampsDidChange, this._dispatchUpdatedEvent, this); -}; - -WebInspector.ResourceTimelineRecord.prototype = { - constructor: WebInspector.ResourceTimelineRecord, - - // Public - - get resource() - { - return this._resource; - }, - - get updatesDynamically() - { - return true; - }, - - get usesActiveStartTime() - { - return true; - }, - - get startTime() - { - return this._resource.requestSentTimestamp; - }, - - get activeStartTime() - { - return this._resource.responseReceivedTimestamp; - }, - - get endTime() - { - return this._resource.finishedOrFailedTimestamp; - }, - - // Private - - _dispatchUpdatedEvent: function() - { - this.dispatchEventToListeners(WebInspector.TimelineRecord.Event.Updated); - } -}; - -WebInspector.ResourceTimelineRecord.prototype.__proto__ = WebInspector.TimelineRecord.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ResourceTreeElement.css b/Source/WebInspectorUI/UserInterface/ResourceTreeElement.css deleted file mode 100644 index eb1d5de4e..000000000 --- a/Source/WebInspectorUI/UserInterface/ResourceTreeElement.css +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.item.resource.failed { - color: rgb(224, 16, 16) !important; -} - -.item.resource.failed .subtitle { - color: rgba(224, 16, 16, 0.7) !important; -} diff --git a/Source/WebInspectorUI/UserInterface/ResourceTreeElement.js b/Source/WebInspectorUI/UserInterface/ResourceTreeElement.js deleted file mode 100644 index 2c38f3520..000000000 --- a/Source/WebInspectorUI/UserInterface/ResourceTreeElement.js +++ /dev/null @@ -1,198 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ResourceTreeElement = function(resource, representedObject) -{ - console.assert(resource instanceof WebInspector.Resource); - - WebInspector.SourceCodeTreeElement.call(this, resource, [WebInspector.ResourceTreeElement.StyleClassName, WebInspector.ResourceTreeElement.ResourceIconStyleClassName, resource.type], "", "", representedObject || resource, false); - - this._updateResource(resource); -}; - -WebInspector.ResourceTreeElement.StyleClassName = "resource"; -WebInspector.ResourceTreeElement.ResourceIconStyleClassName = "resource-icon"; -WebInspector.ResourceTreeElement.FailedStyleClassName = "failed"; - -WebInspector.ResourceTreeElement.compareResourceTreeElements = function(a, b) -{ - // Compare by type first to keep resources grouped by type when not sorted into folders. - var comparisonResult = a.resource.type.localeCompare(b.resource.type); - if (comparisonResult !== 0) - return comparisonResult; - - // Compare async resource types by their first timestamp so they are in chronological order. - if (a.resource.type === WebInspector.Resource.Type.XHR || a.resource.type === WebInspector.Resource.Type.WebSocket) - return a.resource.firstTimestamp - b.resource.firstTimestamp || 0; - - // Compare by subtitle when the types are the same. The subtitle is used to show the - // domain of the resource. This causes resources to group by domain. If the resource - // is on the same domain as the frame it will have an empty subtitle. This is good - // because empty string sorts first, so those will appear before external resources. - comparisonResult = a.subtitle.localeCompare(b.subtitle); - if (comparisonResult !== 0) - return comparisonResult; - - // Compare by title when the subtitles are the same. - return a.mainTitle.localeCompare(b.mainTitle); -} - -WebInspector.ResourceTreeElement.compareFolderAndResourceTreeElements = function(a, b) -{ - var aIsFolder = a instanceof WebInspector.FolderTreeElement; - var bIsFolder = b instanceof WebInspector.FolderTreeElement; - - if (aIsFolder && !bIsFolder) - return -1; - if (!aIsFolder && bIsFolder) - return 1; - if (aIsFolder && bIsFolder) - return a.mainTitle.localeCompare(b.mainTitle); - - return WebInspector.ResourceTreeElement.compareResourceTreeElements(a, b); -} - -WebInspector.ResourceTreeElement.prototype = { - constructor: WebInspector.ResourceTreeElement, - - // Public - - get resource() - { - return this._resource; - }, - - get filterableData() - { - return {text: this._resource.url}; - }, - - ondblclick: function() - { - InspectorFrontendHost.openInNewTab(this._resource.url); - }, - - // Protected (Used by FrameTreeElement) - - _updateResource: function(resource) - { - console.assert(resource instanceof WebInspector.Resource); - - // This method is for subclasses like FrameTreeElement who don't use a resource as the representedObject. - // This method should only be called once if the representedObject is a resource, since changing the resource - // without changing the representedObject is bad. If you need to change the resource, make a new ResourceTreeElement. - console.assert(!this._resource || !(this.representedObject instanceof WebInspector.Resource)); - - if (this._resource) { - this._resource.removeEventListener(WebInspector.Resource.Event.URLDidChange, this._urlDidChange, this); - this._resource.removeEventListener(WebInspector.Resource.Event.TypeDidChange, this._typeDidChange, this); - this._resource.removeEventListener(WebInspector.Resource.Event.LoadingDidFinish, this._updateStatus, this); - this._resource.removeEventListener(WebInspector.Resource.Event.LoadingDidFail, this._updateStatus, this); - } - - this._updateSourceCode(resource); - - this._resource = resource; - - resource.addEventListener(WebInspector.Resource.Event.URLDidChange, this._urlDidChange, this); - resource.addEventListener(WebInspector.Resource.Event.TypeDidChange, this._typeDidChange, this); - resource.addEventListener(WebInspector.Resource.Event.LoadingDidFinish, this._updateStatus, this); - resource.addEventListener(WebInspector.Resource.Event.LoadingDidFail, this._updateStatus, this); - - this._updateTitles(); - this._updateStatus(); - this._updateToolTip(); - }, - - // Protected - - _updateTitles: function() - { - var frame = this._resource.parentFrame; - var isMainResource = this._resource.isMainResource(); - if (isMainResource && frame) { - // When the resource is a main resource, get the host from the current frame's parent frame instead of the current frame. - var parentResourceHost = frame.parentFrame ? frame.parentFrame.mainResource.urlComponents.host : null; - } else if (frame) { - // When the resource is a normal sub-resource, get the host from the current frame's main resource. - var parentResourceHost = frame.mainResource.urlComponents.host; - } - - var urlComponents = this._resource.urlComponents; - - var oldMainTitle = this.mainTitle; - this.mainTitle = WebInspector.displayNameForURL(this._resource.url, urlComponents); - - // Show the host as the subtitle if it is different from the main resource or if this is the main frame's main resource. - var subtitle = parentResourceHost !== urlComponents.host || frame.isMainFrame() && isMainResource ? WebInspector.displayNameForHost(urlComponents.host) : null; - this.subtitle = this.mainTitle !== subtitle ? subtitle : null; - - if (oldMainTitle !== this.mainTitle) - this.callFirstAncestorFunction("descendantResourceTreeElementMainTitleDidChange", [this, oldMainTitle]); - }, - - // Private - - _updateStatus: function() - { - if (this._resource.failed) - this.addClassName(WebInspector.ResourceTreeElement.FailedStyleClassName); - else - this.removeClassName(WebInspector.ResourceTreeElement.FailedStyleClassName); - - if (this._resource.finished || this._resource.failed) { - // Remove the spinner and replace with a reload button in case it's the main frame's main resource. - var frame = this._resource.parentFrame; - if (this._resource.isMainResource() && frame && frame.isMainFrame() && this instanceof WebInspector.FrameTreeElement) - this.updateStatusForMainFrame(); - else - this.status = null; - } else { - var spinner = new WebInspector.IndeterminateProgressSpinner; - this.status = spinner.element; - } - }, - - _updateToolTip: function() - { - this.tooltip = this._resource.url; - }, - - _urlDidChange: function(event) - { - this._updateTitles(); - this._updateToolTip(); - }, - - _typeDidChange: function(event) - { - this.removeClassName(event.data.oldType); - this.addClassName(this._resource.type); - - this.callFirstAncestorFunction("descendantResourceTreeElementTypeDidChange", [this, event.data.oldType]); - } -}; - -WebInspector.ResourceTreeElement.prototype.__proto__ = WebInspector.SourceCodeTreeElement.prototype; diff --git a/Source/WebInspectorUI/UserInterface/Revision.js b/Source/WebInspectorUI/UserInterface/Revision.js deleted file mode 100644 index 4cf2c4b46..000000000 --- a/Source/WebInspectorUI/UserInterface/Revision.js +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.Revision = function() -{ - WebInspector.Object.call(this); -}; - -WebInspector.Revision.prototype = { - constructor: WebInspector.Revision, - - // Public - - apply: function() - { - // Implemented by subclasses. - console.error("Needs to be implemented by a subclass."); - }, - - revert: function() - { - // Implemented by subclasses. - console.error("Needs to be implemented by a subclass."); - }, - - copy: function() - { - // Override by subclasses. - return this; - } -}; - -WebInspector.Revision.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/RulesStyleDetailsPanel.css b/Source/WebInspectorUI/UserInterface/RulesStyleDetailsPanel.css deleted file mode 100644 index 43e1cbaa7..000000000 --- a/Source/WebInspectorUI/UserInterface/RulesStyleDetailsPanel.css +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.sidebar > .panel.details.css-style .rules .label { - font-size: 11px; - font-family: "Lucida Grande", sans-serif; - - color: rgb(60%, 60%, 60%); - text-shadow: white 0 1px 0; - - padding: 0 10px; -} - -.sidebar > .panel.details.css-style .rules .label .go-to-link { - color: inherit !important; -} - -.sidebar > .panel.details.css-style .rules .label + .style-declaration-section { - margin-top: 5px; -} - -.sidebar > .panel.details.css-style .rules .new-rule { - font-size: 12px; - font-family: "Lucida Grande", sans-serif; - font-weight: bold; - - color: black; - text-shadow: white 0 1px 0; - - padding: 5px 10px; - - margin-bottom: 8px; - margin-top: -5px; - - opacity: 0.5; -} - -.sidebar > .panel.details.css-style .rules .new-rule img { - content: url(Images/Plus.svg); - - width: 13px; - height: 13px; - - vertical-align: -2px; - - margin-right: 6px; -} - -.sidebar > .panel.details.css-style .rules .new-rule:hover { - opacity: 0.6; -} - -.sidebar > .panel.details.css-style .rules .new-rule:active { - opacity: 0.7; -} diff --git a/Source/WebInspectorUI/UserInterface/RulesStyleDetailsPanel.js b/Source/WebInspectorUI/UserInterface/RulesStyleDetailsPanel.js deleted file mode 100644 index 0fd114e5a..000000000 --- a/Source/WebInspectorUI/UserInterface/RulesStyleDetailsPanel.js +++ /dev/null @@ -1,273 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.RulesStyleDetailsPanel = function() -{ - WebInspector.StyleDetailsPanel.call(this, WebInspector.RulesStyleDetailsPanel.StyleClassName, "rules", WebInspector.UIString("Rules")); - - this._sections = []; -}; - -WebInspector.RulesStyleDetailsPanel.StyleClassName = "rules"; -WebInspector.RulesStyleDetailsPanel.LabelElementStyleClassName = "label"; -WebInspector.RulesStyleDetailsPanel.NewRuleElementStyleClassName = "new-rule"; - -WebInspector.RulesStyleDetailsPanel.prototype = { - constructor: WebInspector.RulesStyleDetailsPanel, - - // Public - - refresh: function(significantChange) - { - // We only need to do a rebuild on significant changes. Other changes are handled - // by the sections and text editors themselves. - if (!significantChange) - return; - - var newSections = []; - var newDOMFragment = document.createDocumentFragment(); - - var previousMediaList = []; - var previousSection = null; - var previousFocusedSection = null; - - function mediaListsEqual(a, b) - { - a = a || []; - b = b || []; - - if (a.length !== b.length) - return false; - - for (var i = 0; i < a.length; ++i) { - var aMedia = a[i]; - var bMedia = b[i]; - - if (aMedia.type !== bMedia.type) - return false; - - if (aMedia.text !== bMedia.text) - return false; - - if (!aMedia.sourceCodeLocation && bMedia.sourceCodeLocation) - return false; - - if (aMedia.sourceCodeLocation && !aMedia.sourceCodeLocation.isEqual(bMedia.sourceCodeLocation)) - return false; - } - - return true; - } - - function filteredMediaList(mediaList) - { - if (!mediaList) - return []; - - // Exclude the basic "screen" query since it's very common and just clutters things. - return mediaList.filter(function(media) { - return media.text !== "screen"; - }); - } - - function appendStyleSection(style) - { - var section = style.__rulesSection; - if (section && section.focused && !previousFocusedSection) - previousFocusedSection = section; - - if (!section) { - section = new WebInspector.CSSStyleDeclarationSection(style); - style.__rulesSection = section; - } else - section.refresh(); - - if (this._focusNextNewInspectorRule && style.ownerRule && style.ownerRule.type === WebInspector.CSSRule.Type.Inspector) { - previousFocusedSection = section; - delete this._focusNextNewInspectorRule; - } - - // Reset lastInGroup in case the order/grouping changed. - section.lastInGroup = false; - - newDOMFragment.appendChild(section.element); - newSections.push(section); - - previousSection = section; - } - - function addNewRuleButton() - { - if (previousSection) - previousSection.lastInGroup = true; - - var newRuleButton = document.createElement("div"); - newRuleButton.className = WebInspector.RulesStyleDetailsPanel.NewRuleElementStyleClassName; - newRuleButton.addEventListener("click", this._newRuleClicked.bind(this)); - - newRuleButton.appendChild(document.createElement("img")); - newRuleButton.appendChild(document.createTextNode(WebInspector.UIString("New Rule"))); - - newDOMFragment.appendChild(newRuleButton); - - addedNewRuleButton = true; - } - - var pseudoElements = this.nodeStyles.pseudoElements; - for (var pseudoIdentifier in pseudoElements) { - var pseudoElement = pseudoElements[pseudoIdentifier]; - for (var i = 0; i < pseudoElement.orderedStyles.length; ++i) { - var style = pseudoElement.orderedStyles[i]; - appendStyleSection.call(this, style); - } - - if (previousSection) - previousSection.lastInGroup = true; - } - - var addedNewRuleButton = false; - - var orderedStyles = this.nodeStyles.orderedStyles; - for (var i = 0; i < orderedStyles.length; ++i) { - var style = orderedStyles[i]; - - if (style.type === WebInspector.CSSStyleDeclaration.Type.Rule && !addedNewRuleButton) - addNewRuleButton.call(this); - - if (previousSection && previousSection.style.node !== style.node) { - previousSection.lastInGroup = true; - - var prefixElement = document.createElement("strong"); - prefixElement.textContent = WebInspector.UIString("Inherited From: "); - - var inheritedLabel = document.createElement("div"); - inheritedLabel.className = WebInspector.RulesStyleDetailsPanel.LabelElementStyleClassName; - inheritedLabel.appendChild(prefixElement); - inheritedLabel.appendChild(WebInspector.linkifyNodeReference(style.node)); - newDOMFragment.appendChild(inheritedLabel); - } - - // Only include the media list if it is different from the previous media list shown. - var currentMediaList = filteredMediaList(style.ownerRule && style.ownerRule.mediaList); - if (!mediaListsEqual(previousMediaList, currentMediaList)) { - previousMediaList = currentMediaList; - - // Break the section group even if the media list is empty. That way the user knows - // the previous displayed media list does not apply to the next section. - if (previousSection) - previousSection.lastInGroup = true; - - for (var j = 0; j < currentMediaList.length; ++j) { - var media = currentMediaList[j]; - - var prefixElement = document.createElement("strong"); - prefixElement.textContent = WebInspector.UIString("Media: "); - - var mediaLabel = document.createElement("div"); - mediaLabel.className = WebInspector.RulesStyleDetailsPanel.LabelElementStyleClassName; - mediaLabel.appendChild(prefixElement); - mediaLabel.appendChild(document.createTextNode(media.text)); - - if (media.sourceCodeLocation) { - mediaLabel.appendChild(document.createTextNode(" \u2014 ")); - mediaLabel.appendChild(WebInspector.createSourceCodeLocationLink(media.sourceCodeLocation, true)); - } - - newDOMFragment.appendChild(mediaLabel); - } - } - - appendStyleSection.call(this, style); - } - - if (!addedNewRuleButton) - addNewRuleButton.call(this); - - if (previousSection) - previousSection.lastInGroup = true; - - this.element.removeChildren(); - this.element.appendChild(newDOMFragment); - - this._sections = newSections; - - for (var i = 0; i < this._sections.length; ++i) - this._sections[i].updateLayout(); - - if (previousFocusedSection) { - previousFocusedSection.focus(); - - function scrollToFocusedSection() - { - previousFocusedSection.element.scrollIntoViewIfNeeded(true); - } - - // Do the scroll on a timeout since StyleDetailsPanel restores scroll position - // after the refresh, and we might not need to scroll after the restore. - setTimeout(scrollToFocusedSection, 0); - } - }, - - // Protected - - shown: function() - { - WebInspector.StyleDetailsPanel.prototype.shown.call(this); - - // Associate the style and section objects so they can be reused. - // Also update the layout in case we changed widths while hidden. - for (var i = 0; i < this._sections.length; ++i) { - var section = this._sections[i]; - section.style.__rulesSection = section; - section.updateLayout(); - } - }, - - hidden: function() - { - WebInspector.StyleDetailsPanel.prototype.hidden.call(this); - - // Disconnect the style and section objects so they have a chance - // to release their objects when this panel is not visible. - for (var i = 0; i < this._sections.length; ++i) - delete this._sections[i].style.__rulesSection; - }, - - widthDidChange: function() - { - for (var i = 0; i < this._sections.length; ++i) - this._sections[i].updateLayout(); - }, - - // Private - - _newRuleClicked: function(event) - { - this._focusNextNewInspectorRule = true; - this.nodeStyles.addRule(); - } -}; - -WebInspector.RulesStyleDetailsPanel.prototype.__proto__ = WebInspector.StyleDetailsPanel.prototype; diff --git a/Source/WebInspectorUI/UserInterface/RuntimeManager.js b/Source/WebInspectorUI/UserInterface/RuntimeManager.js deleted file mode 100644 index e58642e91..000000000 --- a/Source/WebInspectorUI/UserInterface/RuntimeManager.js +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.RuntimeManager = function() -{ - WebInspector.Object.call(this); - - // Enable the RuntimeAgent to receive notification of execution contexts. - if (RuntimeAgent.enable) - RuntimeAgent.enable(); -}; - -WebInspector.RuntimeManager.prototype = { - constructor: WebInspector.RuntimeManager, - - // Public - - evaluateInInspectedWindow: function(expression, objectGroup, includeCommandLineAPI, doNotPauseOnExceptionsAndMuteConsole, returnByValue, callback) - { - if (!expression) { - // There is no expression, so the completion should happen against global properties. - expression = "this"; - } - - function evalCallback(error, result, wasThrown) - { - if (error) { - console.error(error); - callback(null, false); - return; - } - - if (returnByValue) - callback(null, wasThrown, wasThrown ? null : result); - else - callback(WebInspector.RemoteObject.fromPayload(result), wasThrown); - } - - if (WebInspector.debuggerManager.activeCallFrame) { - DebuggerAgent.evaluateOnCallFrame(WebInspector.debuggerManager.activeCallFrame.id, expression, objectGroup, includeCommandLineAPI, doNotPauseOnExceptionsAndMuteConsole, returnByValue, evalCallback); - return; - } - - // COMPATIBILITY (iOS 6): Execution context identifiers (contextId) did not exist - // in iOS 6. Fallback to including the frame identifier (frameId). - var contextId = WebInspector.quickConsole.executionContextIdentifier; - RuntimeAgent.evaluate.invoke({expression: expression, objectGroup: objectGroup, includeCommandLineAPI: includeCommandLineAPI, doNotPauseOnExceptionsAndMuteConsole: doNotPauseOnExceptionsAndMuteConsole, contextId: contextId, frameId: contextId, returnByValue: returnByValue}, evalCallback); - }, - - getPropertiesForRemoteObject: function(objectId, callback) - { - RuntimeAgent.getProperties(objectId, function(error, result) { - if (error) { - callback(error); - return; - } - - var properties = new Map; - for (var property of result) - properties.set(property.name, property); - - callback(null, properties); - }); - } -}; - -WebInspector.RuntimeManager.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/RuntimeObserver.js b/Source/WebInspectorUI/UserInterface/RuntimeObserver.js deleted file mode 100644 index a8bc71d3f..000000000 --- a/Source/WebInspectorUI/UserInterface/RuntimeObserver.js +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.RuntimeObserver = function() -{ - WebInspector.Object.call(this); -}; - -WebInspector.RuntimeObserver.prototype = { - constructor: WebInspector.RuntimeObserver, - - // Events defined by the "Runtime" domain. - - executionContextCreated: function(contextPayload) - { - WebInspector.frameResourceManager.executionContextCreated(contextPayload); - } -}; - -WebInspector.RuntimeObserver.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ScopeBar.css b/Source/WebInspectorUI/UserInterface/ScopeBar.css deleted file mode 100644 index 08ad58b84..000000000 --- a/Source/WebInspectorUI/UserInterface/ScopeBar.css +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.scope-bar { - font-family: Lucida Grande, sans-serif; - padding: 0 3px; - overflow: hidden; -} - -.scope-bar > li { - display: inline-block; - margin: 0 2px; - padding: 0 8px 3px; - font-size: 11px; - font-weight: bold; - line-height: 12px; - color: rgb(46, 46, 46); - background-color: transparent; - border: 1px solid transparent; - border-radius: 9px; - text-align: center; - - transition: 200ms ease-in-out; - transition-property: background-color, border-color; -} - -.scope-bar > li.selected, -.scope-bar > li:active { - transition-duration: 75ms; -} - -.scope-bar > li:hover { - border-color: rgba(0, 0, 0, 0.15); -} - -.scope-bar > li.selected { - background-color: rgba(0, 0, 0, 0.06); - border-color: rgba(0, 0, 0, 0.30); -} - -.scope-bar > li:active { - background-color: rgba(0, 0, 0, 0.16); - border-color: rgba(0, 0, 0, 0.40); -} diff --git a/Source/WebInspectorUI/UserInterface/ScopeBar.js b/Source/WebInspectorUI/UserInterface/ScopeBar.js deleted file mode 100644 index c17355197..000000000 --- a/Source/WebInspectorUI/UserInterface/ScopeBar.js +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ScopeBar = function(identifier, items, defaultItem) { - WebInspector.NavigationItem.call(this, identifier); - - this._element.classList.add(WebInspector.ScopeBar.StyleClassName); - - this._items = items; - this._defaultItem = defaultItem; - - this._itemsById = []; - this._populate(); -}; - -WebInspector.ScopeBar.StyleClassName = "scope-bar"; -WebInspector.ScopeBar.Event = { - SelectionChanged: "scopebar-selection-did-change" -}; - -WebInspector.ScopeBar.prototype = { - constructor: WebInspector.ScopeBar, - - // Public - - get defaultItem() - { - return this._defaultItem; - }, - - item: function(id) - { - return this._itemsById[id]; - }, - - get selectedItems() - { - return this._items.filter(function(item) { - return item.selected; - }); - }, - - updateLayout: function(expandOnly) - { - if (expandOnly) - return; - - for (var i = 0; i < this._items.length; ++i) { - var item = this._items[i]; - var isSelected = item.selected; - - if (!isSelected) - item.element.classList.add(WebInspector.ScopeBarItem.SelectedStyleClassName); - - var selectedWidth = item.element.offsetWidth; - if (selectedWidth) - item.element.style.minWidth = selectedWidth + "px"; - - if (!isSelected) - item.element.classList.remove(WebInspector.ScopeBarItem.SelectedStyleClassName); - } - }, - - // Private - - _populate: function() - { - var item; - for (var i = 0; i < this._items.length; ++i) { - item = this._items[i]; - this._itemsById[item.id] = item; - this._element.appendChild(item.element); - - item.addEventListener(WebInspector.ScopeBarItem.Event.SelectionChanged, this._itemSelectionDidChange, this); - } - - if (!this.selectedItems.length && this._defaultItem) - this._defaultItem.selected = true; - }, - - _itemSelectionDidChange: function(event) - { - var sender = event.target; - var item; - - // An exclusive item was selected, unselect everything else. - if (sender.isExclusive && sender.selected) { - for (var i = 0; i < this._items.length; ++i) { - item = this._items[i]; - if (item !== sender) - item.selected = false; - } - } else { - var replacesCurrentSelection = !event.data.withModifier; - for (var i = 0; i < this._items.length; ++i) { - item = this._items[i]; - if (item.isExclusive && item !== sender && sender.selected) - item.selected = false; - else if (sender.selected && replacesCurrentSelection && sender !== item) - item.selected = false; - } - } - - // If nothing is selected anymore, select the default item. - if (!this.selectedItems.length && this._defaultItem) - this._defaultItem.selected = true; - - this.dispatchEventToListeners(WebInspector.ScopeBar.Event.SelectionChanged); - } -}; - -WebInspector.ScopeBar.prototype.__proto__ = WebInspector.NavigationItem.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ScopeBarItem.js b/Source/WebInspectorUI/UserInterface/ScopeBarItem.js deleted file mode 100644 index 6ad2863b0..000000000 --- a/Source/WebInspectorUI/UserInterface/ScopeBarItem.js +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ScopeBarItem = function(id, label, isExclusive) { - WebInspector.Object.call(this); - - this.id = id; - this.label = label; - this.isExclusive = isExclusive; - - this._selectedSetting = new WebInspector.Setting("scopebaritem-" + id, false); - - this._markElementSelected(this._selectedSetting.value); -}; - -WebInspector.ScopeBarItem.SelectedStyleClassName = "selected"; -WebInspector.ScopeBarItem.Event = { - SelectionChanged: "scope-bar-item-selection-did-change" -}; - -WebInspector.ScopeBarItem.prototype = { - constructor: WebInspector.ScopeBarItem, - - // Public - - get element() - { - if (!this._element) { - this._element = document.createElement("li"); - this._element.textContent = this.label; - this._element.addEventListener("click", this._clicked.bind(this), false); - } - return this._element; - }, - - get selected() - { - return this._selectedSetting.value; - }, - - set selected(selected) - { - this.setSelected(selected, false); - }, - - setSelected: function(selected, withModifier) - { - if (this._selectedSetting.value === selected) - return; - - this._markElementSelected(selected); - - this._selectedSetting.value = selected; - - this.dispatchEventToListeners(WebInspector.ScopeBarItem.Event.SelectionChanged, {withModifier: withModifier}); - }, - - // Private - - _markElementSelected: function(selected) - { - if (selected) - this.element.classList.add(WebInspector.ScopeBarItem.SelectedStyleClassName); - else - this.element.classList.remove(WebInspector.ScopeBarItem.SelectedStyleClassName); - }, - - _clicked: function(event) - { - var withModifier = (event.metaKey && !event.ctrlKey && !event.altKey && !event.shiftKey); - this.setSelected(!this.selected, withModifier); - } -}; - -WebInspector.ScopeBarItem.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ScopeChainDetailsSidebarPanel.js b/Source/WebInspectorUI/UserInterface/ScopeChainDetailsSidebarPanel.js deleted file mode 100644 index 28ff7524b..000000000 --- a/Source/WebInspectorUI/UserInterface/ScopeChainDetailsSidebarPanel.js +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ScopeChainDetailsSidebarPanel = function() { - WebInspector.DetailsSidebarPanel.call(this, "scope-chain", WebInspector.UIString("Scope Chain"), WebInspector.UIString("Scope Chain"), "Images/NavigationItemVariable.svg", "5"); - - this._callFrame = null; -}; - -WebInspector.ScopeChainDetailsSidebarPanel.prototype = { - constructor: WebInspector.ScopeChainDetailsSidebarPanel, - - // Public - - inspect: function(objects) - { - // Convert to a single item array if needed. - if (!(objects instanceof Array)) - objects = [objects]; - - var callFrameToInspect = null; - - // Iterate over the objects to find a WebInspector.CallFrame to inspect. - for (var i = 0; i < objects.length; ++i) { - if (!(objects[i] instanceof WebInspector.CallFrame)) - continue; - callFrameToInspect = objects[i]; - break; - } - - this.callFrame = callFrameToInspect; - - return !!this.callFrame; - }, - - get callFrame() - { - return this._callFrame; - }, - - set callFrame(callFrame) - { - if (callFrame === this._callFrame) - return; - - this._callFrame = callFrame; - - this.needsRefresh(); - }, - - refresh: function() - { - var callFrame = this.callFrame; - if (!callFrame) - return; - - var detailsSections = []; - var foundLocalScope = false; - - var sectionCountByType = {}; - for (var type in WebInspector.ScopeChainNode.Type) - sectionCountByType[WebInspector.ScopeChainNode.Type[type]] = 0; - - var scopeChain = callFrame.scopeChain; - for (var i = 0; i < scopeChain.length; ++i) { - var scope = scopeChain[i]; - - var title = null; - var extraProperties = null; - var collapsedByDefault = false; - var dontHighlightNonEnumerableProperties = true; - - ++sectionCountByType[scope.type]; - - switch (scope.type) { - case WebInspector.ScopeChainNode.Type.Local: - foundLocalScope = true; - collapsedByDefault = false; - dontHighlightNonEnumerableProperties = true; - - title = WebInspector.UIString("Local Variables"); - - if (callFrame.thisObject) - extraProperties = [new WebInspector.RemoteObjectProperty("this", callFrame.thisObject)]; - break; - - case WebInspector.ScopeChainNode.Type.Closure: - title = WebInspector.UIString("Closure Variables"); - dontHighlightNonEnumerableProperties = true; - collapsedByDefault = false; - break; - - case WebInspector.ScopeChainNode.Type.Catch: - title = WebInspector.UIString("Catch Variables"); - dontHighlightNonEnumerableProperties = true; - collapsedByDefault = false; - break; - - case WebInspector.ScopeChainNode.Type.With: - title = WebInspector.UIString("With Object Properties"); - collapsedByDefault = foundLocalScope; - dontHighlightNonEnumerableProperties = false; - break; - - case WebInspector.ScopeChainNode.Type.Global: - title = WebInspector.UIString("Global Variables"); - dontHighlightNonEnumerableProperties = false; - collapsedByDefault = true; - break; - } - - var detailsSectionIdentifier = scope.type + "-" + sectionCountByType[scope.type]; - - var section = new WebInspector.ObjectPropertiesSection(scope.object, null, null, null, true, extraProperties, WebInspector.ScopeVariableTreeElement); - section.dontHighlightNonEnumerablePropertiesAtTopLevel = dontHighlightNonEnumerableProperties; - section.__propertyIdentifierPrefix = detailsSectionIdentifier; - - var detailsSection = new WebInspector.DetailsSection(detailsSectionIdentifier, title, null, null, collapsedByDefault); - detailsSection.groups[0].rows = [new WebInspector.DetailsSectionPropertiesRow(section)]; - detailsSections.push(detailsSection); - } - - function delayedWork() - { - // Clear the timeout so we don't update the interface twice. - clearTimeout(timeout); - - // Bail if the call frame changed while we were waiting for the async response. - if (this.callFrame !== callFrame) - return; - - this.element.removeChildren(); - for (var i = 0; i < detailsSections.length; ++i) - this.element.appendChild(detailsSections[i].element); - } - - // We need a timeout in place in case there are long running, pending backend dispatches. This can happen - // if the debugger is paused in code that was executed from the console. The console will be waiting for - // the result of the execution and without a timeout we would never update the scope variables. - var timeout = setTimeout(delayedWork.bind(this), 50); - - // Since ObjectPropertiesSection populates asynchronously, we want to wait to replace the existing content - // until after all the pending asynchronous requests are completed. This prevents severe flashing while stepping. - InspectorBackend.runAfterPendingDispatches(delayedWork.bind(this)); - } -}; - -WebInspector.ScopeChainDetailsSidebarPanel.prototype.__proto__ = WebInspector.DetailsSidebarPanel.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ScopeChainNode.js b/Source/WebInspectorUI/UserInterface/ScopeChainNode.js deleted file mode 100644 index 0ba8bc753..000000000 --- a/Source/WebInspectorUI/UserInterface/ScopeChainNode.js +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ScopeChainNode = function(type, object) -{ - WebInspector.Object.call(this); - - console.assert(typeof type === "string"); - console.assert(object instanceof WebInspector.RemoteObject); - - if (type in WebInspector.ScopeChainNode.Type) - type = WebInspector.ScopeChainNode.Type[type]; - - this._type = type || null; - this._object = object || null; -}; - -WebInspector.ScopeChainNode.Type = { - Local: "scope-chain-type-local", - Global: "scope-chain-type-global", - With: "scope-chain-type-with", - Closure: "scope-chain-type-closure", - Catch: "scope-chain-type-catch" -}; - -WebInspector.ScopeChainNode.prototype = { - constructor: WebInspector.ScopeChainNode, - - // Public - - get type() - { - return this._type; - }, - - get object() - { - return this._object; - } -}; - -WebInspector.ScopeChainNode.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ScopeVariableTreeElement.js b/Source/WebInspectorUI/UserInterface/ScopeVariableTreeElement.js deleted file mode 100644 index 0ee232099..000000000 --- a/Source/WebInspectorUI/UserInterface/ScopeVariableTreeElement.js +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (C) 2008, 2013 Apple Inc. All Rights Reserved. - * Copyright (C) 2011 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ScopeVariableTreeElement = function(property) -{ - WebInspector.ObjectPropertyTreeElement.call(this, property); -}; - -WebInspector.ScopeVariableTreeElement._expandedProperties = {}; - -WebInspector.ScopeVariableTreeElement.prototype = { - constructor: WebInspector.ScopeVariableTreeElement, - - // Public - - onattach: function() - { - WebInspector.ObjectPropertyTreeElement.prototype.onattach.call(this); - - if (this.hasChildren && this.constructor._expandedProperties.hasOwnProperty(this.propertyIdentifier)) - this.expand(); - }, - - onexpand: function() - { - this.constructor._expandedProperties[this.propertyIdentifier] = true; - }, - - oncollapse: function() - { - delete this.constructor._expandedProperties[this.propertyIdentifier]; - }, - - get propertyIdentifier() - { - if ("_propertyIdentifier" in this) - return this._propertyIdentifier; - - var section = this.treeOutline.section; - this._propertyIdentifier = (section.__propertyIdentifierPrefix ? section.__propertyIdentifierPrefix + "-" : "") + this.propertyPath; - return this._propertyIdentifier; - }, - - get propertyPath() - { - if ("_propertyPath" in this) - return this._propertyPath; - - 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._propertyPath = result; - return result; - } -}; - -WebInspector.ScopeVariableTreeElement.prototype.__proto__ = WebInspector.ObjectPropertyTreeElement.prototype; diff --git a/Source/WebInspectorUI/UserInterface/Script.js b/Source/WebInspectorUI/UserInterface/Script.js deleted file mode 100644 index 46f1ddbce..000000000 --- a/Source/WebInspectorUI/UserInterface/Script.js +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.Script = function(id, range, url, injected, sourceMapURL) -{ - WebInspector.SourceCode.call(this); - - console.assert(id); - console.assert(range instanceof WebInspector.TextRange); - - this._id = id || null; - this._range = range || null; - this._url = url || null; - this._injected = injected || false; - - this._resource = this._resolveResource(); - if (this._resource) - this._resource.associateWithScript(this); - - if (sourceMapURL) - WebInspector.sourceMapManager.downloadSourceMap(sourceMapURL, this._url, this); -}; - -WebInspector.Script.TypeIdentifier = "script"; -WebInspector.Script.URLCookieKey = "script-url"; -WebInspector.Script.DisplayNameCookieKey = "script-display-name"; - -WebInspector.Script.resetUniqueDisplayNameNumbers = function() -{ - WebInspector.Script._nextUniqueDisplayNameNumber = 1; -} - -WebInspector.Script._nextUniqueDisplayNameNumber = 1; - -WebInspector.Script.prototype = { - constructor: WebInspector.Script, - - // Public - - get id() - { - return this._id; - }, - - get range() - { - return this._range; - }, - - get url() - { - return this._url; - }, - - get urlComponents() - { - if (!this._urlComponents) - this._urlComponents = parseURL(this._url); - return this._urlComponents; - }, - - get displayName() - { - if (this._url) - return WebInspector.displayNameForURL(this._url, this.urlComponents); - - // Assign a unique number to the script object so it will stay the same. - if (!this._uniqueDisplayNameNumber) - this._uniqueDisplayNameNumber = this.constructor._nextUniqueDisplayNameNumber++; - - return WebInspector.UIString("Anonymous Script %d").format(this._uniqueDisplayNameNumber); - }, - - get injected() - { - return this._injected; - }, - - get resource() - { - return this._resource; - }, - - canRequestContentFromBackend: function() - { - // We can request content if we have an id. - return !!this._id; - }, - - requestContentFromBackend: function(callback) - { - if (!this._id) { - // There is no identifier to request content with. Return false to cause the - // pending callbacks to get null content. - return false; - } - - DebuggerAgent.getScriptSource(this._id, callback); - return true; - }, - - saveIdentityToCookie: function(cookie) - { - cookie[WebInspector.Script.URLCookieKey] = this.url; - cookie[WebInspector.Script.DisplayNameCookieKey] = this.displayName; - }, - - // Private - - _resolveResource: function() - { - // FIXME: We should be able to associate a Script with a Resource through identifiers, - // we shouldn't need to lookup by URL, which is not safe with frames, where there might - // be multiple resources with the same URL. - // Scripts should be able to associate directly with a Resource - - // No URL, no resource. - if (!this._url) - return null; - - try { - // Try with the Script's full URL. - var resource = WebInspector.frameResourceManager.resourceForURL(this.url); - if (resource) - return resource; - - // Try with the Script's full decoded URL. - var decodedURL = decodeURI(this._url); - if (decodedURL !== this._url) { - resource = WebInspector.frameResourceManager.resourceForURL(decodedURL); - if (resource) - return resource; - } - - // Next try removing any fragment in the original URL. - var urlWithoutFragment = removeURLFragment(this._url); - if (urlWithoutFragment !== this._url) { - resource = WebInspector.frameResourceManager.resourceForURL(urlWithoutFragment); - if (resource) - return resource; - } - - // Finally try removing any fragment in the decoded URL. - var decodedURLWithoutFragment = removeURLFragment(decodedURL); - if (decodedURLWithoutFragment !== decodedURL) { - resource = WebInspector.frameResourceManager.resourceForURL(decodedURLWithoutFragment); - if (resource) - return resource; - } - } catch (e) { - // Ignore possible URIErrors. - } - - return null; - } -}; - -WebInspector.Script.prototype.__proto__ = WebInspector.SourceCode.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ScriptContentView.css b/Source/WebInspectorUI/UserInterface/ScriptContentView.css deleted file mode 100644 index 349510882..000000000 --- a/Source/WebInspectorUI/UserInterface/ScriptContentView.css +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.content-view.script > .text-editor { - position: absolute; - top: 0; - left: 0; - right: 0; - bottom: 0; -} diff --git a/Source/WebInspectorUI/UserInterface/ScriptContentView.js b/Source/WebInspectorUI/UserInterface/ScriptContentView.js deleted file mode 100644 index 63d0f07bd..000000000 --- a/Source/WebInspectorUI/UserInterface/ScriptContentView.js +++ /dev/null @@ -1,225 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ScriptContentView = function(script) -{ - WebInspector.ContentView.call(this, script); - - this.element.classList.add(WebInspector.ScriptContentView.StyleClassName); - - // Append a spinner while waiting for _contentWillPopulate. - var spinner = new WebInspector.IndeterminateProgressSpinner; - this.element.appendChild(spinner.element); - - this._script = script; - - // This view is only for standalone Scripts with no corresponding Resource. All other Scripts - // should be handled by TextResourceContentView via the Resource. - console.assert(!script.resource); - console.assert(script.range.startLine === 0); - console.assert(script.range.startColumn === 0); - - this._textEditor = new WebInspector.SourceCodeTextEditor(script); - this._textEditor.addEventListener(WebInspector.TextEditor.Event.ExecutionLineNumberDidChange, this._executionLineNumberDidChange, this); - this._textEditor.addEventListener(WebInspector.TextEditor.Event.NumberOfSearchResultsDidChange, this._numberOfSearchResultsDidChange, this); - this._textEditor.addEventListener(WebInspector.TextEditor.Event.FormattingDidChange, this._textEditorFormattingDidChange, this); - this._textEditor.addEventListener(WebInspector.SourceCodeTextEditor.Event.ContentWillPopulate, this._contentWillPopulate, this); - this._textEditor.addEventListener(WebInspector.SourceCodeTextEditor.Event.ContentDidPopulate, this._contentDidPopulate, this); - - var toolTip = WebInspector.UIString("Pretty print"); - var activatedToolTip = WebInspector.UIString("Original formatting"); - this._prettyPrintButtonNavigationItem = new WebInspector.ActivateButtonNavigationItem("pretty-print", toolTip, activatedToolTip, "Images/NavigationItemCurleyBraces.svg", 16, 16); - this._prettyPrintButtonNavigationItem.addEventListener(WebInspector.ButtonNavigationItem.Event.Clicked, this._togglePrettyPrint, this); - this._prettyPrintButtonNavigationItem.enabled = false; // Enabled when the text editor is populated with content. -}; - -WebInspector.ScriptContentView.StyleClassName = "script"; - -WebInspector.ScriptContentView.prototype = { - constructor: WebInspector.ScriptContentView, - - // Public - - get navigationItems() - { - return [this._prettyPrintButtonNavigationItem]; - }, - - get script() - { - return this._script; - }, - - get textEditor() - { - return this._textEditor; - }, - - get supplementalRepresentedObjects() - { - if (isNaN(this._textEditor.executionLineNumber)) - return []; - - // If the SourceCodeTextEditor has an executionLineNumber, we can assume - // it is always the active call frame. - return [WebInspector.debuggerManager.activeCallFrame]; - }, - - revealPosition: function(position, textRangeToSelect, forceUnformatted) - { - this._textEditor.revealPosition(position, textRangeToSelect, forceUnformatted); - }, - - shown: function() - { - this._textEditor.shown(); - }, - - hidden: function() - { - this._textEditor.hidden(); - }, - - closed: function() - { - this._textEditor.close(); - }, - - saveToCookie: function(cookie) - { - cookie.type = WebInspector.ContentViewCookieType.Resource; - cookie.url = this.representedObject.url; - }, - - restoreFromCookie: function(cookie) - { - if ("lineNumber" in cookie && "columnNumber" in cookie) - this.revealPosition(new WebInspector.SourceCodePosition(cookie.lineNumber, cookie.columnNumber)); - }, - - get supportsSave() - { - return true; - }, - - get saveData() - { - var url = this._script.url || "web-inspector:///" + encodeURI(this._script.displayName) + ".js"; - return {url: url, content: this._textEditor.string}; - }, - - get supportsSearch() - { - return true; - }, - - get numberOfSearchResults() - { - return this._textEditor.numberOfSearchResults; - }, - - get hasPerformedSearch() - { - return this._textEditor.currentSearchQuery !== null; - }, - - set automaticallyRevealFirstSearchResult(reveal) - { - this._textEditor.automaticallyRevealFirstSearchResult = reveal; - }, - - performSearch: function(query) - { - this._textEditor.performSearch(query); - }, - - searchCleared: function() - { - this._textEditor.searchCleared(); - }, - - searchQueryWithSelection: function() - { - return this._textEditor.searchQueryWithSelection(); - }, - - revealPreviousSearchResult: function(changeFocus) - { - this._textEditor.revealPreviousSearchResult(changeFocus); - }, - - revealNextSearchResult: function(changeFocus) - { - this._textEditor.revealNextSearchResult(changeFocus); - }, - - updateLayout: function() - { - this._textEditor.updateLayout(); - }, - - // Private - - _contentWillPopulate: function(event) - { - if (this._textEditor.element.parentNode === this.element) - return; - - // Allow editing any local file since edits can be saved and reloaded right from the Inspector. - if (this._script.urlComponents.scheme === "file") - this._textEditor.readOnly = false; - - this.element.removeChildren(); - this.element.appendChild(this._textEditor.element); - }, - - _contentDidPopulate: function(event) - { - this._prettyPrintButtonNavigationItem.enabled = this._textEditor.canBeFormatted(); - }, - - _togglePrettyPrint: function(event) - { - var activated = !this._prettyPrintButtonNavigationItem.activated; - this._textEditor.formatted = activated; - }, - - _textEditorFormattingDidChange: function(event) - { - this._prettyPrintButtonNavigationItem.activated = this._textEditor.formatted; - }, - - _executionLineNumberDidChange: function(event) - { - this.dispatchEventToListeners(WebInspector.ContentView.Event.SupplementalRepresentedObjectsDidChange); - }, - - _numberOfSearchResultsDidChange: function(event) - { - this.dispatchEventToListeners(WebInspector.ContentView.Event.NumberOfSearchResultsDidChange); - } -}; - -WebInspector.ScriptContentView.prototype.__proto__ = WebInspector.ContentView.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ScriptTimelineDataGrid.js b/Source/WebInspectorUI/UserInterface/ScriptTimelineDataGrid.js deleted file mode 100644 index c8c6f2ec2..000000000 --- a/Source/WebInspectorUI/UserInterface/ScriptTimelineDataGrid.js +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ScriptTimelineDataGrid = function(treeOutline, columns, editCallback, deleteCallback) -{ - WebInspector.TimelineDataGrid.call(this, treeOutline, columns, editCallback, deleteCallback); -} - -WebInspector.ScriptTimelineDataGrid.prototype = { - constructor: WebInspector.ScriptTimelineDataGrid, - - // Protected - - callFramePopoverAnchorElement: function() - { - return this.selectedNode.elementWithColumnIdentifier("location"); - } -} - -WebInspector.ScriptTimelineDataGrid.prototype.__proto__ = WebInspector.TimelineDataGrid.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ScriptTimelineDataGridNode.js b/Source/WebInspectorUI/UserInterface/ScriptTimelineDataGridNode.js deleted file mode 100644 index a8ea1712f..000000000 --- a/Source/WebInspectorUI/UserInterface/ScriptTimelineDataGridNode.js +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ScriptTimelineDataGridNode = function(scriptTimelineRecord, baseStartTime) -{ - WebInspector.TimelineDataGridNode.call(this, false, null); - - this._record = scriptTimelineRecord; - this._baseStartTime = baseStartTime || 0; -}; - -WebInspector.Object.addConstructorFunctions(WebInspector.ScriptTimelineDataGridNode); - -WebInspector.ScriptTimelineDataGridNode.IconStyleClassName = "icon"; - -WebInspector.ScriptTimelineDataGridNode.prototype = { - constructor: WebInspector.ScriptTimelineDataGridNode, - __proto__: WebInspector.TimelineDataGridNode.prototype, - - // Public - - get record() - { - return this._record; - }, - - get records() - { - return [this._record]; - }, - - get data() - { - var callFrameOrSourceCodeLocation = this._record.initiatorCallFrame || this._record.sourceCodeLocation; - return {eventType: this._record.eventType, details: this._record.details, startTime: this._record.startTime, duration: this._record.duration, location: callFrameOrSourceCodeLocation}; - }, - - createCellContent: function(columnIdentifier, cell) - { - const emptyValuePlaceholderString = "\u2014"; - var value = this.data[columnIdentifier]; - - switch (columnIdentifier) { - case "eventType": - return WebInspector.ScriptTimelineRecord.EventType.displayName(value, this._record.details); - - case "details": - return value ? value : emptyValuePlaceholderString; - - case "startTime": - return isNaN(value) ? emptyValuePlaceholderString : Number.secondsToString(value - this._baseStartTime); - - case "duration": - return isNaN(value) ? emptyValuePlaceholderString : Number.secondsToString(value); - } - - return WebInspector.TimelineDataGridNode.prototype.createCellContent.call(this, columnIdentifier, cell); - } -}; diff --git a/Source/WebInspectorUI/UserInterface/ScriptTimelineOverviewGraph.css b/Source/WebInspectorUI/UserInterface/ScriptTimelineOverviewGraph.css deleted file mode 100644 index f671511d9..000000000 --- a/Source/WebInspectorUI/UserInterface/ScriptTimelineOverviewGraph.css +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (C) 2014 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.timeline-overview-graph.script > .timeline-record-bar { - margin-top: 8px; - height: 20px; -} - -.timeline-overview-graph.script > .timeline-record-bar > .segment { - border-radius: 2px; -} diff --git a/Source/WebInspectorUI/UserInterface/ScriptTimelineOverviewGraph.js b/Source/WebInspectorUI/UserInterface/ScriptTimelineOverviewGraph.js deleted file mode 100644 index 904eae13e..000000000 --- a/Source/WebInspectorUI/UserInterface/ScriptTimelineOverviewGraph.js +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (C) 2014 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ScriptTimelineOverviewGraph = function(recording) -{ - WebInspector.TimelineOverviewGraph.call(this, recording); - - this.element.classList.add(WebInspector.ScriptTimelineOverviewGraph.StyleClassName); - - this._scriptTimeline = recording.timelines.get(WebInspector.TimelineRecord.Type.Script); - this._scriptTimeline.addEventListener(WebInspector.Timeline.Event.RecordAdded, this._scriptTimelineRecordAdded, this); - - this._timelineRecordBars = []; - - this.reset(); -}; - -WebInspector.ScriptTimelineOverviewGraph.StyleClassName = "script"; - -WebInspector.ScriptTimelineOverviewGraph.prototype = { - constructor: WebInspector.ScriptTimelineOverviewGraph, - __proto__: WebInspector.TimelineOverviewGraph.prototype, - - // Public - - reset: function() - { - WebInspector.TimelineOverviewGraph.prototype.reset.call(this); - - this._timelineRecordBarMap = new Map; - - this.element.removeChildren(); - }, - - updateLayout: function() - { - WebInspector.TimelineOverviewGraph.prototype.updateLayout.call(this); - - var visibleWidth = this.element.offsetWidth; - var secondsPerPixel = (this.endTime - this.startTime) / visibleWidth; - - var recordBarIndex = 0; - - function createBar(records, renderMode) - { - var timelineRecordBar = this._timelineRecordBars[recordBarIndex]; - if (!timelineRecordBar) - timelineRecordBar = this._timelineRecordBars[recordBarIndex] = new WebInspector.TimelineRecordBar; - timelineRecordBar.renderMode = renderMode; - timelineRecordBar.records = records; - timelineRecordBar.refresh(this); - if (!timelineRecordBar.element.parentNode) - this.element.appendChild(timelineRecordBar.element); - ++recordBarIndex; - } - - WebInspector.TimelineRecordBar.createCombinedBars(this._scriptTimeline.records, secondsPerPixel, this, createBar.bind(this)); - - // Remove the remaining unused TimelineRecordBars. - for (; recordBarIndex < this._timelineRecordBars.length; ++recordBarIndex) { - this._timelineRecordBars[recordBarIndex].records = null; - this._timelineRecordBars[recordBarIndex].element.remove(); - } - }, - - // Private - - _scriptTimelineRecordAdded: function(event) - { - this.needsLayout(); - } -}; diff --git a/Source/WebInspectorUI/UserInterface/ScriptTimelineRecord.js b/Source/WebInspectorUI/UserInterface/ScriptTimelineRecord.js deleted file mode 100644 index ab3531cb4..000000000 --- a/Source/WebInspectorUI/UserInterface/ScriptTimelineRecord.js +++ /dev/null @@ -1,264 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ScriptTimelineRecord = function(eventType, startTime, endTime, callFrames, sourceCodeLocation, details) -{ - WebInspector.TimelineRecord.call(this, WebInspector.TimelineRecord.Type.Script, startTime, endTime, callFrames, sourceCodeLocation); - - console.assert(eventType); - - if (eventType in WebInspector.ScriptTimelineRecord.EventType) - eventType = WebInspector.ScriptTimelineRecord.EventType[eventType]; - - this._eventType = eventType; - this._details = details || ""; -}; - -WebInspector.ScriptTimelineRecord.EventType = { - ScriptEvaluated: "script-timeline-record-script-evaluated", - EventDispatched: "script-timeline-record-event-dispatch", - TimerFired: "script-timeline-record-timer-fired", - TimerInstalled: "script-timeline-record-timer-installed", - TimerRemoved: "script-timeline-record-timer-removed", - AnimationFrameFired: "script-timeline-record-animation-frame-fired", - AnimationFrameRequested: "script-timeline-record-animation-frame-requested", - AnimationFrameCanceled: "script-timeline-record-animation-frame-canceled" -}; - -WebInspector.ScriptTimelineRecord.EventType.displayName = function(eventType, details, includeTimerIdentifierInMainTitle) -{ - if (details && !WebInspector.ScriptTimelineRecord._eventDisplayNames) { - // These display names are not localized because they closely represent - // the real API name, just with word spaces and Title Case. - - var nameMap = new Map; - nameMap.set("DOMActivate", "DOM Activate"); - nameMap.set("DOMCharacterDataModified", "DOM Character Data Modified"); - nameMap.set("DOMContentLoaded", "DOM Content Loaded"); - nameMap.set("DOMFocusIn", "DOM Focus In"); - nameMap.set("DOMFocusOut", "DOM Focus Out"); - nameMap.set("DOMNodeInserted", "DOM Node Inserted"); - nameMap.set("DOMNodeInsertedIntoDocument", "DOM Node Inserted Into Document"); - nameMap.set("DOMNodeRemoved", "DOM Node Removed"); - nameMap.set("DOMNodeRemovedFromDocument", "DOM Node Removed From Document"); - nameMap.set("DOMSubtreeModified", "DOM Sub-Tree Modified"); - nameMap.set("addsourcebuffer", "Add Source Buffer"); - nameMap.set("addstream", "Add Stream"); - nameMap.set("addtrack", "Add Track"); - nameMap.set("audioend", "Audio End"); - nameMap.set("audioprocess", "Audio Process"); - nameMap.set("audiostart", "Audio Start"); - nameMap.set("beforecopy", "Before Copy"); - nameMap.set("beforecut", "Before Cut"); - nameMap.set("beforeload", "Before Load"); - nameMap.set("beforepaste", "Before Paste"); - nameMap.set("beforeunload", "Before Unload"); - nameMap.set("canplay", "Can Play"); - nameMap.set("canplaythrough", "Can Play Through"); - nameMap.set("chargingchange", "Charging Change"); - nameMap.set("chargingtimechange", "Charging Time Change"); - nameMap.set("compositionend", "Composition End"); - nameMap.set("compositionstart", "Composition Start"); - nameMap.set("compositionupdate", "Composition Update"); - nameMap.set("contextmenu", "Context Menu"); - nameMap.set("cuechange", "Cue Change"); - nameMap.set("datachannel", "Data Channel"); - nameMap.set("dblclick", "Double Click"); - nameMap.set("devicemotion", "Device Motion"); - nameMap.set("deviceorientation", "Device Orientation"); - nameMap.set("dischargingtimechange", "Discharging Time Change"); - nameMap.set("dragend", "Drag End"); - nameMap.set("dragenter", "Drag Enter"); - nameMap.set("dragleave", "Drag Leave"); - nameMap.set("dragover", "Drag Over"); - nameMap.set("dragstart", "Drag Start"); - nameMap.set("durationchange", "Duration Change"); - nameMap.set("focusin", "Focus In"); - nameMap.set("focusout", "Focus Out"); - nameMap.set("gesturechange", "Gesture Change"); - nameMap.set("gestureend", "Gesture End"); - nameMap.set("gesturescrollend", "Gesture Scroll End"); - nameMap.set("gesturescrollstart", "Gesture Scroll Start"); - nameMap.set("gesturescrollupdate", "Gesture Scroll Update"); - nameMap.set("gesturestart", "Gesture Start"); - nameMap.set("gesturetap", "Gesture Tap"); - nameMap.set("gesturetapdown", "Gesture Tap Down"); - nameMap.set("hashchange", "Hash Change"); - nameMap.set("icecandidate", "ICE Candidate"); - nameMap.set("iceconnectionstatechange", "ICE Connection State Change"); - nameMap.set("keydown", "Key Down"); - nameMap.set("keypress", "Key Press"); - nameMap.set("keyup", "Key Up"); - nameMap.set("levelchange", "Level Change"); - nameMap.set("loadeddata", "Loaded Data"); - nameMap.set("loadedmetadata", "Loaded Metadata"); - nameMap.set("loadend", "Load End"); - nameMap.set("loadingdone", "Loading Done"); - nameMap.set("loadstart", "Load Start"); - nameMap.set("mousedown", "Mouse Down"); - nameMap.set("mouseenter", "Mouse Enter"); - nameMap.set("mouseleave", "Mouse Leave"); - nameMap.set("mousemove", "Mouse Move"); - nameMap.set("mouseout", "Mouse Out"); - nameMap.set("mouseover", "Mouse Over"); - nameMap.set("mouseup", "Mouse Up"); - nameMap.set("mousewheel", "Mouse Wheel"); - nameMap.set("negotiationneeded", "Negotiation Needed"); - nameMap.set("nomatch", "No Match"); - nameMap.set("noupdate", "No Update"); - nameMap.set("orientationchange", "Orientation Change"); - nameMap.set("overflowchanged", "Overflow Changed"); - nameMap.set("pagehide", "Page Hide"); - nameMap.set("pageshow", "Page Show"); - nameMap.set("popstate", "Pop State"); - nameMap.set("ratechange", "Rate Change"); - nameMap.set("readystatechange", "Ready State Change"); - nameMap.set("removesourcebuffer", "Remove Source Buffer"); - nameMap.set("removestream", "Remove Stream"); - nameMap.set("removetrack", "Remove Track"); - nameMap.set("securitypolicyviolation", "Security Policy Violation"); - nameMap.set("selectionchange", "Selection Change"); - nameMap.set("selectstart", "Select Start"); - nameMap.set("signalingstatechange", "Signaling State Change"); - nameMap.set("soundend", "Sound End"); - nameMap.set("soundstart", "Sound Start"); - nameMap.set("sourceclose", "Source Close"); - nameMap.set("sourceended", "Source Ended"); - nameMap.set("sourceopen", "Source Open"); - nameMap.set("speechend", "Speech End"); - nameMap.set("speechstart", "Speech Start"); - nameMap.set("textInput", "Text Input"); - nameMap.set("timeupdate", "Time Update"); - nameMap.set("tonechange", "Tone Change"); - nameMap.set("touchcancel", "Touch Cancel"); - nameMap.set("touchend", "Touch End"); - nameMap.set("touchmove", "Touch Move"); - nameMap.set("touchstart", "Touch Start"); - nameMap.set("transitionend", "Transition End"); - nameMap.set("updateend", "Update End"); - nameMap.set("updateready", "Update Ready"); - nameMap.set("updatestart", "Update Start"); - nameMap.set("upgradeneeded", "Upgrade Needed"); - nameMap.set("versionchange", "Version Change"); - nameMap.set("visibilitychange", "Visibility Change"); - nameMap.set("volumechange", "Volume Change"); - nameMap.set("webglcontextcreationerror", "WebGL Context Creation Error"); - nameMap.set("webglcontextlost", "WebGL Context Lost"); - nameMap.set("webglcontextrestored", "WebGL Context Restored"); - nameMap.set("webkitAnimationEnd", "Animation End"); - nameMap.set("webkitAnimationIteration", "Animation Iteration"); - nameMap.set("webkitAnimationStart", "Animation Start"); - nameMap.set("webkitBeforeTextInserted", "Before Text Inserted"); - nameMap.set("webkitEditableContentChanged", "Editable Content Changed"); - nameMap.set("webkitTransitionEnd", "Transition End"); - nameMap.set("webkitaddsourcebuffer", "Add Source Buffer"); - nameMap.set("webkitbeginfullscreen", "Begin Fullscreen"); - nameMap.set("webkitcurrentplaybacktargetiswirelesschanged", "Current Playback Target Is Wireless Changed"); - nameMap.set("webkitdeviceproximity", "Device Proximity"); - nameMap.set("webkitendfullscreen", "End Fullscreen"); - nameMap.set("webkitfullscreenchange", "Fullscreen Change"); - nameMap.set("webkitfullscreenerror", "Fullscreen Error"); - nameMap.set("webkitkeyadded", "Key Added"); - nameMap.set("webkitkeyerror", "Key Error"); - nameMap.set("webkitkeymessage", "Key Message"); - nameMap.set("webkitneedkey", "Need Key"); - nameMap.set("webkitnetworkinfochange", "Network Info Change"); - nameMap.set("webkitplaybacktargetavailabilitychanged", "Playback Target Availability Changed"); - nameMap.set("webkitpointerlockchange", "Pointer Lock Change"); - nameMap.set("webkitpointerlockerror", "Pointer Lock Error"); - nameMap.set("webkitregionlayoutupdate", "Region Layout Update"); - nameMap.set("webkitregionoversetchange", "Region Overset Change"); - nameMap.set("webkitremovesourcebuffer", "Remove Source Buffer"); - nameMap.set("webkitresourcetimingbufferfull", "Resource Timing Buffer Full"); - nameMap.set("webkitsourceclose", "Source Close"); - nameMap.set("webkitsourceended", "Source Ended"); - nameMap.set("webkitsourceopen", "Source Open"); - nameMap.set("webkitspeechchange", "Speech Change"); - nameMap.set("writeend", "Write End"); - nameMap.set("writestart", "Write Start"); - - WebInspector.ScriptTimelineRecord._eventDisplayNames = nameMap; - } - - switch(eventType) { - case WebInspector.ScriptTimelineRecord.EventType.ScriptEvaluated: - return WebInspector.UIString("Script Evaluated"); - case WebInspector.ScriptTimelineRecord.EventType.EventDispatched: - if (details && (details instanceof String || typeof details === "string")) { - var eventDisplayName = WebInspector.ScriptTimelineRecord._eventDisplayNames.get(details) || details.capitalize(); - return WebInspector.UIString("%s Event Dispatched").format(eventDisplayName); - } - - return WebInspector.UIString("Event Dispatched"); - case WebInspector.ScriptTimelineRecord.EventType.TimerFired: - if (details && includeTimerIdentifierInMainTitle) - return WebInspector.UIString("Timer %s Fired").format(details); - return WebInspector.UIString("Timer Fired"); - case WebInspector.ScriptTimelineRecord.EventType.TimerInstalled: - if (details && includeTimerIdentifierInMainTitle) - return WebInspector.UIString("Timer %s Installed").format(details); - return WebInspector.UIString("Timer Installed"); - case WebInspector.ScriptTimelineRecord.EventType.TimerRemoved: - if (details && includeTimerIdentifierInMainTitle) - return WebInspector.UIString("Timer %s Removed").format(details); - return WebInspector.UIString("Timer Removed"); - case WebInspector.ScriptTimelineRecord.EventType.AnimationFrameFired: - return WebInspector.UIString("Animation Frame Fired"); - case WebInspector.ScriptTimelineRecord.EventType.AnimationFrameRequested: - return WebInspector.UIString("Animation Frame Requested"); - case WebInspector.ScriptTimelineRecord.EventType.AnimationFrameCanceled: - return WebInspector.UIString("Animation Frame Canceled"); - } -}; - -WebInspector.ScriptTimelineRecord.TypeIdentifier = "script-timeline-record"; -WebInspector.ScriptTimelineRecord.EventTypeCookieKey = "script-timeline-record-event-type"; -WebInspector.ScriptTimelineRecord.DetailsCookieKey = "script-timeline-record-details"; - -WebInspector.ScriptTimelineRecord.prototype = { - constructor: WebInspector.ScriptTimelineRecord, - - // Public - - get eventType() - { - return this._eventType; - }, - - get details() - { - return this._details; - }, - - saveIdentityToCookie: function(cookie) - { - WebInspector.TimelineRecord.prototype.saveIdentityToCookie.call(this, cookie); - - cookie[WebInspector.ScriptTimelineRecord.EventTypeCookieKey] = this._eventType; - cookie[WebInspector.ScriptTimelineRecord.DetailsCookieKey] = this._details; - } -}; - -WebInspector.ScriptTimelineRecord.prototype.__proto__ = WebInspector.TimelineRecord.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ScriptTimelineView.css b/Source/WebInspectorUI/UserInterface/ScriptTimelineView.css deleted file mode 100644 index 09ff34bce..000000000 --- a/Source/WebInspectorUI/UserInterface/ScriptTimelineView.css +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2014 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.timeline-view.script > .data-grid { - position: absolute; - top: 0; - left: 0; - right: 0; - bottom: 0; -} - -.timeline-view.script > .data-grid .eventType-column { - border-right: none; -} - -.sidebar > .panel.timeline.timeline-content-view-showing .navigation-sidebar-panel-content-tree-outline.script .item .subtitle { - display: none; -} diff --git a/Source/WebInspectorUI/UserInterface/ScriptTimelineView.js b/Source/WebInspectorUI/UserInterface/ScriptTimelineView.js deleted file mode 100644 index 7a58011a5..000000000 --- a/Source/WebInspectorUI/UserInterface/ScriptTimelineView.js +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Copyright (C) 2014 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ScriptTimelineView = function(recording) -{ - WebInspector.TimelineView.call(this); - - this.navigationSidebarTreeOutline.onselect = this._treeElementSelected.bind(this); - this.navigationSidebarTreeOutline.element.classList.add(WebInspector.NavigationSidebarPanel.HideDisclosureButtonsStyleClassName); - this.navigationSidebarTreeOutline.element.classList.add(WebInspector.ScriptTimelineView.TreeOutlineStyleClassName); - - var columns = {eventType: {}, location: {}, startTime: {}, duration: {}}; - - columns.eventType.title = WebInspector.UIString("Type"); - columns.eventType.width = "15%"; - columns.eventType.scopeBar = WebInspector.TimelineDataGrid.createColumnScopeBar("script", WebInspector.ScriptTimelineRecord.EventType); - columns.eventType.hidden = true; - - columns.location.title = WebInspector.UIString("Location"); - columns.location.width = "15%"; - - columns.startTime.title = WebInspector.UIString("Start Time"); - columns.startTime.width = "10%"; - columns.startTime.aligned = "right"; - columns.startTime.sort = "ascending"; - - columns.duration.title = WebInspector.UIString("Duration"); - columns.duration.width = "10%"; - columns.duration.aligned = "right"; - - for (var column in columns) - columns[column].sortable = true; - - this._dataGrid = new WebInspector.ScriptTimelineDataGrid(this.navigationSidebarTreeOutline, columns); - this._dataGrid.addEventListener(WebInspector.TimelineDataGrid.Event.FiltersDidChange, this._dataGridFiltersDidChange, this); - this._dataGrid.addEventListener(WebInspector.DataGrid.Event.SelectedNodeChanged, this._dataGridNodeSelected, this); - - this.element.classList.add(WebInspector.ScriptTimelineView.StyleClassName); - this.element.appendChild(this._dataGrid.element); - - var scriptTimeline = recording.timelines.get(WebInspector.TimelineRecord.Type.Script); - scriptTimeline.addEventListener(WebInspector.Timeline.Event.RecordAdded, this._scriptTimelineRecordAdded, this); - - this._pendingRecords = []; -}; - -WebInspector.ScriptTimelineView.StyleClassName = "script"; -WebInspector.ScriptTimelineView.TreeOutlineStyleClassName = "script"; - -WebInspector.ScriptTimelineView.prototype = { - constructor: WebInspector.ScriptTimelineView, - __proto__: WebInspector.TimelineView.prototype, - - // Public - - get navigationSidebarTreeOutlineLabel() - { - return WebInspector.UIString("Records"); - }, - - shown: function() - { - WebInspector.TimelineView.prototype.shown.call(this); - - this._dataGrid.shown(); - }, - - hidden: function() - { - this._dataGrid.hidden(); - - WebInspector.TimelineView.prototype.hidden.call(this); - }, - - updateLayout: function() - { - WebInspector.TimelineView.prototype.updateLayout.call(this); - - this._dataGrid.updateLayout(); - - this._processPendingRecords(); - }, - - matchTreeElementAgainstCustomFilters: function(treeElement) - { - return this._dataGrid.treeElementMatchesActiveScopeFilters(treeElement); - }, - - reset: function() - { - WebInspector.TimelineView.prototype.reset.call(this); - - this._dataGrid.reset(); - }, - - // Protected - - treeElementPathComponentSelected: function(event) - { - var dataGridNode = this._dataGrid.dataGridNodeForTreeElement(event.data.pathComponent.generalTreeElement); - if (!dataGridNode) - return; - dataGridNode.revealAndSelect(); - }, - - // Private - - _processPendingRecords: function() - { - if (!this._pendingRecords.length) - return; - - for (var scriptTimelineRecord of this._pendingRecords) { - var treeElement = new WebInspector.TimelineRecordTreeElement(scriptTimelineRecord, WebInspector.SourceCodeLocation.NameStyle.Short, true); - var dataGridNode = new WebInspector.ScriptTimelineDataGridNode(scriptTimelineRecord, this.zeroTime); - - this._dataGrid.addRowInSortOrder(treeElement, dataGridNode); - } - - this._pendingRecords = []; - }, - - _scriptTimelineRecordAdded: function(event) - { - var scriptTimelineRecord = event.data.record; - console.assert(scriptTimelineRecord instanceof WebInspector.ScriptTimelineRecord); - - this._pendingRecords.push(scriptTimelineRecord); - - this.needsLayout(); - }, - - _dataGridFiltersDidChange: function(event) - { - WebInspector.timelineSidebarPanel.updateFilter(); - }, - - _dataGridNodeSelected: function(event) - { - this.dispatchEventToListeners(WebInspector.TimelineView.Event.SelectionPathComponentsDidChange); - }, - - _treeElementSelected: function(treeElement, selectedByUser) - { - if (this._dataGrid.shouldIgnoreSelectionEvent()) - return; - - if (!WebInspector.timelineSidebarPanel.canShowDifferentContentView()) - return; - - if (treeElement instanceof WebInspector.FolderTreeElement) - return; - - if (!(treeElement instanceof WebInspector.TimelineRecordTreeElement)) { - console.error("Unknown tree element selected."); - return; - } - - if (!treeElement.record.sourceCodeLocation) { - WebInspector.timelineSidebarPanel.showTimelineView(WebInspector.TimelineRecord.Type.Script); - return; - } - - WebInspector.resourceSidebarPanel.showOriginalOrFormattedSourceCodeLocation(treeElement.record.sourceCodeLocation); - } -}; diff --git a/Source/WebInspectorUI/UserInterface/ScriptTreeElement.js b/Source/WebInspectorUI/UserInterface/ScriptTreeElement.js deleted file mode 100644 index 7023bb188..000000000 --- a/Source/WebInspectorUI/UserInterface/ScriptTreeElement.js +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ScriptTreeElement = function(script) -{ - console.assert(script instanceof WebInspector.Script); - - WebInspector.SourceCodeTreeElement.call(this, script, WebInspector.ScriptTreeElement.StyleClassName, null, null, script, false); - - this.mainTitle = script.displayName; - - if (script.url) { - // Show the host as the subtitle if it is different from the main title. - var subtitle = WebInspector.displayNameForHost(script.urlComponents.host); - this.subtitle = this.mainTitle !== subtitle ? subtitle : null; - - this.tooltip = script.url; - - this.addClassName(WebInspector.ResourceTreeElement.ResourceIconStyleClassName); - this.addClassName(WebInspector.Resource.Type.Script); - } else - this.addClassName(WebInspector.ScriptTreeElement.AnonymousScriptIconStyleClassName); - - this._script = script; -}; - -WebInspector.ScriptTreeElement.AnonymousScriptIconStyleClassName = "anonymous-script-icon"; -WebInspector.ScriptTreeElement.StyleClassName = "script"; - -WebInspector.ScriptTreeElement.prototype = { - constructor: WebInspector.ScriptTreeElement, - - // Public - - get script() - { - return this._script; - } -}; - -WebInspector.ScriptTreeElement.prototype.__proto__ = WebInspector.SourceCodeTreeElement.prototype; diff --git a/Source/WebInspectorUI/UserInterface/SearchBar.css b/Source/WebInspectorUI/UserInterface/SearchBar.css deleted file mode 100644 index 7275e4c55..000000000 --- a/Source/WebInspectorUI/UserInterface/SearchBar.css +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.search-bar > input[type="search"] { - margin: 1px 6px; - - outline: none; - - -webkit-appearance: none; - - border: 1px solid rgba(0, 0, 0, 0.35); - border-radius: 10px; - background-color: rgba(255, 255, 255, 0.2); - box-shadow: inset rgba(0, 0, 0, 0.1) 0 1px 0; - background-clip: padding-box; - - height: 19px; - - transition: background-color 200ms ease-in-out; -} - -.search-bar > input[type="search"]::-webkit-input-placeholder { - color: rgba(0, 0, 0, 0.35); -} - -.search-bar > input[type="search"]:focus { background-color: white; } -.search-bar > input[type="search"]:not(:placeholder-shown) { background-color: white; } /* Needs to be a separate rule. See http://webkit.org/b/118162 */ diff --git a/Source/WebInspectorUI/UserInterface/SearchBar.js b/Source/WebInspectorUI/UserInterface/SearchBar.js deleted file mode 100644 index 0f91f4283..000000000 --- a/Source/WebInspectorUI/UserInterface/SearchBar.js +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.SearchBar = function(identifier, placeholder, delegate) { - WebInspector.NavigationItem.call(this, identifier); - - this.delegate = delegate; - - this._element.classList.add(WebInspector.SearchBar.StyleClassName); - - this._keyboardShortcutEsc = new WebInspector.KeyboardShortcut(null, WebInspector.KeyboardShortcut.Key.Escape); - this._keyboardShortcutEnter = new WebInspector.KeyboardShortcut(null, WebInspector.KeyboardShortcut.Key.Enter); - - this._searchInput = this._element.appendChild(document.createElement("input")); - this._searchInput.type = "search"; - this._searchInput.spellcheck = false; - this._searchInput.incremental = true; - this._searchInput.setAttribute("results", 5); - this._searchInput.setAttribute("autosave", identifier + "-autosave"); - this._searchInput.setAttribute("placeholder", placeholder); - this._searchInput.addEventListener("search", this._handleSearchEvent.bind(this), false); - this._searchInput.addEventListener("keydown", this._handleKeydownEvent.bind(this), false); -}; - -WebInspector.SearchBar.StyleClassName = "search-bar"; -WebInspector.SearchBar.Event = { - TextChanged: "searchbar-text-did-change" -}; - -WebInspector.SearchBar.prototype = { - constructor: WebInspector.SearchBar, - - // Public - - get text() - { - return this._searchInput.value; - }, - - set text(newText) - { - this._searchInput.value = newText; - }, - - focus: function() - { - this._searchInput.focus(); - this._searchInput.select(); - }, - - // Private - - _handleSearchEvent: function(event) - { - this.dispatchEventToListeners(WebInspector.SearchBar.Event.TextChanged); - }, - - _handleKeydownEvent: function(event) - { - if (this._keyboardShortcutEsc.matchesEvent(event)) { - if (this.delegate && typeof this.delegate.searchBarWantsToLoseFocus === "function") { - this.delegate.searchBarWantsToLoseFocus(this); - event.stopPropagation(); - event.preventDefault(); - } - } else if (this._keyboardShortcutEnter.matchesEvent(event)) { - if (this.delegate && typeof this.delegate.searchBarDidActivate === "function") { - this.delegate.searchBarDidActivate(this); - event.stopPropagation(); - event.preventDefault(); - } - } - } -}; - -WebInspector.SearchBar.prototype.__proto__ = WebInspector.NavigationItem.prototype; diff --git a/Source/WebInspectorUI/UserInterface/SearchIcons.css b/Source/WebInspectorUI/UserInterface/SearchIcons.css deleted file mode 100644 index 9afb66d7c..000000000 --- a/Source/WebInspectorUI/UserInterface/SearchIcons.css +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.dom-match-element-icon .icon { - content: url(Images/DOMElement.svg); -} - -.dom-match-text-node-icon .icon { - content: url(Images/DOMTextNode.svg); -} - -.dom-match-comment-icon .icon { - content: url(Images/DOMComment.svg); -} - -.dom-match-document-type-icon .icon { - content: url(Images/DOMDocumentType.svg); -} - -.dom-match-character-data-icon .icon { - content: url(Images/DOMCharacterData.svg); -} - -.dom-match-node-icon .icon { - content: url(Images/DOMNode.svg); -} - -.resource-match-icon .icon { - content: url(Images/ResultLine.svg); -} diff --git a/Source/WebInspectorUI/UserInterface/SearchResultTreeElement.js b/Source/WebInspectorUI/UserInterface/SearchResultTreeElement.js deleted file mode 100644 index d668d0f8b..000000000 --- a/Source/WebInspectorUI/UserInterface/SearchResultTreeElement.js +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.SearchResultTreeElement = function(representedObject) -{ - console.assert(representedObject instanceof WebInspector.DOMSearchMatchObject || representedObject instanceof WebInspector.ResourceSearchMatchObject); - - var title = WebInspector.SearchResultTreeElement.truncateAndHighlightTitle(representedObject.title, representedObject.searchTerm, representedObject.sourceCodeTextRange); - - WebInspector.GeneralTreeElement.call(this, representedObject.className, title, null, representedObject, false); - this.small = true; -}; - -WebInspector.SearchResultTreeElement.CharactersToShowBeforeSearchMatch = 15; -WebInspector.SearchResultTreeElement.CharactersToShowAfterSearchMatch = 50; -WebInspector.SearchResultTreeElement.HighlightedStyleClassName = "highlighted"; - -WebInspector.SearchResultTreeElement.prototype = { - constructor: WebInspector.SearchResultTreeElement, - - // Public - - get filterableData() - { - return {text: this.representedObject.title}; - } -}; - -WebInspector.SearchResultTreeElement.prototype.__proto__ = WebInspector.GeneralTreeElement.prototype; - -WebInspector.SearchResultTreeElement.truncateAndHighlightTitle = function(title, searchTerm, sourceCodeTextRange) -{ - // Use the original location, since those line/column offsets match the line text in title. - var textRange = sourceCodeTextRange.textRange; - - var searchTermIndex = textRange.startColumn; - - // We should only have one line text ranges, so make sure that is the case. - console.assert(textRange.startLine === textRange.endLine); - - // Show some characters before the matching text (if there are enough) for context. TreeOutline takes care of the truncating - // at the end of the string. - var modifiedTitle = null; - if (searchTermIndex > WebInspector.SearchResultTreeElement.CharactersToShowBeforeSearchMatch) { - modifiedTitle = "\u2026" + title.substring(searchTermIndex - WebInspector.SearchResultTreeElement.CharactersToShowBeforeSearchMatch); - searchTermIndex = WebInspector.SearchResultTreeElement.CharactersToShowBeforeSearchMatch + 1; - } else - modifiedTitle = title; - - // Truncate the tail of the title so the tooltip isn't so large. - modifiedTitle = modifiedTitle.trimEnd(searchTermIndex + searchTerm.length + WebInspector.SearchResultTreeElement.CharactersToShowAfterSearchMatch); - - console.assert(modifiedTitle.substring(searchTermIndex, searchTermIndex + searchTerm.length).toLowerCase() === searchTerm.toLowerCase()); - - var highlightedTitle = document.createDocumentFragment(); - - highlightedTitle.appendChild(document.createTextNode(modifiedTitle.substring(0, searchTermIndex))); - - var highlightSpan = document.createElement("span"); - highlightSpan.className = WebInspector.SearchResultTreeElement.HighlightedStyleClassName; - highlightSpan.appendChild(document.createTextNode(modifiedTitle.substring(searchTermIndex, searchTermIndex + searchTerm.length))); - highlightedTitle.appendChild(highlightSpan); - - highlightedTitle.appendChild(document.createTextNode(modifiedTitle.substring(searchTermIndex + searchTerm.length))); - - return highlightedTitle; -} diff --git a/Source/WebInspectorUI/UserInterface/Section.css b/Source/WebInspectorUI/UserInterface/Section.css deleted file mode 100644 index 299fc0550..000000000 --- a/Source/WebInspectorUI/UserInterface/Section.css +++ /dev/null @@ -1,195 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.section { - position: relative; -} - -.section .header { - color: black; - padding: 0 8px 0 18px; - min-height: 18px; - white-space: nowrap; - background-origin: padding; - background-clip: padding; -} - -.section .header::before { - position: absolute; - top: 5px; - left: 7px; - - width: 8px; - height: 8px; - - background-image: -webkit-canvas(disclosure-triangle-tiny-closed-normal); - background-size: 8px 8px; - background-repeat: no-repeat; - - content: ""; -} - -.section.expanded .header::before { - background-image: -webkit-canvas(disclosure-triangle-tiny-open-normal); -} - -.section .header .title, .event-bar .header .title { - font-weight: normal; - word-wrap: break-word; - white-space: normal; - line-height: 18px; -} - -.section .header .title.blank-title { - font-style: italic; -} - -.section .header label, .event-bar .header label { - display: none; -} - -.section.expanded .header label, .event-bar.expanded .header label { - display: inline; -} - -.section .header .subtitle, .event-bar .header .subtitle { - float: right; - margin-left: 5px; - max-width: 55%; - text-overflow: ellipsis; - overflow: hidden; -} - -.section .header .subtitle a { - color: inherit; -} - -.section .properties, .event-bar .event-properties { - display: none; -} - -.section.expanded .properties, .event-bar.expanded .event-properties { - display: block; - padding-left: 16px; -} - -.section.expanded.no-header .properties { - padding-left: 0; -} - -.section.no-affect .properties li { - opacity: 0.5; -} - -.section.no-affect .properties li.editing { - opacity: 1.0; -} - -.properties-tree { - margin: 0; - padding: 0 6px 2px; - list-style: none; - min-height: 18px; - outline: none; -} - -.properties-tree li { - margin-left: 12px; - white-space: nowrap; - text-overflow: ellipsis; - overflow: hidden; - -webkit-user-select: text; - cursor: default; -} - -.properties-tree li.parent { - margin-left: 1px; -} - -.properties-tree li.parent::before { - float: left; - - content: ""; - - background-image: -webkit-canvas(disclosure-triangle-tiny-closed-normal); - background-size: 8px 8px; - background-repeat: no-repeat; - - width: 8px; - height: 8px; - - margin-top: 3px; - padding-right: 2px; -} - -.properties-tree li.parent.expanded::before { - background-image: -webkit-canvas(disclosure-triangle-tiny-open-normal); -} - -.properties-tree li .info { - padding-top: 4px; - padding-bottom: 3px; -} - -.properties-tree ol { - display: none; - margin: 0; - -webkit-padding-start: 12px; - list-style: none; -} - -.properties-tree ol.expanded { - display: block; -} - -.section .properties li.editing-sub-part { - padding: 3px 6px 8px 18px; - margin: -3px -6px -8px -6px; - text-overflow: clip; -} - -.section .properties .name, .event-properties .name { - color: rgb(136, 19, 145); -} - -.section .properties .dimmed { - opacity: 0.6; -} - -.section .properties .value.error { - color: red; -} - -.section .properties .number, .event-properties .number { - color: blue; -} - -.section .properties .keyword, .event-properties .keyword { - color: rgb(136, 19, 79); -} - -.section .properties .color, .event-properties .color { - color: rgb(118, 15, 21); -} diff --git a/Source/WebInspectorUI/UserInterface/Section.js b/Source/WebInspectorUI/UserInterface/Section.js deleted file mode 100644 index 5305b0b06..000000000 --- a/Source/WebInspectorUI/UserInterface/Section.js +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.Section = function(title, subtitle) -{ - WebInspector.Object.call(this); - - this.element = document.createElement("div"); - this.element.className = "section"; - this.element._section = this; - - if (typeof title === "string" || title instanceof Node || typeof subtitle === "string") { - this.headerElement = document.createElement("div"); - this.headerElement.className = "header"; - - this.titleElement = document.createElement("div"); - this.titleElement.className = "title"; - - this.subtitleElement = document.createElement("div"); - this.subtitleElement.className = "subtitle"; - - this.headerElement.appendChild(this.subtitleElement); - this.headerElement.appendChild(this.titleElement); - - this.headerElement.addEventListener("click", this.handleClick.bind(this), false); - this.element.appendChild(this.headerElement); - - this.title = title; - this.subtitle = subtitle; - } else - this.element.classList.add("no-header"); - - this._expanded = false; - - if (!this.headerElement) - this.expand(); -}; - -WebInspector.Section.Event = { - VisibleContentDidChange: "section-visible-content-did-change" -}; - -WebInspector.Section.prototype = { - get title() - { - return this._title; - }, - - set title(x) - { - if (this._title === x) - return; - this._title = x; - - if (x instanceof Node) { - this.titleElement.removeChildren(); - this.titleElement.appendChild(x); - } else - this.titleElement.textContent = x; - }, - - get subtitle() - { - return this._subtitle; - }, - - set subtitle(x) - { - if (this._subtitle === x) - return; - this._subtitle = x; - this.subtitleElement.textContent = x; - }, - - get subtitleAsTextForTest() - { - var result = this.subtitleElement.textContent; - var child = this.subtitleElement.querySelector("[data-uncopyable]"); - if (child) { - var linkData = child.getAttribute("data-uncopyable"); - if (linkData) - result += linkData; - } - return result; - }, - - get expanded() - { - return this._expanded; - }, - - set expanded(x) - { - if (x) - this.expand(); - else - this.collapse(); - }, - - get populated() - { - return this._populated; - }, - - set populated(x) - { - this._populated = x; - if (!x && this._expanded) { - this.onpopulate(); - this._populated = true; - } - }, - - onpopulate: function() - { - // Overriden by subclasses. - }, - - get firstSibling() - { - var parent = this.element.parentElement; - if (!parent) - return null; - - var childElement = parent.firstChild; - while (childElement) { - if (childElement._section) - return childElement._section; - childElement = childElement.nextSibling; - } - - return null; - }, - - get lastSibling() - { - var parent = this.element.parentElement; - if (!parent) - return null; - - var childElement = parent.lastChild; - while (childElement) { - if (childElement._section) - return childElement._section; - childElement = childElement.previousSibling; - } - - return null; - }, - - get nextSibling() - { - var curElement = this.element; - do { - curElement = curElement.nextSibling; - } while (curElement && !curElement._section); - - return curElement ? curElement._section : null; - }, - - get previousSibling() - { - var curElement = this.element; - do { - curElement = curElement.previousSibling; - } while (curElement && !curElement._section); - - return curElement ? curElement._section : null; - }, - - expand: function() - { - if (this._expanded) - return; - this._expanded = true; - this.element.classList.add("expanded"); - - if (!this._populated) { - this.onpopulate(); - this._populated = true; - } else - this.dispatchEventToListeners(WebInspector.Section.Event.VisibleContentDidChange); - }, - - collapse: function() - { - if (!this._expanded) - return; - this._expanded = false; - this.element.classList.remove("expanded"); - }, - - toggleExpanded: function() - { - this.expanded = !this.expanded; - }, - - handleClick: function(e) - { - this.toggleExpanded(); - e.stopPropagation(); - } -}; - -WebInspector.Section.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/Setting.js b/Source/WebInspectorUI/UserInterface/Setting.js deleted file mode 100644 index 79a80116b..000000000 --- a/Source/WebInspectorUI/UserInterface/Setting.js +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (C) 2009 Google Inc. All rights reserved. - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.Setting = function(name, defaultValue) -{ - this._name = name; - this._localStorageKey = WebInspector.Setting.LocalStorageKeyPrefix + name; - this._defaultValue = defaultValue; -} - -WebInspector.Object.addConstructorFunctions(WebInspector.Setting); - -WebInspector.Setting.Event = { - Changed: "setting-changed" -}; - -WebInspector.Setting.LocalStorageKeyPrefix = "com.apple.WebInspector."; - -WebInspector.Setting.prototype = { - constructor: WebInspector.Setting, - - // Public - - get name() - { - return this._name; - }, - - get value() - { - if ("_value" in this) - return this._value; - - // Make a copy of the default value so changes to object values don't modify the default value. - this._value = JSON.parse(JSON.stringify(this._defaultValue)); - - if (window.localStorage && this._localStorageKey in window.localStorage) { - try { - this._value = JSON.parse(window.localStorage[this._localStorageKey]); - } catch(e) { - delete window.localStorage[this._localStorageKey]; - } - } - - return this._value; - }, - - set value(value) - { - this._value = value; - - if (window.localStorage) { - try { - // Use Object.shallowEqual to properly compare objects. - if (Object.shallowEqual(this._value, this._defaultValue)) - delete window.localStorage[this._localStorageKey]; - else - window.localStorage[this._localStorageKey] = JSON.stringify(this._value); - } catch(e) { - console.error("Error saving setting with name: " + this._name); - } - } - - this.dispatchEventToListeners(WebInspector.Setting.Event.Changed, this._value, {name: this._name}); - } -} - -WebInspector.Setting.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/Sidebar.css b/Source/WebInspectorUI/UserInterface/Sidebar.css deleted file mode 100644 index 3a1f7526a..000000000 --- a/Source/WebInspectorUI/UserInterface/Sidebar.css +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.sidebar { - position: relative; - - background-color: rgb(227, 231, 235); -} - -.sidebar.collapsed { - width: 0 !important; - border: none !important; -} - -body.window-inactive .sidebar { - background-color: rgb(231, 231, 231); -} - -.sidebar > .panel { - position: absolute; - top: 0; - left: 0; - right: 0; - bottom: 0; - - display: none; - - overflow: hidden; - - z-index: 0; /* Workaround so that scroll bars appear above position:sticky section headers. */ -} - -.sidebar > .panel.selected { - display: block; -} - -.sidebar > .resizer { - position: absolute; - top: 0; - bottom: 0; - width: 5px; - - z-index: 100; - - cursor: col-resize; -} - -.sidebar.right > .resizer { - left: -3px; -} - -.sidebar.left > .resizer { - right: -3px; -} - -.sidebar.collapsed.right > .resizer { - left: -5px; -} - -.sidebar.collapsed.left > .resizer { - right: -5px; -} - -.sidebar.left { - border-right: 1px solid rgb(153, 153, 153); -} - -.sidebar.right { - background-color: rgb(231, 231, 231); - border-left: 1px solid rgb(153, 153, 153); -} diff --git a/Source/WebInspectorUI/UserInterface/Sidebar.js b/Source/WebInspectorUI/UserInterface/Sidebar.js deleted file mode 100644 index 9b0872c2f..000000000 --- a/Source/WebInspectorUI/UserInterface/Sidebar.js +++ /dev/null @@ -1,319 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.Sidebar = function(element, side, sidebarPanels, role, label) { - WebInspector.Object.call(this); - - console.assert(!side || side === WebInspector.Sidebar.Sides.Left || side === WebInspector.Sidebar.Sides.Right); - this._side = side || WebInspector.Sidebar.Sides.Left; - - this._element = element || document.createElement("div"); - this._element.classList.add(WebInspector.Sidebar.StyleClassName); - this._element.classList.add(WebInspector.Sidebar.CollapsedStyleClassName); - this._element.classList.add(this._side); - - this._element.setAttribute("role", role || "group"); - if (label) - this._element.setAttribute("aria-label", label); - - this._resizeElement = document.createElement("div"); - this._resizeElement.classList.add(WebInspector.Sidebar.ResizeElementStyleClassName); - this._resizeElement.addEventListener("mousedown", this._resizerMouseDown.bind(this), false); - this._resizeElement.addEventListener("dblclick", this._resizerDoubleClicked.bind(this), false); - this._element.insertBefore(this._resizeElement, this._element.firstChild); - - this._sidebarPanels = []; - - if (sidebarPanels) { - for (var i = 0; i < sidebarPanels.length; ++i) - this.addSidebarPanel(sidebarPanels[i]); - } -}; - -WebInspector.Object.addConstructorFunctions(WebInspector.Sidebar); - -WebInspector.Sidebar.StyleClassName = "sidebar"; -WebInspector.Sidebar.CollapsedStyleClassName = "collapsed"; -WebInspector.Sidebar.ResizeElementStyleClassName = "resizer"; -WebInspector.Sidebar.AbsoluteMinimumWidth = 200; - -WebInspector.Sidebar.Sides = {}; -WebInspector.Sidebar.Sides.Right = "right"; -WebInspector.Sidebar.Sides.Left = "left"; - -WebInspector.Sidebar.Event = { - SidebarPanelSelected: "sidebar-sidebar-panel-selected", - CollapsedStateDidChange: "sidebar-sidebar-collapsed-state-did-change", - WidthDidChange: "sidebar-width-did-change", -}; - -WebInspector.Sidebar.prototype = { - constructor: WebInspector.Sidebar, - - // Public - - addSidebarPanel: function(sidebarPanel) - { - console.assert(sidebarPanel instanceof WebInspector.SidebarPanel); - if (!(sidebarPanel instanceof WebInspector.SidebarPanel)) - return; - - console.assert(!sidebarPanel.parentSidebar); - if (sidebarPanel.parentSidebar) - return; - - sidebarPanel._parentSidebar = this; - - this._sidebarPanels.push(sidebarPanel); - this._element.appendChild(sidebarPanel.element); - - sidebarPanel.added(); - - return sidebarPanel; - }, - - removeSidebarPanel: function(sidebarPanelOrIdentifierOrIndex, index) - { - var sidebarPanel = this.findSidebarPanel(sidebarPanelOrIdentifierOrIndex); - if (!sidebarPanel) - return; - - sidebarPanel.willRemove(); - - sidebarPanel._parentSidebar = null; - - if (this._selectedSidebarPanel === sidebarPanel) { - var index = this._sidebarPanels.indexOf(sidebarPanel); - this.selectedSidebarPanel = this._sidebarPanels[index - 1] || this._sidebarPanels[index + 1]; - } - - this._sidebarPanels.remove(sidebarPanel); - this._element.removeChild(sidebarPanel.element); - - sidebarPanel.removed(); - - return sidebarPanel; - }, - - get selectedSidebarPanel() - { - return this._selectedSidebarPanel || null; - }, - - set selectedSidebarPanel(sidebarPanelOrIdentifierOrIndex) - { - var sidebarPanel = this.findSidebarPanel(sidebarPanelOrIdentifierOrIndex); - if (this._selectedSidebarPanel === sidebarPanel) - return; - - if (this._selectedSidebarPanel) { - var wasVisible = this._selectedSidebarPanel.visible; - - this._selectedSidebarPanel.selected = false; - - if (wasVisible) { - this._selectedSidebarPanel.hidden(); - this._selectedSidebarPanel.visibilityDidChange(); - } - } - - this._selectedSidebarPanel = sidebarPanel || null; - - if (this._selectedSidebarPanel) { - this._selectedSidebarPanel.selected = true; - - if (this._selectedSidebarPanel.visible) { - this._selectedSidebarPanel.shown(); - this._selectedSidebarPanel.visibilityDidChange(); - } - } - - this.dispatchEventToListeners(WebInspector.Sidebar.Event.SidebarPanelSelected); - }, - - get minimumWidth() - { - return WebInspector.Sidebar.AbsoluteMinimumWidth; - }, - - get maximumWidth() - { - // FIXME: This is kind of arbitrary and ideally would be a more complex calculation based on the - // available space for the sibling elements. - return Math.round(window.innerWidth / 3); - }, - - get width() - { - return this._element.offsetWidth; - }, - - set width(newWidth) - { - if (newWidth === this.width) - return; - - newWidth = Math.max(this.minimumWidth, Math.min(newWidth, this.maximumWidth)); - - this._element.style.width = newWidth + "px"; - - if (!this.collapsed && this._selectedSidebarPanel) - this._selectedSidebarPanel.widthDidChange(); - - this.dispatchEventToListeners(WebInspector.Sidebar.Event.WidthDidChange); - }, - - get collapsed() - { - return this._element.classList.contains(WebInspector.Sidebar.CollapsedStyleClassName); - }, - - set collapsed(flag) - { - if (flag === this.collapsed) - return; - - if (flag) - this._element.classList.add(WebInspector.Sidebar.CollapsedStyleClassName); - else - this._element.classList.remove(WebInspector.Sidebar.CollapsedStyleClassName); - - if (this._selectedSidebarPanel) { - if (this._selectedSidebarPanel.visible) - this._selectedSidebarPanel.shown(); - else - this._selectedSidebarPanel.hidden(); - - this._selectedSidebarPanel.visibilityDidChange(); - - this._selectedSidebarPanel.widthDidChange(); - } - - this.dispatchEventToListeners(WebInspector.Sidebar.Event.CollapsedStateDidChange); - this.dispatchEventToListeners(WebInspector.Sidebar.Event.WidthDidChange); - }, - - get sidebarPanels() - { - return this._sidebarPanels; - }, - - get element() - { - return this._element; - }, - - get side() - { - return this._side; - }, - - findSidebarPanel: function(sidebarPanelOrIdentifierOrIndex) - { - var sidebarPanel = null; - - if (sidebarPanelOrIdentifierOrIndex instanceof WebInspector.SidebarPanel) { - if (this._sidebarPanels.contains(sidebarPanelOrIdentifierOrIndex)) - sidebarPanel = sidebarPanelOrIdentifierOrIndex; - } else if (typeof sidebarPanelOrIdentifierOrIndex === "number") { - sidebarPanel = this._sidebarPanels[sidebarPanelOrIdentifierOrIndex]; - } else if (typeof sidebarPanelOrIdentifierOrIndex === "string") { - for (var i = 0; i < this._sidebarPanels.length; ++i) { - if (this._sidebarPanels[i].identifier === sidebarPanelOrIdentifierOrIndex) { - sidebarPanel = this._sidebarPanels[i]; - break; - } - } - } - - return sidebarPanel; - }, - - // Private - - _navigationItemSelected: function(event) - { - this.selectedSidebarPanel = event.target.selectedNavigationItem ? event.target.selectedNavigationItem.identifier : null; - }, - - _resizerDoubleClicked: function(event) - { - this.collapsed = !this.collapsed; - - event.preventDefault(); - event.stopPropagation(); - }, - - _resizerMouseDown: function(event) - { - if (event.button !== 0 || event.ctrlKey) - return; - - document.body.style.cursor = "col-resize"; - - this._resizerMouseMovedEventListener = this._resizerMouseMoved.bind(this); - this._resizerMouseUpEventListener = this._resizerMouseUp.bind(this); - - // Register these listeners on the document so we can track the mouse if it leaves the resizer. - document.addEventListener("mousemove", this._resizerMouseMovedEventListener, false); - document.addEventListener("mouseup", this._resizerMouseUpEventListener, false); - - event.preventDefault(); - event.stopPropagation(); - }, - - _resizerMouseMoved: function(event) - { - if (this._side === WebInspector.Sidebar.Sides.Left) - var newWidth = event.pageX - this._element.totalOffsetLeft; - else - var newWidth = this._element.totalOffsetLeft + this._element.offsetWidth - event.pageX; - - this.width = newWidth; - this.collapsed = (newWidth < (this.minimumWidth / 2)); - - event.preventDefault(); - event.stopPropagation(); - }, - - _resizerMouseUp: function(event) - { - if (event.button !== 0 || event.ctrlKey) - return; - - document.body.style.removeProperty("cursor"); - - document.removeEventListener("mousemove", this._resizerMouseMovedEventListener, false); - document.removeEventListener("mouseup", this._resizerMouseUpEventListener, false); - - delete this._resizerMouseMovedEventListener; - delete this._resizerMouseUpEventListener; - - event.preventDefault(); - event.stopPropagation(); - } -}; - -WebInspector.Sidebar.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/SidebarPanel.js b/Source/WebInspectorUI/UserInterface/SidebarPanel.js deleted file mode 100644 index 3e5d37ccd..000000000 --- a/Source/WebInspectorUI/UserInterface/SidebarPanel.js +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.SidebarPanel = function(identifier, displayName, showToolTip, hideToolTip, image, element, role, label) { - WebInspector.Object.call(this); - - this._identifier = identifier; - - this._toolbarItem = new WebInspector.ActivateButtonToolbarItem(identifier, showToolTip, hideToolTip, displayName, image, null, "tab"); - this._toolbarItem.addEventListener(WebInspector.ButtonNavigationItem.Event.Clicked, this.toggle, this); - this._toolbarItem.enabled = false; - - this._element = element || document.createElement("div"); - this._element.classList.add(WebInspector.SidebarPanel.StyleClassName); - this._element.classList.add(identifier); - - this._element.setAttribute("role", role || "group"); - this._element.setAttribute("aria-label", label || displayName); - -}; - -WebInspector.SidebarPanel.StyleClassName = "panel"; -WebInspector.SidebarPanel.SelectedStyleClassName = "selected"; - -WebInspector.SidebarPanel.prototype = { - constructor: WebInspector.SidebarPanel, - - // Public - - get identifier() - { - return this._identifier; - }, - - get toolbarItem() - { - return this._toolbarItem; - }, - - get element() - { - return this._element; - }, - - get visible() - { - return this.selected && this._parentSidebar && !this._parentSidebar.collapsed; - }, - - get selected() - { - return this._element.classList.contains(WebInspector.SidebarPanel.SelectedStyleClassName); - }, - - set selected(flag) - { - if (flag) - this._element.classList.add(WebInspector.SidebarPanel.SelectedStyleClassName); - else - this._element.classList.remove(WebInspector.SidebarPanel.SelectedStyleClassName); - }, - - get parentSidebar() - { - return this._parentSidebar; - }, - - show: function() - { - if (!this._parentSidebar) - return; - - this._parentSidebar.collapsed = false; - this._parentSidebar.selectedSidebarPanel = this; - }, - - hide: function() - { - if (!this._parentSidebar) - return; - - this._parentSidebar.collapsed = true; - this._parentSidebar.selectedSidebarPanel = null; - }, - - toggle: function() - { - if (this.visible) - this.hide(); - else - this.show(); - }, - - added: function() - { - console.assert(this._parentSidebar); - this._toolbarItem.enabled = true; - this._toolbarItem.activated = this.visible; - }, - - removed: function() - { - console.assert(!this._parentSidebar); - this._toolbarItem.enabled = false; - this._toolbarItem.activated = false; - }, - - willRemove: function() - { - // Implemented by subclasses. - }, - - shown: function() - { - // Implemented by subclasses. - }, - - hidden: function() - { - // Implemented by subclasses. - }, - - widthDidChange: function() - { - // Implemented by subclasses. - }, - - visibilityDidChange: function() - { - this._toolbarItem.activated = this.visible; - } -}; - -WebInspector.SidebarPanel.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/Slider.css b/Source/WebInspectorUI/UserInterface/Slider.css deleted file mode 100644 index 38407345d..000000000 --- a/Source/WebInspectorUI/UserInterface/Slider.css +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.slider { - position: relative; - height: 11px; - outline: 1px solid rgb(148, 148, 148); - border: 1px solid white; -} - -.slider > img { - position: absolute; - left: -5px; - top: -5px; - width: 14px; - height: 17px; - content: -webkit-image-set(url(Images/SliderThumb.png) 1x, url(Images/SliderThumb@2x.png) 2x); -} - -.slider > img.dragging { - content: -webkit-image-set(url(Images/SliderThumbPressed.png) 1x, url(Images/SliderThumbPressed@2x.png) 2x); -} diff --git a/Source/WebInspectorUI/UserInterface/Slider.js b/Source/WebInspectorUI/UserInterface/Slider.js deleted file mode 100644 index a4a206e0b..000000000 --- a/Source/WebInspectorUI/UserInterface/Slider.js +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.Slider = function() -{ - this._element = document.createElement("div"); - this._element.className = "slider"; - - this._knob = this._element.appendChild(document.createElement("img")); - - this._value = 0; - this._knobX = 0; - this.__maxX = 0; - - this._element.addEventListener("mousedown", this); -}; - -WebInspector.Slider.KnobWidth = 13; - -WebInspector.Slider.prototype = { - contructor: WebInspector.Slider, - __proto__: WebInspector.Object.prototype, - - // Public - - get element() - { - return this._element; - }, - - get value() - { - return this._value; - }, - - set value(value) - { - value = Math.max(Math.min(value, 1), 0); - - if (value === this._value) - return; - - this._value = value; - - this._knobX = Math.round(value * this._maxX); - this._knob.style.webkitTransform = "translate3d(" + this._knobX + "px, 0, 0)"; - - if (this.delegate && typeof this.delegate.sliderValueDidChange === "function") - this.delegate.sliderValueDidChange(this, value); - }, - - // Protected - - handleEvent: function(event) - { - switch (event.type) { - case "mousedown": - this._handleMousedown(event); - break; - case "mousemove": - this._handleMousemove(event); - break; - case "mouseup": - this._handleMouseup(event); - break; - } - }, - - // Private - - _handleMousedown: function(event) - { - if (event.target !== this._knob) - this.value = (this._localPointForEvent(event).x - 3) / this._maxX; - - this._startKnobX = this._knobX; - this._startMouseX = this._localPointForEvent(event).x; - - this._element.classList.add("dragging"); - - window.addEventListener("mousemove", this, true); - window.addEventListener("mouseup", this, true); - }, - - _handleMousemove: function(event) - { - var dx = this._localPointForEvent(event).x - this._startMouseX; - var x = Math.max(Math.min(this._startKnobX + dx, this._maxX), 0); - - this.value = x / this._maxX; - }, - - _handleMouseup: function(event) - { - this._element.classList.remove("dragging"); - - window.removeEventListener("mousemove", this, true); - window.removeEventListener("mouseup", this, true); - }, - - _localPointForEvent: function(event) - { - // We convert all event coordinates from page coordinates to local coordinates such that the slider - // may be transformed using CSS Transforms and interaction works as expected. - return window.webkitConvertPointFromPageToNode(this._element, new WebKitPoint(event.pageX, event.pageY)); - }, - - get _maxX() - { - if (this.__maxX == 0 && document.body.contains(this._element)) - this.__maxX = this._element.offsetWidth - Math.ceil(WebInspector.Slider.KnobWidth / 2); - - return this.__maxX; - } -}; diff --git a/Source/WebInspectorUI/UserInterface/SourceCode.js b/Source/WebInspectorUI/UserInterface/SourceCode.js deleted file mode 100644 index fe267d29a..000000000 --- a/Source/WebInspectorUI/UserInterface/SourceCode.js +++ /dev/null @@ -1,262 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.SourceCode = function() -{ - WebInspector.Object.call(this); - - this._pendingContentRequestCallbacks = []; - - this._originalRevision = new WebInspector.SourceCodeRevision(this, null, false); - this._currentRevision = this._originalRevision; - - this._sourceMaps = null; - this._formatterSourceMap = null; -}; - -WebInspector.SourceCode.Event = { - ContentDidChange: "source-code-content-did-change", - SourceMapAdded: "source-code-source-map-added", - FormatterDidChange: "source-code-formatter-did-change" -}; - -WebInspector.SourceCode.prototype = { - constructor: WebInspector.SourceCode, - - // Public - - get displayName() - { - // Implemented by subclasses. - console.error("Needs to be implemented by a subclass."); - return ""; - }, - - get originalRevision() - { - return this._originalRevision; - }, - - get currentRevision() - { - return this._currentRevision; - }, - - set currentRevision(revision) - { - console.assert(revision instanceof WebInspector.SourceCodeRevision); - if (!(revision instanceof WebInspector.SourceCodeRevision)) - return; - - console.assert(revision.sourceCode === this); - if (revision.sourceCode !== this) - return; - - this._currentRevision = revision; - - this.dispatchEventToListeners(WebInspector.SourceCode.Event.ContentDidChange); - }, - - get content() - { - return this._currentRevision.content; - }, - - get contentIsBase64Encoded() - { - return this._currentRevision.contentIsBase64Encoded; - }, - - get sourceMaps() - { - return this._sourceMaps || []; - }, - - addSourceMap: function(sourceMap) - { - console.assert(sourceMap instanceof WebInspector.SourceMap); - - if (!this._sourceMaps) - this._sourceMaps = []; - - this._sourceMaps.push(sourceMap); - - this.dispatchEventToListeners(WebInspector.SourceCode.Event.SourceMapAdded); - }, - - get formatterSourceMap() - { - return this._formatterSourceMap; - }, - - set formatterSourceMap(formatterSourceMap) - { - console.assert(this._formatterSourceMap === null || formatterSourceMap === null); - console.assert(formatterSourceMap === null || formatterSourceMap instanceof WebInspector.FormatterSourceMap); - - this._formatterSourceMap = formatterSourceMap; - - this.dispatchEventToListeners(WebInspector.SourceCode.Event.FormatterDidChange); - }, - - requestContent: function(callback) - { - console.assert(typeof callback === "function"); - if (typeof callback !== "function") - return; - - this._pendingContentRequestCallbacks.push(callback); - - if (this._contentReceived) { - // Call _servicePendingContentRequests on a timeout to force callbacks to be asynchronous. - if (!this._servicePendingContentRequestsTimeoutIdentifier) - this._servicePendingContentRequestsTimeoutIdentifier = setTimeout(this.servicePendingContentRequests.bind(this), 0); - } else if (this.canRequestContentFromBackend()) - this.requestContentFromBackendIfNeeded(); - }, - - createSourceCodeLocation: function(lineNumber, columnNumber) - { - return new WebInspector.SourceCodeLocation(this, lineNumber, columnNumber); - }, - - createSourceCodeTextRange: function(textRange) - { - return new WebInspector.SourceCodeTextRange(this, textRange); - }, - - // Protected - - revisionContentDidChange: function(revision) - { - if (this._ignoreRevisionContentDidChangeEvent) - return; - - if (revision !== this._currentRevision) - return; - - this.handleCurrentRevisionContentChange(); - - this.dispatchEventToListeners(WebInspector.SourceCode.Event.ContentDidChange); - }, - - handleCurrentRevisionContentChange: function() - { - // Implemented by subclasses if needed. - }, - - get revisionForRequestedContent() - { - // Implemented by subclasses if needed. - return this._originalRevision; - }, - - markContentAsStale: function() - { - this._contentReceived = false; - }, - - canRequestContentFromBackend: function() - { - // Implemented by subclasses. - console.error("Needs to be implemented by a subclass."); - return false; - }, - - requestContentFromBackend: function(callback) - { - // Implemented by subclasses. - console.error("Needs to be implemented by a subclass."); - }, - - requestContentFromBackendIfNeeded: function() - { - console.assert(this.canRequestContentFromBackend()); - if (!this.canRequestContentFromBackend()) - return; - - if (!this._pendingContentRequestCallbacks.length) - return; - - if (this._contentRequestResponsePending) - return; - - this._contentRequestResponsePending = true; - - if (this.requestContentFromBackend(this._processContent.bind(this))) - return; - - // Since requestContentFromBackend returned false, just call _processContent, - // which will cause the pending callbacks to get null content. - this._processContent(); - }, - - servicePendingContentRequests: function(force) - { - if (this._servicePendingContentRequestsTimeoutIdentifier) { - clearTimeout(this._servicePendingContentRequestsTimeoutIdentifier); - delete this._servicePendingContentRequestsTimeoutIdentifier; - } - - // Force the content requests to be sent. To do this correctly we also force - // _contentReceived to be true so future calls to requestContent go through. - if (force) - this._contentReceived = true; - - console.assert(this._contentReceived); - if (!this._contentReceived) - return; - - // Move the callbacks into a local and clear _pendingContentRequestCallbacks so - // callbacks that might call requestContent again will not modify the array. - var callbacks = this._pendingContentRequestCallbacks; - this._pendingContentRequestCallbacks = []; - - for (var i = 0; i < callbacks.length; ++i) - callbacks[i](this, this.content, this.contentIsBase64Encoded); - }, - - // Private - - _processContent: function(error, content, base64Encoded) - { - if (error) - console.error(error); - - this._contentRequestResponsePending = false; - this._contentReceived = true; - - var revision = this.revisionForRequestedContent; - - this._ignoreRevisionContentDidChangeEvent = true; - revision.content = content || null; - revision.contentIsBase64Encoded = base64Encoded || false; - delete this._ignoreRevisionContentDidChangeEvent; - - this.servicePendingContentRequests(); - } -}; - -WebInspector.SourceCode.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/SourceCodeLocation.js b/Source/WebInspectorUI/UserInterface/SourceCodeLocation.js deleted file mode 100644 index 583e132ce..000000000 --- a/Source/WebInspectorUI/UserInterface/SourceCodeLocation.js +++ /dev/null @@ -1,455 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.SourceCodeLocation = function(sourceCode, lineNumber, columnNumber) -{ - WebInspector.Object.call(this); - - console.assert(sourceCode === null || sourceCode instanceof WebInspector.SourceCode); - console.assert(!(sourceCode instanceof WebInspector.SourceMapResource)); - console.assert(typeof lineNumber === "number" && !isNaN(lineNumber) && lineNumber >= 0); - console.assert(typeof columnNumber === "number" && !isNaN(columnNumber) && columnNumber >= 0); - - this._sourceCode = sourceCode || null; - this._lineNumber = lineNumber; - this._columnNumber = columnNumber; - this._resolveFormattedLocation(); - - if (this._sourceCode) { - this._sourceCode.addEventListener(WebInspector.SourceCode.Event.SourceMapAdded, this._sourceCodeSourceMapAdded, this); - this._sourceCode.addEventListener(WebInspector.SourceCode.Event.FormatterDidChange, this._sourceCodeFormatterDidChange, this); - } - - this._resetMappedLocation(); -}; - -WebInspector.SourceCodeLocation.DisplayLocationClassName = "display-location"; - -WebInspector.SourceCodeLocation.LargeColumnNumber = 80; - -WebInspector.SourceCodeLocation.NameStyle = { - None: "none", // File name not included. - Short: "short", // Only the file name. - Full: "full" // Full URL is used. -}; - -WebInspector.SourceCodeLocation.ColumnStyle = { - Hidden: "hidden", // column numbers are not included. - OnlyIfLarge: "only-if-large", // column numbers greater than 80 are shown. - Shown: "shown" // non-zero column numbers are shown. -}; - -WebInspector.SourceCodeLocation.Event = { - LocationChanged: "source-code-location-location-changed", - DisplayLocationChanged: "source-code-location-display-location-changed" -}; - -WebInspector.SourceCodeLocation.prototype = { - constructor: WebInspector.SourceCodeLocation, - - // Public - - isEqual: function(other) - { - if (!other) - return false; - return this._sourceCode === other._sourceCode && this._lineNumber === other._lineNumber && this._columnNumber === other._columnNumber; - }, - - get sourceCode() - { - return this._sourceCode; - }, - - set sourceCode(sourceCode) - { - console.assert((this._sourceCode === null && sourceCode instanceof WebInspector.SourceCode) || (this._sourceCode instanceof WebInspector.SourceCode && sourceCode === null)); - - if (sourceCode === this._sourceCode) - return; - - this._makeChangeAndDispatchChangeEventIfNeeded(function() { - if (this._sourceCode) { - this._sourceCode.removeEventListener(WebInspector.SourceCode.Event.SourceMapAdded, this._sourceCodeSourceMapAdded, this); - this._sourceCode.removeEventListener(WebInspector.SourceCode.Event.FormatterDidChange, this._sourceCodeFormatterDidChange, this); - } - - this._sourceCode = sourceCode; - - if (this._sourceCode) { - this._sourceCode.addEventListener(WebInspector.SourceCode.Event.SourceMapAdded, this._sourceCodeSourceMapAdded, this); - this._sourceCode.addEventListener(WebInspector.SourceCode.Event.FormatterDidChange, this._sourceCodeFormatterDidChange, this); - } - }); - }, - - // Raw line and column in the original source code. - - get lineNumber() - { - return this._lineNumber; - }, - - get columnNumber() - { - return this._columnNumber; - }, - - position: function() - { - return new WebInspector.SourceCodePosition(this.lineNumber, this.columnNumber); - }, - - // Formatted line and column if the original source code is pretty printed. - // This is the same as the raw location if there is no formatter. - - get formattedLineNumber() - { - return this._formattedLineNumber; - }, - - get formattedColumnNumber() - { - return this._formattedColumnNumber; - }, - - formattedPosition: function() - { - return new WebInspector.SourceCodePosition(this.formattedLineNumber, this.formattedColumnNumber); - }, - - // Display line and column: - // - Mapped line and column if the original source code has a source map. - // - Otherwise this is the formatted / raw line and column. - - get displaySourceCode() - { - this._resolveMappedLocation(); - return this._mappedResource || this._sourceCode; - }, - - get displayLineNumber() - { - this._resolveMappedLocation(); - return isNaN(this._mappedLineNumber) ? this._formattedLineNumber : this._mappedLineNumber; - }, - - get displayColumnNumber() - { - this._resolveMappedLocation(); - return isNaN(this._mappedColumnNumber) ? this._formattedColumnNumber : this._mappedColumnNumber; - }, - - displayPosition: function() - { - return new WebInspector.SourceCodePosition(this.displayLineNumber, this.displayColumnNumber); - }, - - // User presentable location strings: "file:lineNumber:columnNumber". - - originalLocationString: function(columnStyle, nameStyle, prefix) - { - return this._locationString(this.sourceCode, this.lineNumber, this.columnNumber, columnStyle, nameStyle, prefix); - }, - - formattedLocationString: function(columnStyle, nameStyle, prefix) - { - return this._locationString(this.sourceCode, this.formattedLineNumber, this.formattedColumn, columnStyle, nameStyle, prefix); - }, - - displayLocationString: function(columnStyle, nameStyle, prefix) - { - return this._locationString(this.displaySourceCode, this.displayLineNumber, this.displayColumnNumber, columnStyle, nameStyle, prefix); - }, - - tooltipString: function() - { - if (!this.hasDifferentDisplayLocation()) - return this.originalLocationString(WebInspector.SourceCodeLocation.ColumnStyle.Shown, WebInspector.SourceCodeLocation.NameStyle.Full); - - var tooltip = WebInspector.UIString("Located at %s").format(this.displayLocationString(WebInspector.SourceCodeLocation.ColumnStyle.Shown, WebInspector.SourceCodeLocation.NameStyle.Full)); - tooltip += "\n" + WebInspector.UIString("Originally %s").format(this.originalLocationString(WebInspector.SourceCodeLocation.ColumnStyle.Shown, WebInspector.SourceCodeLocation.NameStyle.Full)); - return tooltip; - }, - - hasMappedLocation: function() - { - this._resolveMappedLocation(); - return this._mappedResource !== null; - }, - - hasFormattedLocation: function() - { - return this._formattedLineNumber !== this._lineNumber || this._formattedColumnNumber !== this._columnNumber; - }, - - hasDifferentDisplayLocation: function() - { - return this.hasMappedLocation() || this.hasFormattedLocation(); - }, - - update: function(sourceCode, lineNumber, columnNumber) - { - console.assert(sourceCode === this._sourceCode || (this._mappedResource && sourceCode === this._mappedResource)); - console.assert(typeof lineNumber === "number" && !isNaN(lineNumber) && lineNumber >= 0); - console.assert(typeof columnNumber === "number" && !isNaN(columnNumber) && columnNumber >= 0); - - if (sourceCode === this._sourceCode && lineNumber === this._lineNumber && columnNumber === this._columnNumber) - return; - else if (this._mappedResource && sourceCode === this._mappedResource && lineNumber === this._mappedLineNumber && columnNumber === this._mappedColumnNumber) - return; - - var newSourceCodeLocation = sourceCode.createSourceCodeLocation(lineNumber, columnNumber); - console.assert(newSourceCodeLocation.sourceCode === this._sourceCode); - - this._makeChangeAndDispatchChangeEventIfNeeded(function() { - this._lineNumber = newSourceCodeLocation._lineNumber; - this._columnNumber = newSourceCodeLocation._columnNumber; - if (newSourceCodeLocation._mappedLocationIsResolved) { - this._mappedLocationIsResolved = true; - this._mappedResource = newSourceCodeLocation._mappedResource; - this._mappedLineNumber = newSourceCodeLocation._mappedLineNumber; - this._mappedColumnNumber = newSourceCodeLocation._mappedColumnNumber; - } - }); - }, - - populateLiveDisplayLocationTooltip: function(element, prefix) - { - prefix = prefix || ""; - - element.title = prefix + this.tooltipString(); - - this.addEventListener(WebInspector.SourceCodeLocation.Event.DisplayLocationChanged, function(event) { - element.title = prefix + this.tooltipString(); - }, this); - }, - - populateLiveDisplayLocationString: function(element, propertyName, columnStyle, nameStyle, prefix) - { - var currentDisplay = undefined; - - function updateDisplayString(showAlternativeLocation, forceUpdate) - { - if (!forceUpdate && currentDisplay === showAlternativeLocation) - return; - - currentDisplay = showAlternativeLocation; - - if (!showAlternativeLocation) { - element[propertyName] = this.displayLocationString(columnStyle, nameStyle, prefix); - element.classList.toggle(WebInspector.SourceCodeLocation.DisplayLocationClassName, this.hasDifferentDisplayLocation()); - } else if (this.hasDifferentDisplayLocation()) { - element[propertyName] = this.originalLocationString(columnStyle, nameStyle, prefix); - element.classList.remove(WebInspector.SourceCodeLocation.DisplayLocationClassName); - } - } - - function mouseOverOrMove(event) - { - updateDisplayString.call(this, event.metaKey && !event.altKey && !event.shiftKey); - } - - updateDisplayString.call(this, false); - - this.addEventListener(WebInspector.SourceCodeLocation.Event.DisplayLocationChanged, function(event) { - updateDisplayString.call(this, currentDisplay, true); - }, this); - - var boundMouseOverOrMove = mouseOverOrMove.bind(this); - element.addEventListener("mouseover", boundMouseOverOrMove); - element.addEventListener("mousemove", boundMouseOverOrMove); - - element.addEventListener("mouseout", function(event) { - updateDisplayString.call(this, false); - }.bind(this)); - }, - - // Private - - _locationString: function(sourceCode, lineNumber, columnNumber, columnStyle, nameStyle, prefix) - { - console.assert(sourceCode); - if (!sourceCode) - return ""; - - columnStyle = columnStyle || WebInspector.SourceCodeLocation.ColumnStyle.OnlyIfLarge; - nameStyle = nameStyle || WebInspector.SourceCodeLocation.NameStyle.Short; - prefix = prefix || ""; - - var lineString = lineNumber + 1; // The user visible line number is 1-based. - if (columnStyle === WebInspector.SourceCodeLocation.ColumnStyle.Shown && columnNumber > 0) - lineString += ":" + (columnNumber + 1); // The user visible column number is 1-based. - else if (columnStyle === WebInspector.SourceCodeLocation.ColumnStyle.OnlyIfLarge && columnNumber > WebInspector.SourceCodeLocation.LargeColumnNumber) - lineString += ":" + (columnNumber + 1); // The user visible column number is 1-based. - - switch (nameStyle) { - case WebInspector.SourceCodeLocation.NameStyle.None: - return prefix + lineString; - - case WebInspector.SourceCodeLocation.NameStyle.Short: - case WebInspector.SourceCodeLocation.NameStyle.Full: - var lineSuffix = sourceCode.url ? ":" + lineString : WebInspector.UIString(" (line %s)").format(lineString); - return prefix + (nameStyle === WebInspector.SourceCodeLocation.NameStyle.Full && sourceCode.url ? sourceCode.url : sourceCode.displayName) + lineSuffix; - - default: - console.error("Unknown nameStyle: " + nameStyle); - return prefix + lineString; - } - }, - - _resetMappedLocation: function() - { - this._mappedLocationIsResolved = false; - this._mappedResource = null; - this._mappedLineNumber = NaN; - this._mappedColumnNumber = NaN; - }, - - _setMappedLocation: function(mappedResource, mappedLineNumber, mappedColumnNumber) - { - // Called by SourceMapResource when it creates a SourceCodeLocation and already knows the resolved location. - this._mappedLocationIsResolved = true; - this._mappedResource = mappedResource; - this._mappedLineNumber = mappedLineNumber; - this._mappedColumnNumber = mappedColumnNumber; - }, - - _resolveMappedLocation: function() - { - if (this._mappedLocationIsResolved) - return; - - console.assert(this._mappedResource === null); - console.assert(isNaN(this._mappedLineNumber)); - console.assert(isNaN(this._mappedColumnNumber)); - - this._mappedLocationIsResolved = true; - - if (!this._sourceCode) - return; - - var sourceMaps = this._sourceCode.sourceMaps; - if (!sourceMaps.length) - return; - - for (var i = 0; i < sourceMaps.length; ++i) { - var sourceMap = sourceMaps[i]; - var entry = sourceMap.findEntry(this._lineNumber, this._columnNumber); - if (!entry || entry.length === 2) - continue; - console.assert(entry.length === 5); - var url = entry[2]; - var sourceMapResource = sourceMap.resourceForURL(url); - if (!sourceMapResource) - return; - this._mappedResource = sourceMapResource; - this._mappedLineNumber = entry[3]; - this._mappedColumnNumber = entry[4]; - return; - } - }, - - _resolveFormattedLocation: function() - { - if (this._sourceCode && this._sourceCode.formatterSourceMap) { - var formattedLocation = this._sourceCode.formatterSourceMap.originalToFormatted(this._lineNumber, this._columnNumber); - this._formattedLineNumber = formattedLocation.lineNumber; - this._formattedColumnNumber = formattedLocation.columnNumber; - } else { - this._formattedLineNumber = this._lineNumber; - this._formattedColumnNumber = this._columnNumber; - } - }, - - _makeChangeAndDispatchChangeEventIfNeeded: function(changeFunction) - { - var oldSourceCode = this._sourceCode; - var oldLineNumber = this._lineNumber; - var oldColumnNumber = this._columnNumber; - - var oldFormattedLineNumber = this._formattedLineNumber; - var oldFormattedColumnNumber = this._formattedColumnNumber; - - var oldDisplaySourceCode = this.displaySourceCode; - var oldDisplayLineNumber = this.displayLineNumber; - var oldDisplayColumnNumber = this.displayColumnNumber; - - this._resetMappedLocation(); - - if (changeFunction) - changeFunction.call(this); - - this._resolveMappedLocation(); - this._resolveFormattedLocation(); - - // If the display source code is non-null then the addresses are not NaN and can be compared. - var displayLocationChanged = false; - var newDisplaySourceCode = this.displaySourceCode; - if (oldDisplaySourceCode !== newDisplaySourceCode) - displayLocationChanged = true; - else if (newDisplaySourceCode && (oldDisplayLineNumber !== this.displayLineNumber || oldDisplayColumnNumber !== this.displayColumnNumber)) - displayLocationChanged = true; - - var anyLocationChanged = false; - if (displayLocationChanged) - anyLocationChanged = true; - else if (oldSourceCode !== this._sourceCode) - anyLocationChanged = true; - else if (this._sourceCode && (oldLineNumber !== this._lineNumber || oldColumnNumber !== this._columnNumber)) - anyLocationChanged = true; - else if (this._sourceCode && (oldFormattedLineNumber !== this._formattedLineNumber || oldFormattedColumnNumber !== this._formattedColumnNumber)) - anyLocationChanged = true; - - if (displayLocationChanged || anyLocationChanged) { - var oldData = { - oldSourceCode: oldSourceCode, - oldLineNumber: oldLineNumber, - oldColumnNumber: oldColumnNumber, - oldFormattedLineNumber: oldFormattedLineNumber, - oldFormattedColumnNumber: oldFormattedColumnNumber, - oldDisplaySourceCode: oldDisplaySourceCode, - oldDisplayLineNumber: oldDisplayLineNumber, - oldDisplayColumnNumber: oldDisplayColumnNumber - }; - if (displayLocationChanged) - this.dispatchEventToListeners(WebInspector.SourceCodeLocation.Event.DisplayLocationChanged, oldData); - if (anyLocationChanged) - this.dispatchEventToListeners(WebInspector.SourceCodeLocation.Event.LocationChanged, oldData); - } - }, - - _sourceCodeSourceMapAdded: function() - { - this._makeChangeAndDispatchChangeEventIfNeeded(null); - }, - - _sourceCodeFormatterDidChange: function() - { - this._makeChangeAndDispatchChangeEventIfNeeded(null); - } -}; - -WebInspector.SourceCodeLocation.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/SourceCodePosition.js b/Source/WebInspectorUI/UserInterface/SourceCodePosition.js deleted file mode 100644 index ac673775c..000000000 --- a/Source/WebInspectorUI/UserInterface/SourceCodePosition.js +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.SourceCodePosition = function(lineNumber, columNumber) -{ - WebInspector.Object.call(this); - - this._lineNumber = lineNumber || 0; - this._columnNumber = columNumber || 0; -} - -WebInspector.SourceCodePosition.prototype = { - constructor: WebInspector.SourceCodePosition, - - // Public - - get lineNumber() - { - return this._lineNumber; - }, - - get columnNumber() - { - return this._columnNumber; - } -}; - -WebInspector.SourceCodePosition.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/SourceCodeRevision.js b/Source/WebInspectorUI/UserInterface/SourceCodeRevision.js deleted file mode 100644 index ceb7a3b97..000000000 --- a/Source/WebInspectorUI/UserInterface/SourceCodeRevision.js +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.SourceCodeRevision = function(sourceCode, content, contentIsBase64Encoded) -{ - WebInspector.Revision.call(this); - - console.assert(sourceCode instanceof WebInspector.SourceCode); - - this._sourceCode = sourceCode; - this._content = content || ""; - this._contentIsBase64Encoded = contentIsBase64Encoded || false; -}; - -WebInspector.SourceCodeRevision.prototype = { - constructor: WebInspector.SourceCodeRevision, - - // Public - - get sourceCode() - { - return this._sourceCode; - }, - - get content() - { - return this._content; - }, - - set content(content) - { - content = content || ""; - - if (this._content === content) - return; - - this._content = content; - - this._sourceCode.revisionContentDidChange(this); - }, - - get contentIsBase64Encoded() - { - return this._contentIsBase64Encoded; - }, - - set contentIsBase64Encoded(encoded) - { - this._contentIsBase64Encoded = encoded || false; - }, - - apply: function() - { - this._sourceCode.currentRevision = this; - }, - - revert: function() - { - this._sourceCode.currentRevision = this._sourceCode.originalRevision; - }, - - copy: function() - { - return new WebInspector.SourceCodeRevision(this._sourceCode, this._content, this._contentIsBase64Encoded); - } -}; - -WebInspector.SourceCodeRevision.prototype.__proto__ = WebInspector.Revision.prototype; diff --git a/Source/WebInspectorUI/UserInterface/SourceCodeTextEditor.css b/Source/WebInspectorUI/UserInterface/SourceCodeTextEditor.css deleted file mode 100644 index 90f0a840b..000000000 --- a/Source/WebInspectorUI/UserInterface/SourceCodeTextEditor.css +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.source-code.text-editor > .CodeMirror .error { - background-color: rgb(255, 220, 208); -} - -.source-code.text-editor > .CodeMirror .warning { - background-color: rgb(253, 249, 226); -} - -.popover .debugger-popover-content { - font-family: monospace; - white-space: pre; -} - -.popover .expandable { - min-width: 300px; - min-height: 250px; -} - -.popover .debugger-popover-content .title { - font-weight: bold; - padding-left: 10px; - - text-overflow: ellipsis; - overflow: hidden; - white-space: nowrap; -} - -.popover .debugger-popover-content .body { - border-top: 1px solid rgb(194, 194, 147); - overflow: auto; - margin-top: 5px; - padding-top: 5px; -} - -.popover .debugger-popover-content.function .body { - padding-left: 10px; - padding-right: 10px; -} - -/* Custom styling for the hover menu attached to color tokens */ - -.hover-menu.color { - padding-right: 15px; -} - -.hover-menu.color > img { - width: 16px; - height: 16px; - -webkit-transform: translateX(14px); - content: -webkit-image-set(url(Images/ColorIcon.png) 1x, url(Images/ColorIcon@2x.png) 2x); -} diff --git a/Source/WebInspectorUI/UserInterface/SourceCodeTextEditor.js b/Source/WebInspectorUI/UserInterface/SourceCodeTextEditor.js deleted file mode 100644 index 7cb354bdf..000000000 --- a/Source/WebInspectorUI/UserInterface/SourceCodeTextEditor.js +++ /dev/null @@ -1,1369 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.SourceCodeTextEditor = function(sourceCode) -{ - console.assert(sourceCode instanceof WebInspector.SourceCode); - - this._sourceCode = sourceCode; - this._breakpointMap = {}; - this._issuesLineNumberMap = {}; - this._contentPopulated = false; - this._invalidLineNumbers = {0: true}; - this._ignoreContentDidChange = 0; - - WebInspector.TextEditor.call(this, null, null, this); - - // FIXME: Currently this just jumps between resources and related source map resources. It doesn't "jump to symbol" yet. - this._updateTokenTrackingControllerState(); - - this.element.classList.add(WebInspector.SourceCodeTextEditor.StyleClassName); - - if (this._supportsDebugging) { - WebInspector.Breakpoint.addEventListener(WebInspector.Breakpoint.Event.DisabledStateDidChange, this._updateBreakpointStatus, this); - WebInspector.Breakpoint.addEventListener(WebInspector.Breakpoint.Event.AutoContinueDidChange, this._updateBreakpointStatus, this); - WebInspector.Breakpoint.addEventListener(WebInspector.Breakpoint.Event.ResolvedStateDidChange, this._updateBreakpointStatus, this); - WebInspector.Breakpoint.addEventListener(WebInspector.Breakpoint.Event.LocationDidChange, this._updateBreakpointLocation, this); - - WebInspector.debuggerManager.addEventListener(WebInspector.DebuggerManager.Event.BreakpointAdded, this._breakpointAdded, this); - WebInspector.debuggerManager.addEventListener(WebInspector.DebuggerManager.Event.BreakpointRemoved, this._breakpointRemoved, this); - WebInspector.debuggerManager.addEventListener(WebInspector.DebuggerManager.Event.ActiveCallFrameDidChange, this._activeCallFrameDidChange, this); - - WebInspector.debuggerManager.addEventListener(WebInspector.DebuggerManager.Event.Paused, this._debuggerDidPause, this); - WebInspector.debuggerManager.addEventListener(WebInspector.DebuggerManager.Event.Resumed, this._debuggerDidResume, this); - if (WebInspector.debuggerManager.activeCallFrame) - this._debuggerDidPause(); - - this._activeCallFrameDidChange(); - } - - WebInspector.issueManager.addEventListener(WebInspector.IssueManager.Event.IssueWasAdded, this._issueWasAdded, this); - - if (this._sourceCode instanceof WebInspector.SourceMapResource || this._sourceCode.sourceMaps.length > 0) - WebInspector.notifications.addEventListener(WebInspector.Notification.GlobalModifierKeysDidChange, this._updateTokenTrackingControllerState, this); - else - this._sourceCode.addEventListener(WebInspector.SourceCode.Event.SourceMapAdded, this._sourceCodeSourceMapAdded, this); - - sourceCode.requestContent(this._contentAvailable.bind(this)); - - // FIXME: Cmd+L shorcut doesn't actually work. - new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.Command, "L", this.showGoToLineDialog.bind(this), this.element); - new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.Control, "G", this.showGoToLineDialog.bind(this), this.element); -}; - -WebInspector.Object.addConstructorFunctions(WebInspector.SourceCodeTextEditor); - -WebInspector.SourceCodeTextEditor.StyleClassName = "source-code"; -WebInspector.SourceCodeTextEditor.LineErrorStyleClassName = "error"; -WebInspector.SourceCodeTextEditor.LineWarningStyleClassName = "warning"; -WebInspector.SourceCodeTextEditor.PopoverDebuggerContentStyleClassName = "debugger-popover-content"; -WebInspector.SourceCodeTextEditor.HoveredExpressionHighlightStyleClassName = "hovered-expression-highlight"; -WebInspector.SourceCodeTextEditor.DurationToMouseOverTokenToMakeHoveredToken = 500; -WebInspector.SourceCodeTextEditor.DurationToMouseOutOfHoveredTokenToRelease = 1000; - -WebInspector.SourceCodeTextEditor.AutoFormatMinimumLineLength = 500; - -WebInspector.SourceCodeTextEditor.Event = { - ContentWillPopulate: "source-code-text-editor-content-will-populate", - ContentDidPopulate: "source-code-text-editor-content-did-populate" -}; - -WebInspector.SourceCodeTextEditor.prototype = { - constructor: WebInspector.SourceCodeTextEditor, - - // Public - - get sourceCode() - { - return this._sourceCode; - }, - - hidden: function() - { - WebInspector.TextEditor.prototype.hidden.call(this); - - this.tokenTrackingController.removeHighlightedRange(); - - this._dismissPopover(); - }, - - close: function() - { - if (this._supportsDebugging) { - WebInspector.Breakpoint.removeEventListener(WebInspector.Breakpoint.Event.DisabledStateDidChange, this._updateBreakpointStatus, this); - WebInspector.Breakpoint.removeEventListener(WebInspector.Breakpoint.Event.AutoContinueDidChange, this._updateBreakpointStatus, this); - WebInspector.Breakpoint.removeEventListener(WebInspector.Breakpoint.Event.ResolvedStateDidChange, this._updateBreakpointStatus, this); - WebInspector.Breakpoint.removeEventListener(WebInspector.Breakpoint.Event.LocationDidChange, this._updateBreakpointLocation, this); - - WebInspector.debuggerManager.removeEventListener(WebInspector.DebuggerManager.Event.BreakpointAdded, this._breakpointAdded, this); - WebInspector.debuggerManager.removeEventListener(WebInspector.DebuggerManager.Event.BreakpointRemoved, this._breakpointRemoved, this); - WebInspector.debuggerManager.removeEventListener(WebInspector.DebuggerManager.Event.ActiveCallFrameDidChange, this._activeCallFrameDidChange, this); - - if (this._activeCallFrameSourceCodeLocation) { - this._activeCallFrameSourceCodeLocation.removeEventListener(WebInspector.SourceCodeLocation.Event.LocationChanged, this._activeCallFrameSourceCodeLocationChanged, this); - delete this._activeCallFrameSourceCodeLocation; - } - } - - WebInspector.issueManager.removeEventListener(WebInspector.IssueManager.Event.IssueWasAdded, this._issueWasAdded, this); - - WebInspector.notifications.removeEventListener(WebInspector.Notification.GlobalModifierKeysDidChange, this._updateTokenTrackingControllerState, this); - this._sourceCode.removeEventListener(WebInspector.SourceCode.Event.SourceMapAdded, this._sourceCodeSourceMapAdded, this); - }, - - canBeFormatted: function() - { - // Currently we assume that source map resources are formatted how the author wants it. - // We could allow source map resources to be formatted, we would then need to make - // SourceCodeLocation watch listen for mappedResource's formatting changes, and keep - // a formatted location alongside the regular mapped location. - if (this._sourceCode instanceof WebInspector.SourceMapResource) - return false; - - return WebInspector.TextEditor.prototype.canBeFormatted.call(this); - }, - - customPerformSearch: function(query) - { - function searchResultCallback(error, matches) - { - // Bail if the query changed since we started. - if (this.currentSearchQuery !== query) - return; - - if (error || !matches || !matches.length) { - // Report zero matches. - this.dispatchEventToListeners(WebInspector.TextEditor.Event.NumberOfSearchResultsDidChange); - return; - } - - var queryRegex = new RegExp(query.escapeForRegExp(), "gi"); - var searchResults = []; - - for (var i = 0; i < matches.length; ++i) { - var matchLineNumber = matches[i].lineNumber; - var line = this.line(matchLineNumber); - - // Reset the last index to reuse the regex on a new line. - queryRegex.lastIndex = 0; - - // Search the line and mark the ranges. - var lineMatch = null; - while (queryRegex.lastIndex + query.length <= line.length && (lineMatch = queryRegex.exec(line))) { - var resultTextRange = new WebInspector.TextRange(matchLineNumber, lineMatch.index, matchLineNumber, queryRegex.lastIndex); - searchResults.push(resultTextRange); - } - } - - this.addSearchResults(searchResults); - - this.dispatchEventToListeners(WebInspector.TextEditor.Event.NumberOfSearchResultsDidChange); - } - - if (this._sourceCode instanceof WebInspector.SourceMapResource) - return false; - - if (this._sourceCode instanceof WebInspector.Resource) - PageAgent.searchInResource(this._sourceCode.parentFrame.id, this._sourceCode.url, query, false, false, searchResultCallback.bind(this)); - else if (this._sourceCode instanceof WebInspector.Script) - DebuggerAgent.searchInContent(this._sourceCode.id, query, false, false, searchResultCallback.bind(this)); - return true; - }, - - showGoToLineDialog: function() - { - if (!this._goToLineDialog) { - this._goToLineDialog = new WebInspector.GoToLineDialog; - this._goToLineDialog.delegate = this; - } - - this._goToLineDialog.present(this.element); - }, - - isGoToLineDialogValueValid: function(goToLineDialog, lineNumber) - { - return !isNaN(lineNumber) && lineNumber > 0 && lineNumber <= this.lineCount; - }, - - goToLineDialogValueWasValidated: function(goToLineDialog, lineNumber) - { - var position = new WebInspector.SourceCodePosition(lineNumber - 1, 0); - var range = new WebInspector.TextRange(lineNumber - 1, 0, lineNumber, 0); - this.revealPosition(position, range, false, true); - }, - - goToLineDialogWasDismissed: function() - { - this.focus(); - }, - - contentDidChange: function(replacedRanges, newRanges) - { - WebInspector.TextEditor.prototype.contentDidChange.call(this, replacedRanges, newRanges); - - if (this._ignoreContentDidChange > 0) - return; - - // Gather all lines containing new text. - var lines = new Set; - for (var range of newRanges) { - // If the range is on a single line, only add the line if the range is not empty. - if (range.startLine === range.endLine) { - if (range.endColumn > range.startColumn) - lines.add(range.startLine); - } else { - // Only add the last line if the range has characters on this line. - for (var line = range.startLine; line < range.endLine || range.endColumn > 0; ++line) - lines.add(line); - } - } - - // Consider all new lines for new color markers. - for (var line of lines) - this._updateColorMarkers(line); - }, - - // Private - - _unformattedLineInfoForEditorLineInfo: function(lineInfo) - { - if (this.formatterSourceMap) - return this.formatterSourceMap.formattedToOriginal(lineInfo.lineNumber, lineInfo.columnNumber); - return lineInfo; - }, - - _sourceCodeLocationForEditorPosition: function(position) - { - var lineInfo = {lineNumber: position.line, columnNumber: position.ch}; - var unformattedLineInfo = this._unformattedLineInfoForEditorLineInfo(lineInfo); - return this.sourceCode.createSourceCodeLocation(unformattedLineInfo.lineNumber, unformattedLineInfo.columnNumber); - }, - - _editorLineInfoForSourceCodeLocation: function(sourceCodeLocation) - { - if (this._sourceCode instanceof WebInspector.SourceMapResource) - return {lineNumber: sourceCodeLocation.displayLineNumber, columnNumber: sourceCodeLocation.displayColumnNumber}; - return {lineNumber: sourceCodeLocation.formattedLineNumber, columnNumber: sourceCodeLocation.formattedColumnNumber}; - }, - - _breakpointForEditorLineInfo: function(lineInfo) - { - if (!this._breakpointMap[lineInfo.lineNumber]) - return null; - return this._breakpointMap[lineInfo.lineNumber][lineInfo.columnNumber]; - }, - - _addBreakpointWithEditorLineInfo: function(breakpoint, lineInfo) - { - if (!this._breakpointMap[lineInfo.lineNumber]) - this._breakpointMap[lineInfo.lineNumber] = {}; - - this._breakpointMap[lineInfo.lineNumber][lineInfo.columnNumber] = breakpoint; - }, - - _removeBreakpointWithEditorLineInfo: function(breakpoint, lineInfo) - { - console.assert(breakpoint === this._breakpointMap[lineInfo.lineNumber][lineInfo.columnNumber]); - - delete this._breakpointMap[lineInfo.lineNumber][lineInfo.columnNumber]; - - if (isEmptyObject(this._breakpointMap[lineInfo.lineNumber])) - delete this._breakpointMap[lineInfo.lineNumber]; - }, - - _contentWillPopulate: function(content) - { - this.dispatchEventToListeners(WebInspector.SourceCodeTextEditor.Event.ContentWillPopulate); - - // We only do the rest of this work before the first populate. - if (this._contentPopulated) - return; - - if (this._supportsDebugging) { - this._breakpointMap = {}; - - var breakpoints = WebInspector.debuggerManager.breakpointsForSourceCode(this._sourceCode); - for (var i = 0; i < breakpoints.length; ++i) { - var breakpoint = breakpoints[i]; - console.assert(this._matchesBreakpoint(breakpoint)); - var lineInfo = this._editorLineInfoForSourceCodeLocation(breakpoint.sourceCodeLocation); - this._addBreakpointWithEditorLineInfo(breakpoint, lineInfo); - this.setBreakpointInfoForLineAndColumn(lineInfo.lineNumber, lineInfo.columnNumber, this._breakpointInfoForBreakpoint(breakpoint)); - } - } - - if (this._sourceCode instanceof WebInspector.Resource) - this.mimeType = this._sourceCode.syntheticMIMEType; - else if (this._sourceCode instanceof WebInspector.Script) - this.mimeType = "text/javascript"; - - // Automatically format the content if it looks minified and it can be formatted. - console.assert(!this.formatted); - if (this.canBeFormatted()) { - var lastNewlineIndex = 0; - while (true) { - var nextNewlineIndex = content.indexOf("\n", lastNewlineIndex); - if (nextNewlineIndex === -1) { - if (content.length - lastNewlineIndex > WebInspector.SourceCodeTextEditor.AutoFormatMinimumLineLength) - this.autoFormat = true; - break; - } - - if (nextNewlineIndex - lastNewlineIndex > WebInspector.SourceCodeTextEditor.AutoFormatMinimumLineLength) { - this.autoFormat = true; - break; - } - - lastNewlineIndex = nextNewlineIndex + 1; - } - } - }, - - _contentDidPopulate: function() - { - this._contentPopulated = true; - - this.dispatchEventToListeners(WebInspector.SourceCodeTextEditor.Event.ContentDidPopulate); - - // We add the issues each time content is populated. This is needed because lines might not exist - // if we tried added them before when the full content wasn't avaiable. (When populating with - // partial script content this can be called multiple times.) - - this._issuesLineNumberMap = {}; - - var issues = WebInspector.issueManager.issuesForSourceCode(this._sourceCode); - for (var i = 0; i < issues.length; ++i) { - var issue = issues[i]; - console.assert(this._matchesIssue(issue)); - this._addIssue(issue); - } - - this._updateTokenTrackingControllerState(); - this._updateColorMarkers(); - }, - - _populateWithContent: function(content) - { - content = content || ""; - - this._contentWillPopulate(content); - this.string = content; - this._contentDidPopulate(); - }, - - _contentAvailable: function(sourceCode, content, base64Encoded) - { - console.assert(sourceCode === this._sourceCode); - console.assert(!base64Encoded); - - // Abort if the full content populated while waiting for this async callback. - if (this._fullContentPopulated) - return; - - this._fullContentPopulated = true; - this._invalidLineNumbers = {}; - - this._populateWithContent(content); - }, - - _updateBreakpointStatus: function(event) - { - console.assert(this._supportsDebugging); - - if (!this._contentPopulated) - return; - - var breakpoint = event.target; - if (!this._matchesBreakpoint(breakpoint)) - return; - - var lineInfo = this._editorLineInfoForSourceCodeLocation(breakpoint.sourceCodeLocation); - this.setBreakpointInfoForLineAndColumn(lineInfo.lineNumber, lineInfo.columnNumber, this._breakpointInfoForBreakpoint(breakpoint)); - }, - - _updateBreakpointLocation: function(event) - { - console.assert(this._supportsDebugging); - - if (!this._contentPopulated) - return; - - var breakpoint = event.target; - if (!this._matchesBreakpoint(breakpoint)) - return; - - if (this._ignoreAllBreakpointLocationUpdates) - return; - - if (breakpoint === this._ignoreLocationUpdateBreakpoint) - return; - - var sourceCodeLocation = breakpoint.sourceCodeLocation; - - if (this._sourceCode instanceof WebInspector.SourceMapResource) { - // Update our breakpoint location if the display location changed. - if (sourceCodeLocation.displaySourceCode !== this._sourceCode) - return; - var oldLineInfo = {lineNumber: event.data.oldDisplayLineNumber, columnNumber: event.data.oldDisplayColumnNumber}; - var newLineInfo = {lineNumber: sourceCodeLocation.displayLineNumber, columnNumber: sourceCodeLocation.displayColumnNumber}; - } else { - // Update our breakpoint location if the original location changed. - if (sourceCodeLocation.sourceCode !== this._sourceCode) - return; - var oldLineInfo = {lineNumber: event.data.oldFormattedLineNumber, columnNumber: event.data.oldFormattedColumnNumber}; - var newLineInfo = {lineNumber: sourceCodeLocation.formattedLineNumber, columnNumber: sourceCodeLocation.formattedColumnNumber}; - } - - var existingBreakpoint = this._breakpointForEditorLineInfo(oldLineInfo); - if (!existingBreakpoint) - return; - - console.assert(breakpoint === existingBreakpoint); - - this.setBreakpointInfoForLineAndColumn(oldLineInfo.lineNumber, oldLineInfo.columnNumber, null); - this.setBreakpointInfoForLineAndColumn(newLineInfo.lineNumber, newLineInfo.columnNumber, this._breakpointInfoForBreakpoint(breakpoint)); - - this._removeBreakpointWithEditorLineInfo(breakpoint, oldLineInfo); - this._addBreakpointWithEditorLineInfo(breakpoint, newLineInfo); - }, - - _breakpointAdded: function(event) - { - console.assert(this._supportsDebugging); - - if (!this._contentPopulated) - return; - - var breakpoint = event.data.breakpoint; - if (!this._matchesBreakpoint(breakpoint)) - return; - - if (breakpoint === this._ignoreBreakpointAddedBreakpoint) - return; - - var lineInfo = this._editorLineInfoForSourceCodeLocation(breakpoint.sourceCodeLocation); - this._addBreakpointWithEditorLineInfo(breakpoint, lineInfo); - this.setBreakpointInfoForLineAndColumn(lineInfo.lineNumber, lineInfo.columnNumber, this._breakpointInfoForBreakpoint(breakpoint)); - }, - - _breakpointRemoved: function(event) - { - console.assert(this._supportsDebugging); - - if (!this._contentPopulated) - return; - - var breakpoint = event.data.breakpoint; - if (!this._matchesBreakpoint(breakpoint)) - return; - - if (breakpoint === this._ignoreBreakpointRemovedBreakpoint) - return; - - var lineInfo = this._editorLineInfoForSourceCodeLocation(breakpoint.sourceCodeLocation); - this._removeBreakpointWithEditorLineInfo(breakpoint, lineInfo); - this.setBreakpointInfoForLineAndColumn(lineInfo.lineNumber, lineInfo.columnNumber, null); - }, - - _activeCallFrameDidChange: function() - { - console.assert(this._supportsDebugging); - - if (this._activeCallFrameSourceCodeLocation) { - this._activeCallFrameSourceCodeLocation.removeEventListener(WebInspector.SourceCodeLocation.Event.LocationChanged, this._activeCallFrameSourceCodeLocationChanged, this); - delete this._activeCallFrameSourceCodeLocation; - } - - var activeCallFrame = WebInspector.debuggerManager.activeCallFrame; - if (!activeCallFrame || !this._matchesSourceCodeLocation(activeCallFrame.sourceCodeLocation)) { - this.executionLineNumber = NaN; - this.executionColumnNumber = NaN; - return; - } - - this._dismissPopover(); - - this._activeCallFrameSourceCodeLocation = activeCallFrame.sourceCodeLocation; - this._activeCallFrameSourceCodeLocation.addEventListener(WebInspector.SourceCodeLocation.Event.LocationChanged, this._activeCallFrameSourceCodeLocationChanged, this); - - // Don't return early if the line number didn't change. The execution state still - // could have changed (e.g. continuing in a loop with a breakpoint inside). - - var lineInfo = this._editorLineInfoForSourceCodeLocation(activeCallFrame.sourceCodeLocation); - this.executionLineNumber = lineInfo.lineNumber; - this.executionColumnNumber = lineInfo.columnNumber; - - // If we have full content or this source code isn't a Resource we can return early. - // Script source code populates from the request started in the constructor. - if (this._fullContentPopulated || !(this._sourceCode instanceof WebInspector.Resource) || this._requestingScriptContent) - return; - - // Since we are paused in the debugger we need to show some content, and since the Resource - // content hasn't populated yet we need to populate with content from the Scripts by URL. - // Document resources will attempt to populate the scripts as inline (in "; - - var content = ""; - var lineNumber = 0; - var columnNumber = 0; - - this._invalidLineNumbers = {}; - - for (var i = 0; i < scripts.length; ++i) { - // Fill the line gap with newline characters. - for (var newLinesCount = scripts[i].range.startLine - lineNumber; newLinesCount > 0; --newLinesCount) { - if (!columnNumber) - this._invalidLineNumbers[scripts[i].range.startLine - newLinesCount] = true; - columnNumber = 0; - content += "\n"; - } - - // Fill the column gap with space characters. - for (var spacesCount = scripts[i].range.startColumn - columnNumber - scriptOpenTag.length; spacesCount > 0; --spacesCount) - content += " "; - - // Add script tags and content. - content += scriptOpenTag; - content += scripts[i].content; - content += scriptCloseTag; - - lineNumber = scripts[i].range.endLine; - columnNumber = scripts[i].range.endColumn + scriptCloseTag.length; - } - - this._populateWithContent(content); - } - - this._requestingScriptContent = true; - - var boundScriptContentAvailable = scriptContentAvailable.bind(this); - for (var i = 0; i < scripts.length; ++i) - scripts[i].requestContent(boundScriptContentAvailable); - }, - - _populateWithScriptContent: function() - { - console.assert(this._sourceCode instanceof WebInspector.Resource); - console.assert(!this._fullContentPopulated); - console.assert(!this._requestingScriptContent); - - // We can assume this resource only has one script that starts at line/column 0. - var scripts = this._sourceCode.scripts; - console.assert(scripts.length === 1); - if (!scripts.length) - return; - - console.assert(scripts[0].range.startLine === 0); - console.assert(scripts[0].range.startColumn === 0); - - function scriptContentAvailable(error, content) - { - delete this._requestingScriptContent; - - // Abort if the full content populated while waiting for this async callback. - if (this._fullContentPopulated) - return; - - // This is the full content. - this._fullContentPopulated = true; - - this._populateWithContent(content); - } - - this._requestingScriptContent = true; - - scripts[0].requestContent(scriptContentAvailable.bind(this)); - }, - - _matchesSourceCodeLocation: function(sourceCodeLocation) - { - if (this._sourceCode instanceof WebInspector.SourceMapResource) - return sourceCodeLocation.displaySourceCode === this._sourceCode; - if (this._sourceCode instanceof WebInspector.Resource) - return sourceCodeLocation.sourceCode.url === this._sourceCode.url; - if (this._sourceCode instanceof WebInspector.Script) - return sourceCodeLocation.sourceCode === this._sourceCode; - return false; - }, - - _matchesBreakpoint: function(breakpoint) - { - console.assert(this._supportsDebugging); - if (this._sourceCode instanceof WebInspector.SourceMapResource) - return breakpoint.sourceCodeLocation.displaySourceCode === this._sourceCode; - if (this._sourceCode instanceof WebInspector.Resource) - return breakpoint.url === this._sourceCode.url; - if (this._sourceCode instanceof WebInspector.Script) - return breakpoint.url === this._sourceCode.url || breakpoint.scriptIdentifier === this._sourceCode.id; - return false; - }, - - _matchesIssue: function(issue) - { - if (this._sourceCode instanceof WebInspector.Resource) - return issue.url === this._sourceCode.url; - // FIXME: Support issues for Scripts based on id, not only by URL. - if (this._sourceCode instanceof WebInspector.Script) - return issue.url === this._sourceCode.url; - return false; - }, - - _issueWasAdded: function(event) - { - var issue = event.data.issue; - if (!this._matchesIssue(issue)) - return; - - this._addIssue(issue); - }, - - _addIssue: function(issue) - { - var lineNumberIssues = this._issuesLineNumberMap[issue.lineNumber]; - if (!lineNumberIssues) - lineNumberIssues = this._issuesLineNumberMap[issue.lineNumber] = []; - - lineNumberIssues.push(issue); - - if (issue.level === WebInspector.IssueMessage.Level.Error) - this.addStyleClassToLine(issue.lineNumber, WebInspector.SourceCodeTextEditor.LineErrorStyleClassName); - else if (issue.level === WebInspector.IssueMessage.Level.Warning) - this.addStyleClassToLine(issue.lineNumber, WebInspector.SourceCodeTextEditor.LineWarningStyleClassName); - else - console.error("Unknown issue level"); - - // FIXME : Show the issue message on the line as a bubble. - }, - - _breakpointInfoForBreakpoint: function(breakpoint) - { - return {resolved: breakpoint.resolved, disabled: breakpoint.disabled, autoContinue: breakpoint.autoContinue}; - }, - - get _supportsDebugging() - { - if (this._sourceCode instanceof WebInspector.Resource) - return this._sourceCode.type === WebInspector.Resource.Type.Document || this._sourceCode.type === WebInspector.Resource.Type.Script; - if (this._sourceCode instanceof WebInspector.Script) - return true; - return false; - }, - - // TextEditor Delegate - - textEditorBaseURL: function(textEditor) - { - return this._sourceCode.url; - }, - - textEditorShouldHideLineNumber: function(textEditor, lineNumber) - { - return lineNumber in this._invalidLineNumbers; - }, - - textEditorGutterContextMenu: function(textEditor, lineNumber, columnNumber, editorBreakpoints, event) - { - if (!this._supportsDebugging) - return; - - event.preventDefault(); - - var contextMenu = new WebInspector.ContextMenu(event); - - // Paused. Add Continue to Here option only if we have a script identifier for the location. - if (WebInspector.debuggerManager.paused) { - var editorLineInfo = {lineNumber:lineNumber, columnNumber:columnNumber}; - var unformattedLineInfo = this._unformattedLineInfoForEditorLineInfo(editorLineInfo); - var sourceCodeLocation = this._sourceCode.createSourceCodeLocation(unformattedLineInfo.lineNumber, unformattedLineInfo.columnNumber); - - if (sourceCodeLocation.sourceCode instanceof WebInspector.Script) - var script = sourceCodeLocation.sourceCode; - else if (sourceCodeLocation.sourceCode instanceof WebInspector.Resource) - var script = sourceCodeLocation.sourceCode.scriptForLocation(sourceCodeLocation); - - if (script) { - function continueToLocation() - { - WebInspector.debuggerManager.continueToLocation(script.id, sourceCodeLocation.lineNumber, sourceCodeLocation.columnNumber); - } - - contextMenu.appendItem(WebInspector.UIString("Continue to Here"), continueToLocation); - contextMenu.appendSeparator(); - } - } - - var breakpoints = []; - for (var i = 0; i < editorBreakpoints.length; ++i) { - var lineInfo = editorBreakpoints[i]; - var breakpoint = this._breakpointForEditorLineInfo(lineInfo); - console.assert(breakpoint); - if (breakpoint) - breakpoints.push(breakpoint); - } - - // No breakpoints. - if (!breakpoints.length) { - function addBreakpoint() - { - var data = this.textEditorBreakpointAdded(this, lineNumber, columnNumber); - this.setBreakpointInfoForLineAndColumn(data.lineNumber, data.columnNumber, data.breakpointInfo); - } - - contextMenu.appendItem(WebInspector.UIString("Add Breakpoint"), addBreakpoint.bind(this)); - contextMenu.show(); - return; - } - - // Single breakpoint. - if (breakpoints.length === 1) { - var breakpoint = breakpoints[0]; - function revealInSidebar() - { - WebInspector.debuggerSidebarPanel.show(); - var treeElement = WebInspector.debuggerSidebarPanel.treeElementForRepresentedObject(breakpoint); - if (treeElement) - treeElement.revealAndSelect(); - } - - breakpoint.appendContextMenuItems(contextMenu, event.target); - contextMenu.appendSeparator(); - contextMenu.appendItem(WebInspector.UIString("Reveal in Debugger Navigation Sidebar"), revealInSidebar); - contextMenu.show(); - return; - } - - // Multiple breakpoints. - var shouldDisable = false; - for (var i = 0; i < breakpoints.length; ++i) { - if (!breakpoints[i].disabled) { - shouldDisable = true; - break; - } - } - - function removeBreakpoints() - { - for (var i = 0; i < breakpoints.length; ++i) { - var breakpoint = breakpoints[i]; - if (WebInspector.debuggerManager.isBreakpointRemovable(breakpoint)) - WebInspector.debuggerManager.removeBreakpoint(breakpoint); - } - } - - function toggleBreakpoints() - { - for (var i = 0; i < breakpoints.length; ++i) - breakpoints[i].disabled = shouldDisable; - } - - if (shouldDisable) - contextMenu.appendItem(WebInspector.UIString("Disable Breakpoints"), toggleBreakpoints.bind(this)); - else - contextMenu.appendItem(WebInspector.UIString("Enable Breakpoints"), toggleBreakpoints.bind(this)); - contextMenu.appendItem(WebInspector.UIString("Delete Breakpoints"), removeBreakpoints.bind(this)); - contextMenu.show(); - }, - - textEditorBreakpointAdded: function(textEditor, lineNumber, columnNumber) - { - if (!this._supportsDebugging) - return null; - - var editorLineInfo = {lineNumber:lineNumber, columnNumber:columnNumber}; - var unformattedLineInfo = this._unformattedLineInfoForEditorLineInfo(editorLineInfo); - var sourceCodeLocation = this._sourceCode.createSourceCodeLocation(unformattedLineInfo.lineNumber, unformattedLineInfo.columnNumber); - var breakpoint = new WebInspector.Breakpoint(sourceCodeLocation); - - var lineInfo = this._editorLineInfoForSourceCodeLocation(breakpoint.sourceCodeLocation); - this._addBreakpointWithEditorLineInfo(breakpoint, lineInfo); - - this._ignoreBreakpointAddedBreakpoint = breakpoint; - WebInspector.debuggerManager.addBreakpoint(breakpoint); - delete this._ignoreBreakpointAddedBreakpoint; - - // Return the more accurate location and breakpoint info. - return { - breakpointInfo: this._breakpointInfoForBreakpoint(breakpoint), - lineNumber: lineInfo.lineNumber, - columnNumber: lineInfo.columnNumber - }; - }, - - textEditorBreakpointRemoved: function(textEditor, lineNumber, columnNumber) - { - console.assert(this._supportsDebugging); - if (!this._supportsDebugging) - return; - - var lineInfo = {lineNumber: lineNumber, columnNumber: columnNumber}; - var breakpoint = this._breakpointForEditorLineInfo(lineInfo); - console.assert(breakpoint); - if (!breakpoint) - return; - - this._removeBreakpointWithEditorLineInfo(breakpoint, lineInfo); - - this._ignoreBreakpointRemovedBreakpoint = breakpoint; - WebInspector.debuggerManager.removeBreakpoint(breakpoint); - delete this._ignoreBreakpointAddedBreakpoint; - }, - - textEditorBreakpointMoved: function(textEditor, oldLineNumber, oldColumnNumber, newLineNumber, newColumnNumber) - { - console.assert(this._supportsDebugging); - if (!this._supportsDebugging) - return; - - var oldLineInfo = {lineNumber: oldLineNumber, columnNumber: oldColumnNumber}; - var breakpoint = this._breakpointForEditorLineInfo(oldLineInfo); - console.assert(breakpoint); - if (!breakpoint) - return; - - this._removeBreakpointWithEditorLineInfo(breakpoint, oldLineInfo); - - var newLineInfo = {lineNumber: newLineNumber, columnNumber: newColumnNumber}; - var unformattedNewLineInfo = this._unformattedLineInfoForEditorLineInfo(newLineInfo); - this._ignoreLocationUpdateBreakpoint = breakpoint; - breakpoint.sourceCodeLocation.update(this._sourceCode, unformattedNewLineInfo.lineNumber, unformattedNewLineInfo.columnNumber); - delete this._ignoreLocationUpdateBreakpoint; - - var accurateNewLineInfo = this._editorLineInfoForSourceCodeLocation(breakpoint.sourceCodeLocation); - this._addBreakpointWithEditorLineInfo(breakpoint, accurateNewLineInfo); - - if (accurateNewLineInfo.lineNumber !== newLineInfo.lineNumber || accurateNewLineInfo.columnNumber !== newLineInfo.columnNumber) - this.updateBreakpointLineAndColumn(newLineInfo.lineNumber, newLineInfo.columnNumber, accurateNewLineInfo.lineNumber, accurateNewLineInfo.columnNumber); - }, - - textEditorBreakpointClicked: function(textEditor, lineNumber, columnNumber) - { - console.assert(this._supportsDebugging); - if (!this._supportsDebugging) - return; - - var breakpoint = this._breakpointForEditorLineInfo({lineNumber: lineNumber, columnNumber: columnNumber}); - console.assert(breakpoint); - if (!breakpoint) - return; - - breakpoint.cycleToNextMode(); - }, - - textEditorUpdatedFormatting: function(textEditor) - { - this._ignoreAllBreakpointLocationUpdates = true; - this._sourceCode.formatterSourceMap = this.formatterSourceMap; - delete this._ignoreAllBreakpointLocationUpdates; - - // Always put the source map on both the Script and Resource if both exist. For example, - // if this SourceCode is a Resource, then there might also be a Script. In the debugger, - // the backend identifies call frames with Script line and column information, and the - // Script needs the formatter source map to produce the proper display line and column. - if (this._sourceCode instanceof WebInspector.Resource && !(this._sourceCode instanceof WebInspector.SourceMapResource)) { - var scripts = this._sourceCode.scripts; - for (var i = 0; i < scripts.length; ++i) - scripts[i].formatterSourceMap = this.formatterSourceMap; - } else if (this._sourceCode instanceof WebInspector.Script) { - if (this._sourceCode.resource) - this._sourceCode.resource.formatterSourceMap = this.formatterSourceMap; - } - - // Some breakpoints may have moved, some might not have. Just go through - // and remove and reinsert all the breakpoints. - - var oldBreakpointMap = this._breakpointMap; - this._breakpointMap = {}; - - for (var lineNumber in oldBreakpointMap) { - for (var columnNumber in oldBreakpointMap[lineNumber]) { - var breakpoint = oldBreakpointMap[lineNumber][columnNumber]; - var newLineInfo = this._editorLineInfoForSourceCodeLocation(breakpoint.sourceCodeLocation); - this._addBreakpointWithEditorLineInfo(breakpoint, newLineInfo); - this.setBreakpointInfoForLineAndColumn(lineNumber, columnNumber, null); - this.setBreakpointInfoForLineAndColumn(newLineInfo.lineNumber, newLineInfo.columnNumber, this._breakpointInfoForBreakpoint(breakpoint)); - } - } - }, - - _debuggerDidPause: function(event) - { - this._updateTokenTrackingControllerState(); - }, - - _debuggerDidResume: function(event) - { - this._updateTokenTrackingControllerState(); - this._dismissPopover(); - }, - - _sourceCodeSourceMapAdded: function(event) - { - WebInspector.notifications.addEventListener(WebInspector.Notification.GlobalModifierKeysDidChange, this._updateTokenTrackingControllerState, this); - this._sourceCode.removeEventListener(WebInspector.SourceCode.Event.SourceMapAdded, this._sourceCodeSourceMapAdded, this); - - this._updateTokenTrackingControllerState(); - }, - - _updateTokenTrackingControllerState: function() - { - var mode = WebInspector.CodeMirrorTokenTrackingController.Mode.None; - if (WebInspector.debuggerManager.paused) - mode = WebInspector.CodeMirrorTokenTrackingController.Mode.JavaScriptExpression; - else if (this._hasColorMarkers()) - mode = WebInspector.CodeMirrorTokenTrackingController.Mode.MarkedTokens; - else if ((this._sourceCode instanceof WebInspector.SourceMapResource || this._sourceCode.sourceMaps.length !== 0) && WebInspector.modifierKeys.metaKey && !WebInspector.modifierKeys.altKey && !WebInspector.modifierKeys.shiftKey) - mode = WebInspector.CodeMirrorTokenTrackingController.Mode.NonSymbolTokens; - - this.tokenTrackingController.enabled = mode !== WebInspector.CodeMirrorTokenTrackingController.Mode.None; - - if (mode === this.tokenTrackingController.mode) - return; - - switch (mode) { - case WebInspector.CodeMirrorTokenTrackingController.Mode.MarkedTokens: - this.tokenTrackingController.mouseOverDelayDuration = 0; - this.tokenTrackingController.mouseOutReleaseDelayDuration = 0; - break; - case WebInspector.CodeMirrorTokenTrackingController.Mode.NonSymbolTokens: - this.tokenTrackingController.mouseOverDelayDuration = 0; - this.tokenTrackingController.mouseOutReleaseDelayDuration = 0; - this.tokenTrackingController.classNameForHighlightedRange = WebInspector.CodeMirrorTokenTrackingController.JumpToSymbolHighlightStyleClassName; - this._dismissPopover(); - break; - case WebInspector.CodeMirrorTokenTrackingController.Mode.JavaScriptExpression: - this.tokenTrackingController.mouseOverDelayDuration = WebInspector.SourceCodeTextEditor.DurationToMouseOverTokenToMakeHoveredToken; - this.tokenTrackingController.mouseOutReleaseDelayDuration = WebInspector.SourceCodeTextEditor.DurationToMouseOutOfHoveredTokenToRelease; - this.tokenTrackingController.classNameForHighlightedRange = WebInspector.SourceCodeTextEditor.HoveredExpressionHighlightStyleClassName; - break; - } - - this.tokenTrackingController.mode = mode; - }, - - _hasColorMarkers: function() - { - for (var marker of this.markers) { - if (marker.type === WebInspector.TextMarker.Type.Color) - return true; - } - return false; - }, - - // CodeMirrorTokenTrackingController Delegate - - tokenTrackingControllerCanReleaseHighlightedRange: function(tokenTrackingController, element) - { - if (!this._popover) - return true; - - if (!window.getSelection().isCollapsed && this._popover.element.contains(window.getSelection().anchorNode)) - return false; - - return true; - }, - - tokenTrackingControllerHighlightedRangeReleased: function(tokenTrackingController) - { - if (!this._mouseIsOverPopover) - this._dismissPopover(); - }, - - tokenTrackingControllerHighlightedRangeWasClicked: function(tokenTrackingController) - { - if (this.tokenTrackingController.mode !== WebInspector.CodeMirrorTokenTrackingController.Mode.NonSymbolTokens) - return; - - // Links are handled by TextEditor. - if (/\blink\b/.test(this.tokenTrackingController.candidate.hoveredToken.type)) - return; - - var sourceCodeLocation = this._sourceCodeLocationForEditorPosition(this.tokenTrackingController.candidate.hoveredTokenRange.start); - if (this.sourceCode instanceof WebInspector.SourceMapResource) - WebInspector.resourceSidebarPanel.showOriginalOrFormattedSourceCodeLocation(sourceCodeLocation); - else - WebInspector.resourceSidebarPanel.showSourceCodeLocation(sourceCodeLocation); - }, - - tokenTrackingControllerNewHighlightCandidate: function(tokenTrackingController, candidate) - { - if (this.tokenTrackingController.mode === WebInspector.CodeMirrorTokenTrackingController.Mode.NonSymbolTokens) { - this.tokenTrackingController.highlightRange(candidate.hoveredTokenRange); - return; - } - - if (this.tokenTrackingController.mode === WebInspector.CodeMirrorTokenTrackingController.Mode.JavaScriptExpression) { - this._tokenTrackingControllerHighlightedJavaScriptExpression(candidate); - return; - } - - if (this.tokenTrackingController.mode === WebInspector.CodeMirrorTokenTrackingController.Mode.MarkedTokens) { - var markers = this.markersAtPosition(candidate.hoveredTokenRange.start); - if (markers.length > 0) - this._tokenTrackingControllerHighlightedMarkedExpression(candidate, markers); - else - this._dismissCodeMirrorColorEditingController(); - } - }, - - tokenTrackingControllerMouseOutOfHoveredMarker: function(tokenTrackingController, hoveredMarker) - { - this._dismissCodeMirrorColorEditingController(); - }, - - _tokenTrackingControllerHighlightedJavaScriptExpression: function(candidate) - { - console.assert(candidate.expression); - - function populate(error, result, wasThrown) - { - if (error || wasThrown) - return; - - if (candidate !== this.tokenTrackingController.candidate) - return; - - var data = WebInspector.RemoteObject.fromPayload(result); - switch (data.type) { - case "function": - this._showPopoverForFunction(data); - break; - case "object": - this._showPopoverForObject(data); - break; - case "string": - this._showPopoverForString(data); - break; - case "number": - this._showPopoverForNumber(data); - break; - case "boolean": - this._showPopoverForBoolean(data); - break; - case "undefined": - this._showPopoverForUndefined(data); - break; - } - } - - DebuggerAgent.evaluateOnCallFrame.invoke({callFrameId: WebInspector.debuggerManager.activeCallFrame.id, expression: candidate.expression, objectGroup: "popover", doNotPauseOnExceptionsAndMuteConsole: true}, populate.bind(this)); - }, - - _showPopover: function(content) - { - console.assert(this.tokenTrackingController.candidate); - - var candidate = this.tokenTrackingController.candidate; - if (!candidate) - return; - - var bounds = this.boundsForRange(candidate.hoveredTokenRange); - if (!bounds) - return; - - content.classList.add(WebInspector.SourceCodeTextEditor.PopoverDebuggerContentStyleClassName); - - this._popover = this._popover || new WebInspector.Popover(this); - this._popover.content = content; - this._popover.present(bounds.pad(5), [WebInspector.RectEdge.MIN_Y, WebInspector.RectEdge.MAX_Y, WebInspector.RectEdge.MAX_X]); - - this._trackPopoverEvents(); - - this.tokenTrackingController.highlightRange(candidate.expressionRange); - }, - - _showPopoverForFunction: function(data) - { - var candidate = this.tokenTrackingController.candidate; - - function didGetDetails(error, response) - { - if (error) { - console.error(error); - this._dismissPopover(); - return; - } - - // Nothing to do if the token has changed since the time we - // asked for the function details from the backend. - if (candidate !== this.tokenTrackingController.candidate) - return; - - var wrapper = document.createElement("div"); - wrapper.className = "body console-formatted-function"; - wrapper.textContent = data.description; - - var content = document.createElement("div"); - content.className = "function"; - - var title = content.appendChild(document.createElement("div")); - title.className = "title"; - title.textContent = response.name || response.inferredName || response.displayName || WebInspector.UIString("(anonymous function)"); - - content.appendChild(wrapper); - - this._showPopover(content); - } - DebuggerAgent.getFunctionDetails(data.objectId, didGetDetails.bind(this)); - }, - - _showPopoverForObject: function(data) - { - if (data.subtype === "null") { - this._showPopoverForNull(data); - return; - } - - var content = document.createElement("div"); - content.className = "object expandable"; - - var titleElement = document.createElement("div"); - titleElement.className = "title"; - titleElement.textContent = data.description; - content.appendChild(titleElement); - - var section = new WebInspector.ObjectPropertiesSection(data); - section.expanded = true; - section.element.classList.add("body"); - content.appendChild(section.element); - - this._showPopover(content); - }, - - _showPopoverForString: function(data) - { - var content = document.createElement("div"); - content.className = "string console-formatted-string"; - content.textContent = "\"" + data.description + "\""; - - this._showPopover(content); - }, - - _showPopoverForNumber: function(data) - { - var content = document.createElement("span"); - content.className = "number console-formatted-number"; - content.textContent = data.description; - - this._showPopover(content); - }, - - _showPopoverForBoolean: function(data) - { - var content = document.createElement("span"); - content.className = "boolean console-formatted-boolean"; - content.textContent = data.description; - - this._showPopover(content); - }, - - _showPopoverForNull: function(data) - { - var content = document.createElement("span"); - content.className = "boolean console-formatted-null"; - content.textContent = data.description; - - this._showPopover(content); - }, - - _showPopoverForUndefined: function(data) - { - var content = document.createElement("span"); - content.className = "boolean console-formatted-undefined"; - content.textContent = data.description; - - this._showPopover(content); - }, - - willDismissPopover: function(popover) - { - this.tokenTrackingController.removeHighlightedRange(); - - RuntimeAgent.releaseObjectGroup("popover"); - }, - - _dismissPopover: function() - { - if (!this._popover) - return; - - this._popover.dismiss(); - - if (this._popoverEventHandler) - this._popoverEventHandler.stopTrackingEvents(); - }, - - _trackPopoverEvents: function() - { - if (!this._popoverEventHandler) { - this._popoverEventHandler = new WebInspector.EventHandler(this, { - "mouseover": this._popoverMouseover, - "mouseout": this._popoverMouseout, - }); - } - - this._popoverEventHandler.trackEvents(this._popover.element); - }, - - _popoverMouseover: function(event) - { - this._mouseIsOverPopover = true; - }, - - _popoverMouseout: function(event) - { - this._mouseIsOverPopover = this._popover.element.contains(event.relatedTarget); - }, - - _updateColorMarkers: function(lineNumber) - { - this.createColorMarkers(lineNumber); - - this._updateTokenTrackingControllerState(); - }, - - _tokenTrackingControllerHighlightedMarkedExpression: function(candidate, markers) - { - var colorMarker; - for (var marker of markers) { - if (marker.type === WebInspector.TextMarker.Type.Color) { - colorMarker = marker; - break; - } - } - - if (!colorMarker) { - this.tokenTrackingController.hoveredMarker = null; - return; - } - - if (this.tokenTrackingController.hoveredMarker === colorMarker) - return; - - this._dismissCodeMirrorColorEditingController(); - - this.tokenTrackingController.hoveredMarker = colorMarker; - - this._colorEditingController = this.colorEditingControllerForMarker(colorMarker); - - var color = this._colorEditingController.color; - if (!color || !color.valid) { - colorMarker.clear(); - delete this._colorEditingController; - return; - } - - this._colorEditingController.delegate = this; - this._colorEditingController.presentHoverMenu(); - }, - - _dismissCodeMirrorColorEditingController: function() - { - if (this._colorEditingController) - this._colorEditingController.dismissHoverMenu(); - - this.tokenTrackingController.hoveredMarker = null; - delete this._colorEditingController; - }, - - // CodeMirrorColorEditingController Delegate - - colorEditingControllerDidStartEditing: function(colorEditingController) - { - // We can pause the token tracking controller during editing, it will be reset - // to the expected state by calling _updateColorMarkers() in the - // colorEditingControllerDidFinishEditing delegate. - this.tokenTrackingController.enabled = false; - - // We clear the marker since we'll reset it after editing. - colorEditingController.marker.clear(); - - // We ignore content changes made as a result of color editing. - this._ignoreContentDidChange++; - }, - - colorEditingControllerDidFinishEditing: function(colorEditingController) - { - this._updateColorMarkers(colorEditingController.range.startLine); - - this._ignoreContentDidChange--; - - delete this._colorEditingController; - } -}; - -WebInspector.SourceCodeTextEditor.prototype.__proto__ = WebInspector.TextEditor.prototype; diff --git a/Source/WebInspectorUI/UserInterface/SourceCodeTextRange.js b/Source/WebInspectorUI/UserInterface/SourceCodeTextRange.js deleted file mode 100644 index 59bb5030d..000000000 --- a/Source/WebInspectorUI/UserInterface/SourceCodeTextRange.js +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.SourceCodeTextRange = function(sourceCode) /* textRange || startLocation, endLocation */ -{ - WebInspector.Object.call(this); - - console.assert(sourceCode instanceof WebInspector.SourceCode); - console.assert(arguments.length === 2 || arguments.length === 3); - - this._sourceCode = sourceCode; - - if (arguments.length === 2) { - var textRange = arguments[1]; - console.assert(textRange instanceof WebInspector.TextRange); - this._startLocation = sourceCode.createSourceCodeLocation(textRange.startLine, textRange.startColumn); - this._endLocation = sourceCode.createSourceCodeLocation(textRange.endLine, textRange.endColumn); - } else { - console.assert(arguments[1] instanceof WebInspector.SourceCodeLocation); - console.assert(arguments[2] instanceof WebInspector.SourceCodeLocation); - this._startLocation = arguments[1]; - this._endLocation = arguments[2]; - } - - this._startLocation.addEventListener(WebInspector.SourceCodeLocation.Event.LocationChanged, this._sourceCodeLocationChanged, this); - this._endLocation.addEventListener(WebInspector.SourceCodeLocation.Event.LocationChanged, this._sourceCodeLocationChanged, this); -}; - -WebInspector.SourceCodeTextRange.Event = { - RangeChanged: "source-code-text-range-range-changed" -}; - -WebInspector.SourceCodeTextRange.prototype = { - constructor: WebInspector.SourceCodeTextRange, - - // Public - - get sourceCode() - { - return this._sourceCode; - }, - - // Raw text range in the original source code. - - get textRange() - { - var startLine = this._startLocation.lineNumber; - var startColumn = this._startLocation.columnNumber; - var endLine = this._endLocation.lineNumber; - var endColumn = this._endLocation.columnNumber; - return new WebInspector.TextRange(startLine, startColumn, endLine, endColumn); - }, - - // Formatted text range in the original source code if it is pretty printed. - // This is the same as the raw text range if the source code has no formatter. - - get formattedTextRange() - { - var startLine = this._startLocation.formattedLineNumber; - var startColumn = this._startLocation.formattedColumnNumber; - var endLine = this._endLocation.formattedLineNumber; - var endColumn = this._endLocation.formattedColumnNumber; - return new WebInspector.TextRange(startLine, startColumn, endLine, endColumn); - }, - - // Display values: - // - Mapped resource and text range locations if the original source code has a - // source map and both start and end locations are in the same mapped resource. - // - Otherwise this is the formatted / raw text range. - - get displaySourceCode() - { - if (!this._startAndEndLocationsInSameMappedResource()) - return this._sourceCode; - - return this._startLocation.displaySourceCode; - }, - - get displayTextRange() - { - if (!this._startAndEndLocationsInSameMappedResource()) - return this.formattedTextRange; - - var startLine = this._startLocation.displayLineNumber; - var startColumn = this._startLocation.displayColumnNumber; - var endLine = this._endLocation.displayLineNumber; - var endColumn = this._endLocation.displayColumnNumber; - return new WebInspector.TextRange(startLine, startColumn, endLine, endColumn); - }, - - // Private - - _startAndEndLocationsInSameMappedResource: function() - { - return this._startLocation.hasMappedLocation() && this._endLocation.hasMappedLocation() && this._startLocation.displaySourceCode === this._endLocation.displaySourceCode; - }, - - _sourceCodeLocationChanged: function(event) - { - this.dispatchEventToListeners(WebInspector.SourceCodeLocation.Event.RangeChanged); - } -}; - -WebInspector.SourceCodeTextRange.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/SourceCodeTimeline.js b/Source/WebInspectorUI/UserInterface/SourceCodeTimeline.js deleted file mode 100644 index 348ff57fe..000000000 --- a/Source/WebInspectorUI/UserInterface/SourceCodeTimeline.js +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.SourceCodeTimeline = function(sourceCode, sourceCodeLocation, recordType, recordEventType) -{ - WebInspector.Timeline.call(this); - - console.assert(sourceCode); - console.assert(!sourceCodeLocation || sourceCodeLocation.sourceCode === sourceCode); - console.assert(recordType); - - this._sourceCode = sourceCode; - this._sourceCodeLocation = sourceCodeLocation || null; - this._recordType = recordType; - this._recordEventType = recordEventType || null; -}; - -WebInspector.SourceCodeTimeline.TypeIdentifier = "source-code-timeline"; -WebInspector.SourceCodeTimeline.SourceCodeURLCookieKey = "source-code-timeline-source-code-url"; -WebInspector.SourceCodeTimeline.SourceCodeLocationLineCookieKey = "source-code-timeline-source-code-location-line"; -WebInspector.SourceCodeTimeline.SourceCodeLocationColumnCookieKey = "source-code-timeline-source-code-location-column"; -WebInspector.SourceCodeTimeline.SourceCodeURLCookieKey = "source-code-timeline-source-code-url"; -WebInspector.SourceCodeTimeline.RecordTypeCookieKey = "source-code-timeline-record-type"; -WebInspector.SourceCodeTimeline.RecordEventTypeCookieKey = "source-code-timeline-record-event-type"; - -WebInspector.SourceCodeTimeline.prototype = { - constructor: WebInspector.SourceCodeTimeline, - __proto__: WebInspector.Timeline.prototype, - - // Public - - get sourceCode() - { - return this._sourceCode; - }, - - get sourceCodeLocation() - { - return this._sourceCodeLocation; - }, - - get recordType() - { - return this._recordType; - }, - - get recordEventType() - { - return this._recordEventType; - }, - - saveIdentityToCookie: function(cookie) - { - cookie[WebInspector.SourceCodeTimeline.SourceCodeURLCookieKey] = this._sourceCode.url ? this._sourceCode.url.hash : null; - cookie[WebInspector.SourceCodeTimeline.SourceCodeLocationLineCookieKey] = this._sourceCodeLocation ? this._sourceCodeLocation.lineNumber : null; - cookie[WebInspector.SourceCodeTimeline.SourceCodeLocationColumnCookieKey] = this._sourceCodeLocation ? this._sourceCodeLocation.columnNumber : null; - cookie[WebInspector.SourceCodeTimeline.RecordTypeCookieKey] = this._recordType || null; - cookie[WebInspector.SourceCodeTimeline.RecordEventTypeCookieKey] = this._recordEventType || null; - } -}; diff --git a/Source/WebInspectorUI/UserInterface/SourceCodeTimelineTimelineDataGridNode.js b/Source/WebInspectorUI/UserInterface/SourceCodeTimelineTimelineDataGridNode.js deleted file mode 100644 index a527e4f3a..000000000 --- a/Source/WebInspectorUI/UserInterface/SourceCodeTimelineTimelineDataGridNode.js +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (C) 2014 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.SourceCodeTimelineTimelineDataGridNode = function(sourceCodeTimeline, graphDataSource) -{ - WebInspector.TimelineDataGridNode.call(this, true, graphDataSource); - - this._sourceCodeTimeline = sourceCodeTimeline; - this._sourceCodeTimeline.addEventListener(WebInspector.Timeline.Event.RecordAdded, this._timelineRecordAdded, this); -}; - -WebInspector.Object.addConstructorFunctions(WebInspector.SourceCodeTimelineTimelineDataGridNode); - -WebInspector.SourceCodeTimelineTimelineDataGridNode.prototype = { - constructor: WebInspector.SourceCodeTimelineTimelineDataGridNode, - __proto__: WebInspector.TimelineDataGridNode.prototype, - - // Public - - get records() - { - return this._sourceCodeTimeline.records; - }, - - get sourceCodeTimeline() - { - return this._sourceCodeTimeline; - }, - - get data() - { - return {graph: this._sourceCodeTimeline.startTime}; - }, - - // Private - - _timelineRecordAdded: function(event) - { - if (this.isRecordVisible(event.data.record)) - this.needsGraphRefresh(); - } -}; diff --git a/Source/WebInspectorUI/UserInterface/SourceCodeTimelineTreeElement.js b/Source/WebInspectorUI/UserInterface/SourceCodeTimelineTreeElement.js deleted file mode 100644 index 0c6355630..000000000 --- a/Source/WebInspectorUI/UserInterface/SourceCodeTimelineTreeElement.js +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.SourceCodeTimelineTreeElement = function(sourceCodeTimeline, subtitleNameStyle, includeTimerIdentifierInMainTitle) -{ - console.assert(sourceCodeTimeline); - - this._sourceCodeTimeline = sourceCodeTimeline; - - subtitleNameStyle = subtitleNameStyle || WebInspector.SourceCodeLocation.NameStyle.None; - - WebInspector.TimelineRecordTreeElement.call(this, sourceCodeTimeline.records[0], subtitleNameStyle, includeTimerIdentifierInMainTitle, sourceCodeTimeline.sourceCodeLocation, sourceCodeTimeline); -}; - -WebInspector.SourceCodeTimelineTreeElement.prototype = { - constructor: WebInspector.SourceCodeTimelineTreeElement, - __proto__: WebInspector.TimelineRecordTreeElement.prototype, - - // Public - - record: undefined, - - get sourceCodeTimeline() - { - return this._sourceCodeTimeline; - } -}; diff --git a/Source/WebInspectorUI/UserInterface/SourceCodeTreeElement.js b/Source/WebInspectorUI/UserInterface/SourceCodeTreeElement.js deleted file mode 100644 index d885eb28d..000000000 --- a/Source/WebInspectorUI/UserInterface/SourceCodeTreeElement.js +++ /dev/null @@ -1,208 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.SourceCodeTreeElement = function(sourceCode, classNames, title, subtitle, representedObject, hasChildren) -{ - console.assert(sourceCode instanceof WebInspector.SourceCode); - - WebInspector.GeneralTreeElement.call(this, classNames, title, subtitle, representedObject || sourceCode, hasChildren); - - this.small = true; - - this._updateSourceCode(sourceCode); -}; - -WebInspector.SourceCodeTreeElement.prototype = { - constructor: WebInspector.SourceCodeTreeElement, - - // Public - - updateSourceMapResources: function() - { - if (!this.treeOutline || !this.treeOutline.includeSourceMapResourceChildren) - return; - - this.hasChildren = !!this._sourceCode.sourceMaps.length; - this.shouldRefreshChildren = this.hasChildren; - - if (!this.hasChildren) - this.removeChildren(); - }, - - // Overrides from TreeElement - - onattach: function() - { - WebInspector.GeneralTreeElement.prototype.onattach.call(this); - - this.updateSourceMapResources(); - }, - - onpopulate: function() - { - if (!this.treeOutline || !this.treeOutline.includeSourceMapResourceChildren) - return; - - if (!this.hasChildren || !this.shouldRefreshChildren) - return; - - this.shouldRefreshChildren = false; - - this.removeChildren(); - - function combineFolderChain(topFolder, bottomFolder) - { - console.assert(topFolder.children.length === 1); - - var components = []; - - for (var currentFolder = bottomFolder; currentFolder !== topFolder; currentFolder = currentFolder.parent) - components.push(currentFolder.mainTitle); - components.push(topFolder.mainTitle); - - var folderName = components.reverse().join("/"); - var newFolder = new WebInspector.FolderTreeElement(folderName); - - var folderIndex = topFolder.parent.children.indexOf(topFolder); - topFolder.parent.insertChild(newFolder, folderIndex); - topFolder.parent.removeChild(topFolder); - - var children = bottomFolder.children; - bottomFolder.removeChildren(); - for (var i = 0; i < children.length; ++i) - newFolder.appendChild(children[i]); - } - - function findAndCombineFolderChains(treeElement, previousSingleTreeElement) - { - if (!(treeElement instanceof WebInspector.FolderTreeElement)) { - if (previousSingleTreeElement && previousSingleTreeElement !== treeElement.parent) - combineFolderChain(previousSingleTreeElement, treeElement.parent); - return; - } - - if (previousSingleTreeElement && treeElement.children.length !== 1) { - combineFolderChain(previousSingleTreeElement, treeElement); - previousSingleTreeElement = null; - } - - if (!previousSingleTreeElement && treeElement.children.length === 1) - previousSingleTreeElement = treeElement; - - for (var i = 0; i < treeElement.children.length; ++i) - findAndCombineFolderChains(treeElement.children[i], previousSingleTreeElement); - } - - var sourceMaps = this._sourceCode.sourceMaps; - for (var i = 0; i < sourceMaps.length; ++i) { - var sourceMap = sourceMaps[i]; - for (var j = 0; j < sourceMap.resources.length; ++j) { - var sourceMapResource = sourceMap.resources[j]; - var relativeSubpath = sourceMapResource.sourceMapDisplaySubpath; - var folderTreeElement = this.createFoldersAsNeededForSubpath(relativeSubpath); - var sourceMapTreeElement = new WebInspector.SourceMapResourceTreeElement(sourceMapResource); - folderTreeElement.insertChild(sourceMapTreeElement, insertionIndexForObjectInListSortedByFunction(sourceMapTreeElement, folderTreeElement.children, WebInspector.ResourceTreeElement.compareFolderAndResourceTreeElements)); - } - } - - for (var i = 0; i < this.children.length; ++i) - findAndCombineFolderChains(this.children[i], null); - }, - - // Protected - - createFoldersAsNeededForSubpath: function(subpath) - { - if (!subpath) - return this; - - var components = subpath.split("/"); - if (components.length === 1) - return this; - - if (!this._subpathFolderTreeElementMap) - this._subpathFolderTreeElementMap = {}; - - var currentPath = ""; - var currentFolderTreeElement = this; - - for (var i = 0 ; i < components.length - 1; ++i) { - var componentName = components[i]; - currentPath += (i ? "/" : "") + componentName; - - var cachedFolder = this._subpathFolderTreeElementMap[currentPath]; - if (cachedFolder) { - currentFolderTreeElement = cachedFolder; - continue; - } - - var newFolder = new WebInspector.FolderTreeElement(componentName); - newFolder.__path = currentPath; - this._subpathFolderTreeElementMap[currentPath] = newFolder; - - var index = insertionIndexForObjectInListSortedByFunction(newFolder, currentFolderTreeElement.children, WebInspector.ResourceTreeElement.compareFolderAndResourceTreeElements); - currentFolderTreeElement.insertChild(newFolder, index); - currentFolderTreeElement = newFolder; - } - - return currentFolderTreeElement; - }, - - descendantResourceTreeElementTypeDidChange: function(childTreeElement, oldType) - { - // Called by descendant SourceMapResourceTreeElements. - - console.assert(this.hasChildren); - - var wasSelected = childTreeElement.selected; - - var parentTreeElement = childTreeElement.parent; - parentTreeElement.removeChild(childTreeElement, true, true); - parentTreeElement.insertChild(childTreeElement, insertionIndexForObjectInListSortedByFunction(childTreeElement, parentTreeElement.children, WebInspector.ResourceTreeElement.compareFolderAndResourceTreeElements)); - - if (wasSelected) - childTreeElement.revealAndSelect(true, false, true, true); - }, - - // Protected (ResourceTreeElement calls this when its Resource changes dynamically for Frames) - - _updateSourceCode: function(sourceCode) - { - console.assert(sourceCode instanceof WebInspector.SourceCode); - - if (this._sourceCode === sourceCode) - return; - - if (this._sourceCode) - this._sourceCode.removeEventListener(WebInspector.SourceCode.Event.SourceMapAdded, this.updateSourceMapResources, this); - - this._sourceCode = sourceCode; - this._sourceCode.addEventListener(WebInspector.SourceCode.Event.SourceMapAdded, this.updateSourceMapResources, this); - - this.updateSourceMapResources(); - } -}; - -WebInspector.SourceCodeTreeElement.prototype.__proto__ = WebInspector.GeneralTreeElement.prototype; diff --git a/Source/WebInspectorUI/UserInterface/SourceMap.js b/Source/WebInspectorUI/UserInterface/SourceMap.js deleted file mode 100644 index b910baadd..000000000 --- a/Source/WebInspectorUI/UserInterface/SourceMap.js +++ /dev/null @@ -1,333 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -/** - * Implements Source Map V3 model. See http://code.google.com/p/closure-compiler/wiki/SourceMaps - * for format description. - * @constructor - * @param {string} sourceMappingURL - * @param {SourceMapV3} payload - * @param {WebInspector.Resource|WebInspector.Script} originalSourceCode - */ -WebInspector.SourceMap = function(sourceMappingURL, payload, originalSourceCode) -{ - 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._originalSourceCode = originalSourceCode || null; - this._sourceMapResources = {}; - this._sourceMapResourcesList = []; - - this._sourceMappingURL = sourceMappingURL; - this._reverseMappingsBySourceURL = {}; - this._mappings = []; - this._sources = {}; - this._sourceRoot = null; - this._sourceContentByURL = {}; - this._parseMappingPayload(payload); -} - -WebInspector.SourceMap.prototype = { - - get originalSourceCode() - { - return this._originalSourceCode; - }, - - get sourceMappingBasePathURLComponents() - { - if (this._sourceMappingURLBasePathComponents) - return this._sourceMappingURLBasePathComponents; - - if (this._sourceRoot) { - var baseURLPath = absoluteURL(this._sourceRoot, this._sourceMappingURL); - console.assert(baseURLPath); - if (baseURLPath) { - var urlComponents = parseURL(baseURLPath); - if (!/\/$/.test(urlComponents.path)) - urlComponents.path += "/"; - this._sourceMappingURLBasePathComponents = urlComponents; - return this._sourceMappingURLBasePathComponents; - } - } - - var urlComponents = parseURL(this._sourceMappingURL); - urlComponents.path = urlComponents.path.substr(0, urlComponents.path.lastIndexOf(urlComponents.lastPathComponent)); - urlComponents.lastPathComponent = null; - this._sourceMappingURLBasePathComponents = urlComponents; - return this._sourceMappingURLBasePathComponents; - }, - - get resources() - { - return this._sourceMapResourcesList; - }, - - addResource: function(resource) - { - console.assert(!(resource.url in this._sourceMapResources)); - this._sourceMapResources[resource.url] = resource; - this._sourceMapResourcesList.push(resource); - }, - - resourceForURL: function(url) - { - return this._sourceMapResources[url]; - }, - - /** - * @return {Array.} - */ - sources: function() - { - return Object.keys(this._sources); - }, - - /** - * @param {string} sourceURL - * @return {string|undefined} - */ - sourceContent: function(sourceURL) - { - return this._sourceContentByURL[sourceURL]; - }, - - /** - * @param {SourceMapV3} mappingPayload - */ - _parseMappingPayload: function(mappingPayload) - { - if (mappingPayload.sections) - this._parseSections(mappingPayload.sections); - else - this._parseMap(mappingPayload, 0, 0); - }, - - /** - * @param {Array.} sections - */ - _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); - } - }, - - /** - * @param {number} lineNumber in compiled resource - * @param {number} columnNumber in compiled resource - * @return {?Array} - */ - 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; - }, - - /** - * @param {string} sourceURL of the originating resource - * @param {number} lineNumber in the originating resource - * @return {Array} - */ - findEntryReversed: function(sourceURL, lineNumber) - { - var mappings = this._reverseMappingsBySourceURL[sourceURL]; - for ( ; lineNumber < mappings.length; ++lineNumber) { - var mapping = mappings[lineNumber]; - if (mapping) - return mapping; - } - return this._mappings[0]; - }, - - /** - * @param {SourceMapV3} map - * @param {number} lineNumber - * @param {number} columnNumber - */ - _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 href = originalSourceURL; - if (map.sourceRoot && href.charAt(0) !== "/") - href = map.sourceRoot.replace(/\/+$/, "") + "/" + href; - var url = absoluteURL(href, this._sourceMappingURL) || href; - originalToCanonicalURLMap[originalSourceURL] = url; - sources.push(url); - this._sources[url] = true; - - if (map.sourcesContent && map.sourcesContent[i]) - this._sourceContentByURL[url] = map.sourcesContent[i]; - } - - this._sourceRoot = map.sourceRoot || null; - - 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 (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]]; - } - }, - - /** - * @param {string} char - * @return {boolean} - */ - _isSeparator: function(char) - { - return char === "," || char === ";"; - }, - - /** - * @param {WebInspector.SourceMap.StringCharIterator} stringCharIterator - * @return {number} - */ - _decodeVLQ: function(stringCharIterator) - { - // Read unsigned value. - 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); - - // Fix the sign. - 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 -} - -/** - * @constructor - * @param {string} string - */ -WebInspector.SourceMap.StringCharIterator = function(string) -{ - this._string = string; - this._position = 0; -} - -WebInspector.SourceMap.StringCharIterator.prototype = { - /** - * @return {string} - */ - next: function() - { - return this._string.charAt(this._position++); - }, - - /** - * @return {string} - */ - peek: function() - { - return this._string.charAt(this._position); - }, - - /** - * @return {boolean} - */ - hasNext: function() - { - return this._position < this._string.length; - } -} diff --git a/Source/WebInspectorUI/UserInterface/SourceMapManager.js b/Source/WebInspectorUI/UserInterface/SourceMapManager.js deleted file mode 100644 index ba36c040a..000000000 --- a/Source/WebInspectorUI/UserInterface/SourceMapManager.js +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.SourceMapManager = function() -{ - WebInspector.Object.call(this); - - this._sourceMapURLMap = {}; - this._downloadingSourceMaps = {}; - - WebInspector.Frame.addEventListener(WebInspector.Frame.Event.MainResourceDidChange, this._mainResourceDidChange, this); -}; - -WebInspector.SourceMapManager.prototype = { - constructor: WebInspector.SourceMapManager, - - // Public - - sourceMapForURL: function(sourceMapURL) - { - return this._sourceMapURLMap[sourceMapURL]; - }, - - downloadSourceMap: function(sourceMapURL, baseURL, originalSourceCode) - { - sourceMapURL = absoluteURL(sourceMapURL, baseURL); - if (!sourceMapURL) - return; - - console.assert(originalSourceCode.url); - if (!originalSourceCode.url) - return; - - // FIXME: Source Maps: Better handle when multiple resources reference the same SourceMap - - if (sourceMapURL in this._sourceMapURLMap) - return; - - if (sourceMapURL in this._downloadingSourceMaps) - return; - - this._loadAndParseSourceMap(sourceMapURL, baseURL, originalSourceCode); - }, - - // Private - - _loadAndParseSourceMap: function(sourceMapURL, baseURL, originalSourceCode) - { - this._downloadingSourceMaps[sourceMapURL] = true; - - // FIXME: Source Maps: Frontend needs asynchronous resource loading of content + mime type - var response = InspectorFrontendHost.loadResourceSynchronously(sourceMapURL); - if (response === undefined) { - this._loadAndParseFailed(sourceMapURL); - return; - } - - if (response.slice(0, 3) === ")]}") { - var firstNewlineIndex = response.indexOf("\n"); - if (firstNewlineIndex === -1) { - this._loadAndParseFailed(sourceMapURL); - return; - } - response = response.substring(firstNewlineIndex); - } - - try { - var payload = JSON.parse(response); - var baseURL = sourceMapURL.startsWith("data:") ? originalSourceCode.url : sourceMapURL; - var sourceMap = new WebInspector.SourceMap(baseURL, payload, originalSourceCode); - this._loadAndParseSucceeded(sourceMapURL, sourceMap); - } catch(e) { - console.error(e.message); - this._loadAndParseFailed(sourceMapURL); - } - }, - - _loadAndParseFailed: function(sourceMapURL) - { - delete this._downloadingSourceMaps[sourceMapURL]; - }, - - _loadAndParseSucceeded: function(sourceMapURL, sourceMap) - { - if (!(sourceMapURL in this._downloadingSourceMaps)) - return; - - delete this._downloadingSourceMaps[sourceMapURL]; - - this._sourceMapURLMap[sourceMapURL] = sourceMap; - - var sources = sourceMap.sources(); - for (var i = 0; i < sources.length; ++i) { - var sourceMapResource = new WebInspector.SourceMapResource(sources[i], sourceMap); - sourceMap.addResource(sourceMapResource); - } - - // Associate the SourceMap with the originalSourceCode. - sourceMap.originalSourceCode.addSourceMap(sourceMap); - - // If the originalSourceCode was not a Resource, be sure to also associate with the Resource if one exists. - // FIXME: We should try to use the right frame instead of a global lookup by URL. - if (!(sourceMap.originalSourceCode instanceof WebInspector.Resource)) { - console.assert(sourceMap.originalSourceCode instanceof WebInspector.Script); - var resource = sourceMap.originalSourceCode.resource; - if (resource) - resource.addSourceMap(sourceMap); - } - }, - - _mainResourceDidChange: function(event) - { - if (!event.target.isMainFrame()) - return; - - this._sourceMapURLMap = {}; - this._downloadingSourceMaps = {}; - } -}; - -WebInspector.SourceMapManager.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/SourceMapResource.js b/Source/WebInspectorUI/UserInterface/SourceMapResource.js deleted file mode 100644 index 0fed0393a..000000000 --- a/Source/WebInspectorUI/UserInterface/SourceMapResource.js +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.SourceMapResource = function(url, sourceMap) -{ - WebInspector.Resource.call(this, url, null); - - console.assert(url); - console.assert(sourceMap); - - this._sourceMap = sourceMap; -}; - -WebInspector.SourceMapResource.prototype = { - constructor: WebInspector.SourceMapResource, - - // Public - - get sourceMap() - { - return this._sourceMap; - }, - - get sourceMapDisplaySubpath() - { - var sourceMappingBasePathURLComponents = this._sourceMap.sourceMappingBasePathURLComponents; - var resourceURLComponents = this.urlComponents; - - // Different schemes / hosts. Return the host + path of this resource. - if (resourceURLComponents.scheme !== sourceMappingBasePathURLComponents.scheme || resourceURLComponents.host !== sourceMappingBasePathURLComponents.host) - return resourceURLComponents.host + (resourceURLComponents.port ? (":" + resourceURLComponents.port) : "") + resourceURLComponents.path; - - // Same host, but not a subpath of the base. This implies a ".." in the relative path. - if (!resourceURLComponents.path.startsWith(sourceMappingBasePathURLComponents.path)) - return relativePath(resourceURLComponents.path, sourceMappingBasePathURLComponents.path); - - // Same host. Just a subpath of the base. - return resourceURLComponents.path.substring(sourceMappingBasePathURLComponents.path.length, resourceURLComponents.length); - }, - - canRequestContentFromBackend: function() - { - return !this.finished; - }, - - requestContentFromBackend: function(callback) - { - function requestAsyncCallback(body, base64encoded, mimeType) - { - if (body === null) { - this.markAsFailed(); - callback("Failed to load resource", body, base64encoded); - return; - } - - var oldType = this._type; - var oldMIMEType = this._mimeType; - - this._mimeType = mimeType; - this._type = WebInspector.Resource.Type.fromMIMEType(this._mimeType); - - if (oldMIMEType !== mimeType) { - // Delete the MIME-type components so the MIME-type is re-parsed the next time it is requested. - delete this._mimeTypeComponents; - - this.dispatchEventToListeners(WebInspector.Resource.Event.MIMETypeDidChange, {oldMIMEType: oldMIMEType}); - } - - if (oldType !== this._type) - this.dispatchEventToListeners(WebInspector.Resource.Event.TypeDidChange, {oldType: oldType}); - - this.markAsFinished(); - - callback(null, body, base64encoded); - } - - this._requestResourceAsynchronously(requestAsyncCallback.bind(this)); - return true; - }, - - createSourceCodeLocation: function(lineNumber, columnNumber) - { - // SourceCodeLocations are always constructed with raw resources and raw locations. Lookup the raw location. - var entry = this._sourceMap.findEntryReversed(this.url, lineNumber); - var rawLineNumber = entry[0]; - var rawColumnNumber = entry[1]; - - // If the raw location is an inline script we need to include that offset. - var originalSourceCode = this._sourceMap.originalSourceCode; - if (originalSourceCode instanceof WebInspector.Script) { - if (rawLineNumber === 0) - rawColumnNumber += originalSourceCode.range.startColumn; - rawLineNumber += originalSourceCode.range.startLine; - } - - // Create the SourceCodeLocation and since we already know the the mapped location set it directly. - var location = originalSourceCode.createSourceCodeLocation(rawLineNumber, rawColumnNumber); - location._setMappedLocation(this, lineNumber, columnNumber); - return location; - }, - - createSourceCodeTextRange: function(textRange) - { - // SourceCodeTextRanges are always constructed with raw resources and raw locations. - // However, we can provide the most accurate mapped locations in construction. - var startSourceCodeLocation = this.createSourceCodeLocation(textRange.startLine, textRange.startColumn); - var endSourceCodeLocation = this.createSourceCodeLocation(textRange.endLine, textRange.endColumn); - return new WebInspector.SourceCodeTextRange(this._sourceMap.originalSourceCode, startSourceCodeLocation, endSourceCodeLocation); - }, - - // Private - - _requestResourceAsynchronously: function(callback) - { - // FIXME: Source Maps: Frontend needs asynchronous resource loading of content + mime type - - function async() - { - var body = this._sourceMap.sourceContent(this.url) || InspectorFrontendHost.loadResourceSynchronously(this.url); - if (body === undefined) - body = null; - var fileExtension = WebInspector.fileExtensionForURL(this.url); - var mimeType = WebInspector.mimeTypeForFileExtension(fileExtension, true) || "text/javascript"; - callback(body, false, mimeType); - } - - setTimeout(async.bind(this), 0); - } -}; - -WebInspector.SourceMapResource.prototype.__proto__ = WebInspector.Resource.prototype; diff --git a/Source/WebInspectorUI/UserInterface/SourceMapResourceTreeElement.js b/Source/WebInspectorUI/UserInterface/SourceMapResourceTreeElement.js deleted file mode 100644 index 9d9d90574..000000000 --- a/Source/WebInspectorUI/UserInterface/SourceMapResourceTreeElement.js +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.SourceMapResourceTreeElement = function(sourceMapResource, representedObject) -{ - console.assert(sourceMapResource instanceof WebInspector.SourceMapResource); - - WebInspector.ResourceTreeElement.call(this, sourceMapResource); - - console.assert(this.resource === sourceMapResource); - - this.addClassName(WebInspector.SourceMapResourceTreeElement.StyleClassName); -}; - -WebInspector.SourceMapResourceTreeElement.StyleClassName = "source-map-resource"; - -WebInspector.SourceMapResourceTreeElement.prototype = { - constructor: WebInspector.SourceMapResourceTreeElement, - - // Protected - - onattach: function() - { - WebInspector.ResourceTreeElement.prototype.onattach.call(this); - - // SourceMap resources must be loaded by the frontend, and only - // then do they get their type information. So force a load as - // soon as they are attached to the sidebar. - this.resource.requestContent(function() {}); - }, - - _updateTitles: function() - { - var oldMainTitle = this.mainTitle; - this.mainTitle = this.resource.displayName; - - // Show the host as the subtitle if it is different from the originalSourceCode's host. - var sourceMapHost = this.resource.urlComponents.host; - var originalHost = this.resource.sourceMap.originalSourceCode.urlComponents.host; - var subtitle = sourceMapHost !== originalHost ? WebInspector.displayNameForHost(sourceMapHost) : null; - this.subtitle = this.mainTitle !== subtitle ? subtitle : null; - - if (oldMainTitle !== this.mainTitle) - this.callFirstAncestorFunction("descendantResourceTreeElementMainTitleDidChange", [this, oldMainTitle]); - } -}; - -WebInspector.SourceMapResourceTreeElement.prototype.__proto__ = WebInspector.ResourceTreeElement.prototype; diff --git a/Source/WebInspectorUI/UserInterface/StorageManager.js b/Source/WebInspectorUI/UserInterface/StorageManager.js deleted file mode 100644 index fa0c94ce6..000000000 --- a/Source/WebInspectorUI/UserInterface/StorageManager.js +++ /dev/null @@ -1,234 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * Copyright (C) 2013 Samsung Electronics. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.StorageManager = function() -{ - WebInspector.Object.call(this); - - if (window.DOMStorageAgent) - DOMStorageAgent.enable(); - if (window.DatabaseAgent) - DatabaseAgent.enable(); - - WebInspector.Frame.addEventListener(WebInspector.Frame.Event.MainResourceDidChange, this._mainResourceDidChange, this); - - // COMPATIBILITY (iOS 6): DOMStorage was discovered via a DOMStorageObserver event. Now DOM Storage - // is added whenever a new securityOrigin is discovered. Check for DOMStorageAgent.getDOMStorageItems, - // which was renamed at the same time the change to start using securityOrigin was made. - if (window.DOMStorageAgent && DOMStorageAgent.getDOMStorageItems) - WebInspector.Frame.addEventListener(WebInspector.Frame.Event.SecurityOriginDidChange, this._securityOriginDidChange, this); - - this.initialize(); -}; - -WebInspector.StorageManager.Event = { - CookieStorageObjectWasAdded: "storage-manager-cookie-storage-object-was-added", - DOMStorageObjectWasAdded: "storage-manager-dom-storage-object-was-added", - DOMStorageObjectWasInspected: "storage-dom-object-was-inspected", - DatabaseWasAdded: "storage-manager-database-was-added", - DatabaseWasInspected: "storage-object-was-inspected", - Cleared: "storage-manager-cleared" -}; - -WebInspector.StorageManager.prototype = { - constructor: WebInspector.StorageManager, - - // Public - - initialize: function() - { - this._domStorageObjects = []; - this._databaseObjects = []; - this._cookieStorageObjects = {}; - }, - - domStorageWasAdded: function(id, host, isLocalStorage) - { - var domStorage = new WebInspector.DOMStorageObject(id, host, isLocalStorage); - - this._domStorageObjects.push(domStorage); - this.dispatchEventToListeners(WebInspector.StorageManager.Event.DOMStorageObjectWasAdded, {domStorage: domStorage}); - }, - - databaseWasAdded: function(id, host, name, version) - { - var database = new WebInspector.DatabaseObject(id, host, name, version); - - this._databaseObjects.push(database); - this.dispatchEventToListeners(WebInspector.StorageManager.Event.DatabaseWasAdded, {database: database}); - }, - - domStorageWasUpdated: function(id) - { - var domStorageView = this._domStorageViewForId(id); - if (!domStorageView) - return; - - console.assert(domStorageView instanceof WebInspector.DOMStorageContentView); - domStorageView.update(); - }, - - domStorageItemsCleared: function(id) - { - var domStorageView = this._domStorageViewForId(id); - if (!domStorageView) - return; - - console.assert(domStorageView instanceof WebInspector.DOMStorageContentView); - domStorageView.itemsCleared(); - }, - - domStorageItemRemoved: function(id, key) - { - var domStorageView = this._domStorageViewForId(id); - if (!domStorageView) - return; - - console.assert(domStorageView instanceof WebInspector.DOMStorageContentView); - domStorageView.itemRemoved(key); - }, - - domStorageItemAdded: function(id, key, value) - { - var domStorageView = this._domStorageViewForId(id); - if (!domStorageView) - return; - - console.assert(domStorageView instanceof WebInspector.DOMStorageContentView); - domStorageView.itemAdded(key, value); - }, - - domStorageItemUpdated: function(id, key, oldValue, value) - { - var domStorageView = this._domStorageViewForId(id); - if (!domStorageView) - return; - - console.assert(domStorageView instanceof WebInspector.DOMStorageContentView); - domStorageView.itemUpdated(key, oldValue, value); - }, - - inspectDatabase: function(id) - { - var database = this._databaseForId(id); - console.assert(database); - if (!database) - return; - this.dispatchEventToListeners(WebInspector.StorageManager.Event.DatabaseWasInspected, {database: database}); - }, - - inspectDOMStorage: function(id) - { - var domStorage = this._domStorageForId(id); - console.assert(domStorage); - if (!domStorage) - return; - this.dispatchEventToListeners(WebInspector.StorageManager.Event.DOMStorageObjectWasInspected, {domStorage: domStorage}); - }, - - // Private - - _mainResourceDidChange: function(event) - { - console.assert(event.target instanceof WebInspector.Frame); - - if (event.target.isMainFrame()) { - // If we are dealing with the main frame, we want to clear our list of objects, because we are navigating to a new page. - this.initialize(); - this.dispatchEventToListeners(WebInspector.StorageManager.Event.Cleared); - - this._addDOMStorageIfNeeded(event.target); - } - - // Add the host of the frame that changed the main resource to the list of hosts there could be cookies for. - var host = parseURL(event.target.url).host; - if (!host) - return; - - if (this._cookieStorageObjects[host]) - return; - - this._cookieStorageObjects[host] = new WebInspector.CookieStorageObject(host); - this.dispatchEventToListeners(WebInspector.StorageManager.Event.CookieStorageObjectWasAdded, {cookieStorage: this._cookieStorageObjects[host]}); - }, - - _addDOMStorageIfNeeded: function(frame) - { - // Don't show storage if we don't have a security origin (about:blank). - if (!frame.securityOrigin || frame.securityOrigin === "://") - return; - - // FIXME: Consider passing the other parts of the origin along to domStorageWasAdded. - - var localStorageIdentifier = {securityOrigin: frame.securityOrigin, isLocalStorage: true}; - if (!this._domStorageForId(localStorageIdentifier)) - this.domStorageWasAdded(localStorageIdentifier, frame.mainResource.urlComponents.host, true); - - var sessionStorageIdentifier = {securityOrigin: frame.securityOrigin, isLocalStorage: false}; - if (!this._domStorageForId(sessionStorageIdentifier)) - this.domStorageWasAdded(sessionStorageIdentifier, frame.mainResource.urlComponents.host, false); - }, - - _securityOriginDidChange: function(event) - { - console.assert(event.target instanceof WebInspector.Frame); - - this._addDOMStorageIfNeeded(event.target); - }, - - _databaseForId: function(id) - { - for (var i = 0; i < this._databaseObjects.length; ++i) { - if (this._databaseObjects[i].id === id) - return this._databaseObjects[i]; - } - - return null; - }, - - _domStorageForId: function(id) - { - for (var i = 0; i < this._domStorageObjects.length; ++i) { - // The id is an object, so we need to compare the properties using Object.shallowEqual. - // COMPATIBILITY (iOS 6): The id was a string. Object.shallowEqual works for both. - if (Object.shallowEqual(this._domStorageObjects[i].id, id)) - return this._domStorageObjects[i]; - } - - return null; - }, - - _domStorageViewForId: function(id) - { - var domStorage = this._domStorageForId(id); - if (!domStorage) - return null; - - return WebInspector.contentBrowser.contentViewContainer.contentViewForRepresentedObject(domStorage, true); - } -}; - -WebInspector.StorageManager.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/StorageTreeElement.js b/Source/WebInspectorUI/UserInterface/StorageTreeElement.js deleted file mode 100644 index dc72e8b3f..000000000 --- a/Source/WebInspectorUI/UserInterface/StorageTreeElement.js +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.StorageTreeElement = function(classNames, title, representedObject) -{ - WebInspector.GeneralTreeElement.call(this, classNames, title, null, representedObject, false); - - this.small = true; - this.flattened = false; -}; - -WebInspector.StorageTreeElement.prototype = { - constructor: WebInspector.StorageTreeElement, - - // Public - - get flattened() - { - return this._flattened; - }, - - set flattened(flattened) - { - if (this._flattened === flattened) - return; - - this._flattened = flattened; - if (!this._flattened) { - this.mainTitle = this.name; - this.subtitle = this.secondaryName; - this._updateChildrenTitles(); - return; - } - - this.mainTitle = this.categoryName; - this.subtitle = this.name; - this._updateChildrenTitles(); - }, - - // Private - - _updateChildrenTitles: function() - { - for (var i = 0; i < this.children.length; ++i) { - if (typeof this.children[i].updateTitles === "function") - this.children[i].updateTitles(); - } - } -}; - -WebInspector.StorageTreeElement.prototype.__proto__ = WebInspector.GeneralTreeElement.prototype; diff --git a/Source/WebInspectorUI/UserInterface/StyleDetailsPanel.js b/Source/WebInspectorUI/UserInterface/StyleDetailsPanel.js deleted file mode 100644 index 41f63570c..000000000 --- a/Source/WebInspectorUI/UserInterface/StyleDetailsPanel.js +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.StyleDetailsPanel = function(className, identifier, label) -{ - this._element = document.createElement("div"); - this._element.className = className; - - // Add this offset-sections class name so the sticky headers don't overlap the navigation bar. - this.element.classList.add(WebInspector.StyleDetailsPanel.OffsetSectionsStyleClassName); - - this._navigationItem = new WebInspector.RadioButtonNavigationItem(identifier, label); - - this._nodeStyles = null; - this._visible = false; -}; - -WebInspector.StyleDetailsPanel.OffsetSectionsStyleClassName = "offset-sections"; - -WebInspector.StyleDetailsPanel.prototype = { - constructor: WebInspector.StyleDetailsPanel, - - // Public - - get element() - { - return this._element; - }, - - get navigationItem() - { - return this._navigationItem; - }, - - get nodeStyles() - { - return this._nodeStyles; - }, - - shown: function() - { - if (this._visible) - return; - - this._visible = true; - - this._refreshNodeStyles(); - }, - - hidden: function() - { - this._visible = false; - }, - - widthDidChange: function() - { - // Implemented by subclasses. - }, - - markAsNeedsRefresh: function(domNode) - { - console.assert(domNode); - if (!domNode) - return; - - if (!this._nodeStyles || this._nodeStyles.node !== domNode) { - if (this._nodeStyles) { - this._nodeStyles.removeEventListener(WebInspector.DOMNodeStyles.Event.Refreshed, this._nodeStylesRefreshed, this); - this._nodeStyles.removeEventListener(WebInspector.DOMNodeStyles.Event.NeedsRefresh, this._nodeStylesNeedsRefreshed, this); - } - - this._nodeStyles = WebInspector.cssStyleManager.stylesForNode(domNode); - - console.assert(this._nodeStyles); - if (!this._nodeStyles) - return; - - this._nodeStyles.addEventListener(WebInspector.DOMNodeStyles.Event.Refreshed, this._nodeStylesRefreshed, this); - this._nodeStyles.addEventListener(WebInspector.DOMNodeStyles.Event.NeedsRefresh, this._nodeStylesNeedsRefreshed, this); - - this._forceSignificantChange = true; - } - - if (this._visible) - this._refreshNodeStyles(); - }, - - refresh: function(significantChange) - { - // Implemented by subclasses. - }, - - // Private - - get _initialScrollOffset() - { - if (!WebInspector.cssStyleManager.canForcePseudoClasses()) - return 0; - return this.nodeStyles.node.enabledPseudoClasses.length ? 0 : WebInspector.CSSStyleDetailsSidebarPanel.NoForcedPseudoClassesScrollOffset; - }, - - _refreshNodeStyles: function() - { - if (!this._nodeStyles) - return; - this._nodeStyles.refresh(); - }, - - _refreshPreservingScrollPosition: function(significantChange) - { - significantChange = this._forceSignificantChange || significantChange || false; - delete this._forceSignificantChange; - - var previousScrollTop = this._initialScrollOffset; - - // Only remember the scroll position if the previous node is the same as this one. - if (this.element.parentNode && this._previousRefreshNodeIdentifier === this._nodeStyles.node.id) - previousScrollTop = this.element.parentNode.scrollTop; - - this.refresh(significantChange); - - this._previousRefreshNodeIdentifier = this._nodeStyles.node.id; - - if (this.element.parentNode) - this.element.parentNode.scrollTop = previousScrollTop; - }, - - _nodeStylesRefreshed: function(event) - { - if (this._visible) - this._refreshPreservingScrollPosition(event.data.significantChange); - }, - - _nodeStylesNeedsRefreshed: function(event) - { - if (this._visible) - this._refreshNodeStyles(); - } -}; - -WebInspector.StyleDetailsPanel.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/StyleRuleIcons.css b/Source/WebInspectorUI/UserInterface/StyleRuleIcons.css deleted file mode 100644 index 74a988088..000000000 --- a/Source/WebInspectorUI/UserInterface/StyleRuleIcons.css +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.author-style-rule-icon .icon { - content: url(Images/StyleRuleAuthor.svg); -} - -.user-style-rule-icon .icon { - content: url(Images/StyleRuleUser.svg); -} - -.user-agent-style-rule-icon .icon { - content: url(Images/StyleRuleUserAgent.svg); -} - -.inspector-style-rule-icon .icon { - content: url(Images/StyleRuleInspector.svg); -} - -.inherited-style-rule-icon .icon { - content: url(Images/StyleRuleInherited.svg); -} - -.inherited-element-style-rule-icon .icon { - content: url(Images/StyleRuleInheritedElement.svg); -} diff --git a/Source/WebInspectorUI/UserInterface/SyntaxHighlightingDefaultTheme.css b/Source/WebInspectorUI/UserInterface/SyntaxHighlightingDefaultTheme.css deleted file mode 100644 index a6ac8c06a..000000000 --- a/Source/WebInspectorUI/UserInterface/SyntaxHighlightingDefaultTheme.css +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -/* These styles match Xcode 4's Default theme. */ - -.cm-s-default, -.syntax-highlighted { - color: black; - - font-family: Menlo, monospace; - font-size: 11px; -} - -.cm-s-default .cm-comment, -.syntax-highlighted .css-comment, -.syntax-highlighted .javascript-comment, -.syntax-highlighted .html-comment { - color: rgb(0, 116, 0); -} - -.cm-s-default .cm-tag, -.cm-s-default .cm-atom, -.cm-s-default .cm-keyword, -.cm-s-default .cm-m-css.cm-meta, -.cm-s-default .cm-m-css.cm-property, -.cm-s-default .cm-m-css.cm-string-2, -.cm-s-default .cm-m-javascript.cm-builtin, -.syntax-highlighted .css-keyword, -.syntax-highlighted .css-property, -.syntax-highlighted .css-at-rule, -.syntax-highlighted .css-important, -.syntax-highlighted .javascript-keyword, -.syntax-highlighted .html-tag { - color: rgb(170, 13, 145); -} - -.cm-s-default .cm-number, -.cm-s-default .cm-m-css.cm-atom, -.syntax-highlighted .css-number, -.syntax-highlighted .javascript-number { - color: rgb(28, 0, 207); -} - -.cm-s-default .cm-def, -.cm-s-default .cm-bracket, -.cm-s-default .cm-operator, -.cm-s-default .cm-qualifier, -.cm-s-default .cm-variable, -.cm-s-default .cm-variable-2, -.cm-s-default .cm-variable-3, -.cm-s-default .cm-m-css.cm-tag, -.cm-s-default .cm-m-css.cm-builtin, -.syntax-highlighted .css-selector, -.syntax-highlighted .javascript-ident { - color: inherit; -} - -.cm-s-default .cm-string, -.syntax-highlighted .css-string, -.syntax-highlighted .javascript-string, -.syntax-highlighted .javascript-regexp, -.syntax-highlighted .html-attribute-value { - color: rgb(196, 26, 22); -} - -.cm-s-default .cm-m-xml.cm-meta, -.syntax-highlighted .html-doctype { - color: rgb(192, 192, 192); -} - -.cm-s-default .cm-m-xml.cm-attribute, -.syntax-highlighted .html-attribute-name { - color: rgb(131, 108, 40); -} - -.syntax-highlighted a { - color: rgb(14, 14, 255); -} - -.cm-s-default .cm-link, -.syntax-highlighted a { - text-decoration: none; - cursor: pointer; -} - -.cm-s-default .cm-link:hover, -.syntax-highlighted a:hover { - text-decoration: underline; -} - -.supports-find-banner.showing-find-banner.syntax-highlighted .search-result, -.supports-find-banner.showing-find-banner .syntax-highlighted .search-result { - background-color: rgba(235, 215, 38, 0.2); - border-bottom: 1px solid rgb(237, 202, 71); -} diff --git a/Source/WebInspectorUI/UserInterface/SyntaxHighlightingSupport.js b/Source/WebInspectorUI/UserInterface/SyntaxHighlightingSupport.js deleted file mode 100644 index 1e98e2690..000000000 --- a/Source/WebInspectorUI/UserInterface/SyntaxHighlightingSupport.js +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.SyntaxHighlightedStyleClassName = "syntax-highlighted"; - -WebInspector.syntaxHighlightStringAsDocumentFragment = function(string, mimeType, baseURL) -{ - var resultFragment = document.createDocumentFragment(); - - function appendText(text, style) - { - if (!style) { - resultFragment.appendChild(document.createTextNode(text)); - return; - } - - var span = document.createElement("span"); - span.className = "cm-" + style; - span.textContent = text; - - resultFragment.appendChild(span); - } - - mimeType = parseMIMEType(mimeType).type; - - CodeMirror.runMode(string, mimeType, appendText); - - return resultFragment; -}; diff --git a/Source/WebInspectorUI/UserInterface/Test.html b/Source/WebInspectorUI/UserInterface/Test.html new file mode 100644 index 000000000..d9e41b63d --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Test.html @@ -0,0 +1,221 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/Test/FrontendTestHarness.js b/Source/WebInspectorUI/UserInterface/Test/FrontendTestHarness.js new file mode 100644 index 000000000..5d9bb202e --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Test/FrontendTestHarness.js @@ -0,0 +1,256 @@ +/* + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +FrontendTestHarness = class FrontendTestHarness extends TestHarness +{ + constructor() + { + super(); + + this._results = []; + this._shouldResendResults = true; + + // Options that are set per-test for debugging purposes. + this.dumpActivityToSystemConsole = false; + } + + // TestHarness Overrides + + completeTest() + { + if (this.dumpActivityToSystemConsole) + InspectorFrontendHost.unbufferedLog("completeTest()"); + + // Wait for results to be resent before requesting completeTest(). Otherwise, messages will be + // queued after pending dispatches run to zero and the test page will quit before processing them. + if (this._testPageIsReloading) { + this._completeTestAfterReload = true; + return; + } + + InspectorBackend.runAfterPendingDispatches(this.evaluateInPage.bind(this, "TestPage.completeTest()")); + } + + addResult(message) + { + let stringifiedMessage = TestHarness.messageAsString(message); + + // Save the stringified message, since message may be a DOM element that won't survive reload. + this._results.push(stringifiedMessage); + + if (this.dumpActivityToSystemConsole) + InspectorFrontendHost.unbufferedLog(stringifiedMessage); + + if (!this._testPageIsReloading) + this.evaluateInPage(`TestPage.addResult(unescape("${escape(stringifiedMessage)}"))`); + } + + debugLog(message) + { + let stringifiedMessage = TestHarness.messageAsString(message); + + if (this.dumpActivityToSystemConsole) + InspectorFrontendHost.unbufferedLog(stringifiedMessage); + + this.evaluateInPage(`TestPage.debugLog(unescape("${escape(stringifiedMessage)}"));`); + } + + evaluateInPage(expression, callback) + { + // If we load this page outside of the inspector, or hit an early error when loading + // the test frontend, then defer evaluating the commands (indefinitely in the former case). + if (this._originalConsole && !window.RuntimeAgent) { + this._originalConsole["error"]("Tried to evaluate in test page, but connection not yet established:", expression); + return; + } + + RuntimeAgent.evaluate.invoke({expression, objectGroup: "test", includeCommandLineAPI: false}, callback); + } + + debug() + { + this.dumpActivityToSystemConsole = true; + InspectorBackend.dumpInspectorProtocolMessages = true; + } + + // Frontend test-specific methods. + + expectNoError(error) + { + if (error) { + InspectorTest.log("PROTOCOL ERROR: " + error); + InspectorTest.completeTest(); + throw "PROTOCOL ERROR"; + } + } + + testPageDidLoad() + { + if (this.dumpActivityToSystemConsole) + InspectorFrontendHost.unbufferedLog("testPageDidLoad()"); + + this._testPageIsReloading = false; + this._resendResults(); + + this.dispatchEventToListeners(FrontendTestHarness.Event.TestPageDidLoad); + + if (this._completeTestAfterReload) + this.completeTest(); + } + + reloadPage(shouldIgnoreCache) + { + console.assert(!this._testPageIsReloading); + console.assert(!this._testPageReloadedOnce); + + this._testPageIsReloading = true; + + return PageAgent.reload(!!shouldIgnoreCache) + .then(() => { + this._shouldResendResults = true; + this._testPageReloadedOnce = true; + + return Promise.resolve(null); + }); + } + + redirectConsoleToTestOutput() + { + // We can't use arrow functions here because of 'arguments'. It might + // be okay once rest parameters work. + let self = this; + function createProxyConsoleHandler(type) { + return function() { + self.addResult(`${type}: ` + Array.from(arguments).join(" ")); + }; + } + + function createProxyConsoleTraceHandler(){ + return function() { + try { + throw new Exception(); + } catch (e) { + // Skip the first frame which is added by this function. + let frames = e.stack.split("\n").slice(1); + let sanitizedFrames = frames.map(TestHarness.sanitizeStackFrame); + self.addResult("TRACE: " + Array.from(arguments).join(" ")); + self.addResult(sanitizedFrames.join("\n")); + } + }; + } + + let redirectedMethods = {}; + for (let key in window.console) + redirectedMethods[key] = window.console[key]; + + for (let type of ["log", "error", "info", "warn"]) + redirectedMethods[type] = createProxyConsoleHandler(type.toUpperCase()); + + redirectedMethods["trace"] = createProxyConsoleTraceHandler(); + + this._originalConsole = window.console; + window.console = redirectedMethods; + } + + reportUnhandledRejection(error) + { + let message = error.message; + let stack = error.stack; + let result = `Unhandled promise rejection in inspector page: ${message}\n`; + if (stack) { + let sanitizedStack = this.sanitizeStack(stack); + result += `\nStack Trace: ${sanitizedStack}\n`; + } + + // If the connection to the test page is not set up, then just dump to console and give up. + // Errors encountered this early can be debugged by loading Test.html in a normal browser page. + if (this._originalConsole && !this._testPageHasLoaded()) + this._originalConsole["error"](result); + + this.addResult(result); + this.completeTest(); + + // Stop default handler so we can empty InspectorBackend's message queue. + return true; + } + + reportUncaughtExceptionFromEvent(message, url, lineNumber, columnNumber) + { + // An exception thrown from a timer callback does not report a URL. + if (url === "undefined") + url = "global"; + + return this.reportUncaughtException({message, url, lineNumber, columnNumber}); + } + + reportUncaughtException({message, url, lineNumber, columnNumber, stack, code}) + { + let result; + let sanitizedURL = TestHarness.sanitizeURL(url); + let sanitizedStack = this.sanitizeStack(stack); + if (url || lineNumber || columnNumber) + result = `Uncaught exception in Inspector page: ${message} [${sanitizedURL}:${lineNumber}:${columnNumber}]\n`; + else + result = `Uncaught exception in Inspector page: ${message}\n`; + + if (stack) + result += `\nStack Trace:\n${sanitizedStack}\n`; + if (code) + result += `\nEvaluated Code:\n${code}`; + + // If the connection to the test page is not set up, then just dump to console and give up. + // Errors encountered this early can be debugged by loading Test.html in a normal browser page. + if (this._originalConsole && !this._testPageHasLoaded()) + this._originalConsole["error"](result); + + this.addResult(result); + this.completeTest(); + // Stop default handler so we can empty InspectorBackend's message queue. + return true; + } + + // Private + + _testPageHasLoaded() + { + return self._shouldResendResults; + } + + _resendResults() + { + console.assert(this._shouldResendResults); + this._shouldResendResults = false; + + if (this.dumpActivityToSystemConsole) + InspectorFrontendHost.unbufferedLog("_resendResults()"); + + for (let result of this._results) + this.evaluateInPage(`TestPage.addResult(unescape("${escape(result)}"))`); + } +}; + +FrontendTestHarness.Event = { + TestPageDidLoad: "frontend-test-test-page-did-load" +}; diff --git a/Source/WebInspectorUI/UserInterface/Test/InspectorProtocol.js b/Source/WebInspectorUI/UserInterface/Test/InspectorProtocol.js new file mode 100644 index 000000000..60ec624f1 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Test/InspectorProtocol.js @@ -0,0 +1,182 @@ +/* + * Copyright (C) 2012 Samsung Electronics. All rights reserved. + * Copyright (C) 2014, 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +InspectorProtocol = {}; +InspectorProtocol._dispatchTable = []; +InspectorProtocol._placeholderRequestIds = []; +InspectorProtocol._requestId = -1; +InspectorProtocol.eventHandler = {}; + +InspectorProtocol.sendCommand = function(methodOrObject, params, handler) +{ + // Allow new-style arguments object, as in awaitCommand. + let method = methodOrObject; + if (typeof methodOrObject === "object") + ({method, params, handler} = methodOrObject); + else if (!params) + params = {}; + + this._dispatchTable[++this._requestId] = handler; + let messageObject = {method, params, id: this._requestId}; + this._sendMessage(messageObject); + + return this._requestId; +}; + +InspectorProtocol.awaitCommand = function(args) +{ + let {method, params} = args; + let messageObject = {method, params, id: ++this._requestId}; + + return this.awaitMessage(messageObject); +}; + +InspectorProtocol.awaitMessage = function(messageObject) +{ + // Send a raw message to the backend. Mostly used to test the backend's error handling. + return new Promise((resolve, reject) => { + let requestId = messageObject.id; + + // If the caller did not provide an id, then make one up so that the response + // can be used to settle a promise. + if (typeof requestId !== "number") { + requestId = ++this._requestId; + this._placeholderRequestIds.push(requestId); + } + + this._dispatchTable[requestId] = {resolve, reject}; + this._sendMessage(messageObject); + }); +}; + +InspectorProtocol.awaitEvent = function(args) +{ + let event = args.event; + if (typeof event !== "string") + throw new Error("Event must be a string."); + + return new Promise((resolve, reject) => { + InspectorProtocol.eventHandler[event] = function(message) { + InspectorProtocol.eventHandler[event] = undefined; + resolve(message); + }; + }); +}; + +InspectorProtocol._sendMessage = function(messageObject) +{ + let messageString = typeof messageObject !== "string" ? JSON.stringify(messageObject) : messageObject; + + if (ProtocolTest.dumpInspectorProtocolMessages) + InspectorFrontendHost.unbufferedLog(`frontend: ${messageString}`); + + InspectorFrontendHost.sendMessageToBackend(messageString); +}; + +InspectorProtocol.addEventListener = function(eventTypeOrObject, listener) +{ + let event = eventTypeOrObject; + if (typeof eventTypeOrObject === "object") + ({event, listener} = eventTypeOrObject); + + if (typeof event !== "string") + throw new Error("Event name must be a string."); + + if (typeof listener !== "function") + throw new Error("Event listener must be callable."); + + // Convert to an array of listeners. + let listeners = InspectorProtocol.eventHandler[event]; + if (!listeners) + listeners = InspectorProtocol.eventHandler[event] = []; + else if (typeof listeners === "function") + listeners = InspectorProtocol.eventHandler[event] = [listeners]; + + // Prevent registering multiple times. + if (listeners.includes(listener)) + throw new Error("Cannot register the same listener more than once."); + + listeners.push(listener); +}; + +InspectorProtocol.checkForError = function(responseObject) +{ + if (responseObject.error) { + ProtocolTest.log("PROTOCOL ERROR: " + JSON.stringify(responseObject.error)); + ProtocolTest.completeTest(); + throw "PROTOCOL ERROR"; + } +}; + +InspectorProtocol.dispatchMessageFromBackend = function(messageObject) +{ + // This matches the debug dumping in InspectorBackend, which is bypassed + // by InspectorProtocol. Return messages should be dumped by InspectorBackend. + if (ProtocolTest.dumpInspectorProtocolMessages) + InspectorFrontendHost.unbufferedLog("backend: " + JSON.stringify(messageObject)); + + // If the message has an id, then it is a reply to a command. + let messageId = messageObject.id; + + // If the id is 'null', then it may be an error response. + if (messageId === null) + messageId = InspectorProtocol._placeholderRequestIds.shift(); + + // If we could figure out a requestId, then dispatch the message. + if (typeof messageId === "number") { + let handler = InspectorProtocol._dispatchTable[messageId]; + if (!handler) + return; + + if (typeof handler === "function") + handler(messageObject); + else if (typeof handler === "object") { + let {resolve, reject} = handler; + if ("error" in messageObject) + reject(messageObject.error); + else + resolve(messageObject.result); + } + } else { + // Otherwise, it is an event. + let eventName = messageObject["method"]; + let handler = InspectorProtocol.eventHandler[eventName]; + if (!handler) + return; + + if (typeof handler === "function") + handler(messageObject); + else if (handler instanceof Array) { + handler.map((listener) => { listener.call(null, messageObject); }); + } else if (typeof handler === "object") { + let {resolve, reject} = handler; + if ("error" in messageObject) + reject(messageObject.error); + else + resolve(messageObject.result); + } + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Test/ProtocolTestHarness.js b/Source/WebInspectorUI/UserInterface/Test/ProtocolTestHarness.js new file mode 100644 index 000000000..d0ef614b6 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Test/ProtocolTestHarness.js @@ -0,0 +1,78 @@ +/* + * Copyright (C) 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +ProtocolTestHarness = class ProtocolTestHarness extends TestHarness +{ + // TestHarness Overrides + + completeTest() + { + if (this.dumpActivityToSystemConsole) + InspectorFrontendHost.unbufferedLog("completeTest()"); + + this.evaluateInPage("TestPage.closeTest();"); + } + + addResult(message) + { + let stringifiedMessage = TestHarness.messageAsString(message); + + if (this.dumpActivityToSystemConsole) + InspectorFrontendHost.unbufferedLog(stringifiedMessage); + + // Unfortunately, every string argument must be escaped because tests are not consistent + // with respect to escaping with single or double quotes. Some exceptions use single quotes. + this.evaluateInPage(`TestPage.log(unescape("${escape(stringifiedMessage)}"));`); + } + + debugLog(message) + { + let stringifiedMessage = TestHarness.messageAsString(message); + + if (this.dumpActivityToSystemConsole) + InspectorFrontendHost.unbufferedLog(stringifiedMessage); + + this.evaluateInPage(`TestPage.debugLog(unescape("${escape(stringifiedMessage)}"));`); + } + + evaluateInPage(expression, callback) + { + let args = { + method: "Runtime.evaluate", + params: {expression} + }; + + if (typeof callback === "function") + InspectorProtocol.sendCommand(args, callback); + else + return InspectorProtocol.awaitCommand(args); + } + + debug() + { + this.dumpActivityToSystemConsole = true; + this.dumpInspectorProtocolMessages = true; + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Test/Test.js b/Source/WebInspectorUI/UserInterface/Test/Test.js new file mode 100644 index 000000000..f59bf7304 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Test/Test.js @@ -0,0 +1,120 @@ +/* + * Copyright (C) 2013-2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.DebuggableType = { + Web: "web", + JavaScript: "javascript" +}; + +WebInspector.loaded = function() +{ + this.debuggableType = WebInspector.DebuggableType.Web; + this.hasExtraDomains = false; + + // Register observers for events from the InspectorBackend. + // The initialization order should match the same in Main.js. + InspectorBackend.registerInspectorDispatcher(new WebInspector.InspectorObserver); + InspectorBackend.registerPageDispatcher(new WebInspector.PageObserver); + InspectorBackend.registerConsoleDispatcher(new WebInspector.ConsoleObserver); + InspectorBackend.registerDOMDispatcher(new WebInspector.DOMObserver); + InspectorBackend.registerNetworkDispatcher(new WebInspector.NetworkObserver); + InspectorBackend.registerDebuggerDispatcher(new WebInspector.DebuggerObserver); + InspectorBackend.registerHeapDispatcher(new WebInspector.HeapObserver); + InspectorBackend.registerDOMStorageDispatcher(new WebInspector.DOMStorageObserver); + InspectorBackend.registerTimelineDispatcher(new WebInspector.TimelineObserver); + InspectorBackend.registerCSSDispatcher(new WebInspector.CSSObserver); + InspectorBackend.registerRuntimeDispatcher(new WebInspector.RuntimeObserver); + InspectorBackend.registerWorkerDispatcher(new WebInspector.WorkerObserver); + if (InspectorBackend.registerReplayDispatcher) + InspectorBackend.registerReplayDispatcher(new WebInspector.ReplayObserver); + + WebInspector.mainTarget = new WebInspector.MainTarget; + + // Instantiate controllers used by tests. + this.targetManager = new WebInspector.TargetManager; + this.frameResourceManager = new WebInspector.FrameResourceManager; + this.storageManager = new WebInspector.StorageManager; + this.domTreeManager = new WebInspector.DOMTreeManager; + this.cssStyleManager = new WebInspector.CSSStyleManager; + this.logManager = new WebInspector.LogManager; + this.issueManager = new WebInspector.IssueManager; + this.runtimeManager = new WebInspector.RuntimeManager; + this.heapManager = new WebInspector.HeapManager; + this.memoryManager = new WebInspector.MemoryManager; + this.timelineManager = new WebInspector.TimelineManager; + this.debuggerManager = new WebInspector.DebuggerManager; + this.probeManager = new WebInspector.ProbeManager; + this.workerManager = new WebInspector.WorkerManager; + this.replayManager = new WebInspector.ReplayManager; + + document.addEventListener("DOMContentLoaded", this.contentLoaded); + + // Enable agents. + InspectorAgent.enable(); + ConsoleAgent.enable(); + + // Perform one-time tasks. + WebInspector.CSSCompletions.requestCSSCompletions(); + + // Global settings. + this.showShadowDOMSetting = new WebInspector.Setting("show-shadow-dom", true); +}; + +WebInspector.contentLoaded = function() +{ + // Signal that the frontend is now ready to receive messages. + InspectorFrontendAPI.loadCompleted(); + + // Tell the InspectorFrontendHost we loaded, which causes the window to display + // and pending InspectorFrontendAPI commands to be sent. + InspectorFrontendHost.loaded(); +}; + +Object.defineProperty(WebInspector, "targets", +{ + get() { return this.targetManager.targets; } +}); + +WebInspector.assumingMainTarget = () => WebInspector.mainTarget; + +WebInspector.isDebugUIEnabled = () => false; + +WebInspector.UIString = (string) => string; + +WebInspector.indentString = () => " "; + +// Add stubs that are called by the frontend API. +WebInspector.updateDockedState = () => {}; +WebInspector.updateDockingAvailability = () => {}; +WebInspector.updateVisibilityState = () => {}; + +window.InspectorTest = new FrontendTestHarness(); + +InspectorTest.redirectConsoleToTestOutput(); + +WebInspector.reportInternalError = (e) => { console.error(e); }; + +window.reportUnhandledRejection = InspectorTest.reportUnhandledRejection.bind(InspectorTest); +window.onerror = InspectorTest.reportUncaughtExceptionFromEvent.bind(InspectorTest); diff --git a/Source/WebInspectorUI/UserInterface/Test/TestHarness.js b/Source/WebInspectorUI/UserInterface/Test/TestHarness.js new file mode 100644 index 000000000..53bee4a4b --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Test/TestHarness.js @@ -0,0 +1,374 @@ +/* + * Copyright (C) 2015, 2016 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +TestHarness = class TestHarness extends WebInspector.Object +{ + constructor() + { + super(); + + this._logCount = 0; + this._failureObjects = new Map; + this._failureObjectIdentifier = 1; + + // Options that are set per-test for debugging purposes. + this.forceDebugLogging = false; + + // Options that are set per-test to ensure deterministic output. + this.suppressStackTraces = false; + } + + completeTest() + { + throw new Error("Must be implemented by subclasses."); + } + + addResult() + { + throw new Error("Must be implemented by subclasses."); + } + + debugLog() + { + throw new Error("Must be implemented by subclasses."); + } + + evaluateInPage(string, callback) + { + throw new Error("Must be implemented by subclasses."); + } + + debug() + { + throw new Error("Must be implemented by subclasses."); + } + + createAsyncSuite(name) + { + return new AsyncTestSuite(this, name); + } + + createSyncSuite(name) + { + return new SyncTestSuite(this, name); + } + + get logCount() + { + return this._logCount; + } + + log(message) + { + ++this._logCount; + + if (this.forceDebugLogging) + this.debugLog(message); + else + this.addResult(message); + } + + assert(condition, message) + { + if (condition) + return; + + let stringifiedMessage = TestHarness.messageAsString(message); + this.log("ASSERT: " + stringifiedMessage); + } + + expectThat(actual, message) + { + this._expect(TestHarness.ExpectationType.True, !!actual, message, actual); + } + + expectFalse(actual, message) + { + this._expect(TestHarness.ExpectationType.False, !actual, message, actual); + } + + expectNull(actual, message) + { + this._expect(TestHarness.ExpectationType.Null, actual === null, message, actual, null); + } + + expectNotNull(actual, message) + { + this._expect(TestHarness.ExpectationType.NotNull, actual !== null, message, actual); + } + + expectEqual(actual, expected, message) + { + this._expect(TestHarness.ExpectationType.Equal, expected === actual, message, actual, expected); + } + + expectNotEqual(actual, expected, message) + { + this._expect(TestHarness.ExpectationType.NotEqual, expected !== actual, message, actual, expected); + } + + expectShallowEqual(actual, expected, message) + { + this._expect(TestHarness.ExpectationType.ShallowEqual, Object.shallowEqual(actual, expected), message, actual, expected); + } + + expectNotShallowEqual(actual, expected, message) + { + this._expect(TestHarness.ExpectationType.NotShallowEqual, !Object.shallowEqual(actual, expected), message, actual, expected); + } + + expectEqualWithAccuracy(actual, expected, accuracy, message) + { + console.assert(typeof expected === "number"); + console.assert(typeof actual === "number"); + + this._expect(TestHarness.ExpectationType.EqualWithAccuracy, Math.abs(expected - actual) <= accuracy, message, actual, expected, accuracy); + } + + expectLessThan(actual, expected, message) + { + this._expect(TestHarness.ExpectationType.LessThan, actual < expected, message, actual, expected); + } + + expectLessThanOrEqual(actual, expected, message) + { + this._expect(TestHarness.ExpectationType.LessThanOrEqual, actual <= expected, message, actual, expected); + } + + expectGreaterThan(actual, expected, message) + { + this._expect(TestHarness.ExpectationType.GreaterThan, actual > expected, message, actual, expected); + } + + expectGreaterThanOrEqual(actual, expected, message) + { + this._expect(TestHarness.ExpectationType.GreaterThanOrEqual, actual >= expected, message, actual, expected); + } + + pass(message) + { + let stringifiedMessage = TestHarness.messageAsString(message); + this.log("PASS: " + stringifiedMessage); + } + + fail(message) + { + let stringifiedMessage = TestHarness.messageAsString(message); + this.log("FAIL: " + stringifiedMessage); + } + + // Protected + + static messageAsString(message) + { + if (message instanceof Element) + return message.textContent; + + return (typeof message !== "string") ? JSON.stringify(message) : message; + } + + static sanitizeURL(url) + { + if (!url) + return "(unknown)"; + + let lastPathSeparator = Math.max(url.lastIndexOf("/"), url.lastIndexOf("\\")); + let location = (lastPathSeparator > 0) ? url.substr(lastPathSeparator + 1) : url; + if (!location.length) + location = "(unknown)"; + + // Clean up the location so it is bracketed or in parenthesis. + if (url.indexOf("[native code]") !== -1) + location = "[native code]"; + + return location; + } + + static sanitizeStackFrame(frame, i) + { + // Most frames are of the form "functionName@file:///foo/bar/File.js:345". + // But, some frames do not have a functionName. Get rid of the file path. + let nameAndURLSeparator = frame.indexOf("@"); + let frameName = (nameAndURLSeparator > 0) ? frame.substr(0, nameAndURLSeparator) : "(anonymous)"; + + let lastPathSeparator = Math.max(frame.lastIndexOf("/"), frame.lastIndexOf("\\")); + let frameLocation = (lastPathSeparator > 0) ? frame.substr(lastPathSeparator + 1) : frame; + if (!frameLocation.length) + frameLocation = "unknown"; + + // Clean up the location so it is bracketed or in parenthesis. + if (frame.indexOf("[native code]") !== -1) + frameLocation = "[native code]"; + else + frameLocation = "(" + frameLocation + ")"; + + return `#${i}: ${frameName} ${frameLocation}`; + } + + sanitizeStack(stack) + { + if (this.suppressStackTraces) + return "(suppressed)"; + + if (!stack || typeof stack !== "string") + return "(unknown)"; + + return stack.split("\n").map(TestHarness.sanitizeStackFrame).join("\n"); + } + + // Private + + _expect(type, condition, message, ...values) + { + console.assert(values.length > 0, "Should have an 'actual' value."); + + if (!message || !condition) { + values = values.map(this._expectationValueAsString.bind(this)); + message = message || this._expectationMessageFormat(type).format(...values); + } + + if (condition) { + this.pass(message); + return; + } + + message += "\n Expected: " + this._expectedValueFormat(type).format(...values.slice(1)); + message += "\n Actual: " + values[0]; + + this.fail(message); + } + + _expectationValueAsString(value) + { + let instanceIdentifier = (object) => { + let id = this._failureObjects.get(object); + if (!id) { + id = this._failureObjectIdentifier++; + this._failureObjects.set(object, id); + } + return "#" + id; + }; + + const maximumValueStringLength = 200; + const defaultValueString = String(new Object); // [object Object] + + // Special case for numbers, since JSON.stringify converts Infinity and NaN to null. + if (typeof value === "number") + return value; + + try { + let valueString = JSON.stringify(value); + if (valueString.length <= maximumValueStringLength) + return valueString; + } catch (e) {} + + try { + let valueString = String(value); + if (valueString === defaultValueString && value.constructor && value.constructor.name !== "Object") + return value.constructor.name + " instance " + instanceIdentifier(value); + return valueString; + } catch (e) { + return defaultValueString; + } + } + + _expectationMessageFormat(type) + { + switch (type) { + case TestHarness.ExpectationType.True: + return "expectThat(%s)"; + case TestHarness.ExpectationType.False: + return "expectFalse(%s)"; + case TestHarness.ExpectationType.Null: + return "expectNull(%s)"; + case TestHarness.ExpectationType.NotNull: + return "expectNotNull(%s)"; + case TestHarness.ExpectationType.Equal: + return "expectEqual(%s, %s)"; + case TestHarness.ExpectationType.NotEqual: + return "expectNotEqual(%s, %s)"; + case TestHarness.ExpectationType.ShallowEqual: + return "expectShallowEqual(%s, %s)"; + case TestHarness.ExpectationType.NotShallowEqual: + return "expectNotShallowEqual(%s, %s)"; + case TestHarness.ExpectationType.EqualWithAccuracy: + return "expectEqualWithAccuracy(%s, %s, %s)"; + case TestHarness.ExpectationType.LessThan: + return "expectLessThan(%s, %s)"; + case TestHarness.ExpectationType.LessThanOrEqual: + return "expectLessThanOrEqual(%s, %s)"; + case TestHarness.ExpectationType.GreaterThan: + return "expectGreaterThan(%s, %s)"; + case TestHarness.ExpectationType.GreaterThanOrEqual: + return "expectGreaterThanOrEqual(%s, %s)"; + default: + console.error("Unknown TestHarness.ExpectationType type: " + type); + return null; + } + } + + _expectedValueFormat(type) + { + switch (type) { + case TestHarness.ExpectationType.True: + return "truthy"; + case TestHarness.ExpectationType.False: + return "falsey"; + case TestHarness.ExpectationType.NotNull: + return "not null"; + case TestHarness.ExpectationType.NotEqual: + case TestHarness.ExpectationType.NotShallowEqual: + return "not %s"; + case TestHarness.ExpectationType.EqualWithAccuracy: + return "%s +/- %s"; + case TestHarness.ExpectationType.LessThan: + return "less than %s"; + case TestHarness.ExpectationType.LessThanOrEqual: + return "less than or equal to %s"; + case TestHarness.ExpectationType.GreaterThan: + return "greater than %s"; + case TestHarness.ExpectationType.GreaterThanOrEqual: + return "greater than or equal to %s"; + default: + return "%s"; + } + } +}; + +TestHarness.ExpectationType = { + True: Symbol("expect-true"), + False: Symbol("expect-false"), + Null: Symbol("expect-null"), + NotNull: Symbol("expect-not-null"), + Equal: Symbol("expect-equal"), + NotEqual: Symbol("expect-not-equal"), + ShallowEqual: Symbol("expect-shallow-equal"), + NotShallowEqual: Symbol("expect-not-shallow-equal"), + EqualWithAccuracy: Symbol("expect-equal-with-accuracy"), + LessThan: Symbol("expect-less-than"), + LessThanOrEqual: Symbol("expect-less-than-or-equal"), + GreaterThan: Symbol("expect-greater-than"), + GreaterThanOrEqual: Symbol("expect-greater-than-or-equal"), +}; diff --git a/Source/WebInspectorUI/UserInterface/Test/TestStub.js b/Source/WebInspectorUI/UserInterface/Test/TestStub.js new file mode 100644 index 000000000..cda7c7ac6 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Test/TestStub.js @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2012 Samsung Electronics. All rights reserved. + * Copyright (C) 2014, 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +InspectorFrontendAPI = {}; +InspectorFrontendAPI.dispatchMessageAsync = InspectorProtocol.dispatchMessageFromBackend; + +window.ProtocolTest = new ProtocolTestHarness(); + +window.addEventListener("message", (event) => { + try { + eval(event.data); + } catch (e) { + alert(e.stack); + ProtocolTest.completeTest(); + throw e; + } +}); diff --git a/Source/WebInspectorUI/UserInterface/Test/TestSuite.js b/Source/WebInspectorUI/UserInterface/Test/TestSuite.js new file mode 100644 index 000000000..aacd313b7 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Test/TestSuite.js @@ -0,0 +1,251 @@ +/* + * Copyright (C) 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +TestSuite = class TestSuite extends WebInspector.Object +{ + constructor(harness, name) { + if (!(harness instanceof TestHarness)) + throw new Error("Must pass the test's harness as the first argument."); + + if (typeof name !== "string" || !name.trim().length) + throw new Error("Tried to create TestSuite without string suite name."); + + super(); + + this.name = name; + this._harness = harness; + + this.testcases = []; + this.runCount = 0; + this.failCount = 0; + } + + // Use this if the test file only has one suite, and no handling + // of the value returned by runTestCases() is needed. + runTestCasesAndFinish() + { + throw new Error("Must be implemented by subclasses."); + } + + runTestCases() + { + throw new Error("Must be implemented by subclasses."); + } + + get passCount() + { + return this.runCount - this.failCount; + } + + get skipCount() + { + if (this.failCount) + return this.testcases.length - this.runCount; + else + return 0; + } + + addTestCase(testcase) + { + if (!testcase || !(testcase instanceof Object)) + throw new Error("Tried to add non-object test case."); + + if (typeof testcase.name !== "string" || !testcase.name.trim().length) + throw new Error("Tried to add test case without a name."); + + if (typeof testcase.test !== "function") + throw new Error("Tried to add test case without `test` function."); + + if (testcase.setup && typeof testcase.setup !== "function") + throw new Error("Tried to add test case with invalid `setup` parameter (must be a function)."); + + if (testcase.teardown && typeof testcase.teardown !== "function") + throw new Error("Tried to add test case with invalid `teardown` parameter (must be a function)."); + + this.testcases.push(testcase); + } + + // Protected + + logThrownObject(e) + { + let message = e; + let stack = "(unknown)"; + if (e instanceof Error) { + message = e.message; + if (e.stack) + stack = e.stack; + } + + if (typeof message !== "string") + message = JSON.stringify(message); + + let sanitizedStack = this._harness.sanitizeStack(stack); + + let result = `!! EXCEPTION: ${message}`; + if (stack) + result += `\nStack Trace: ${sanitizedStack}`; + + this._harness.log(result); + } +}; + +AsyncTestSuite = class AsyncTestSuite extends TestSuite +{ + runTestCasesAndFinish() + { + let finish = () => { this._harness.completeTest(); }; + + this.runTestCases() + .then(finish) + .catch(finish); + } + + runTestCases() + { + if (!this.testcases.length) + throw new Error("Tried to call runTestCases() for suite with no test cases"); + if (this._startedRunning) + throw new Error("Tried to call runTestCases() more than once."); + + this._startedRunning = true; + + this._harness.log(""); + this._harness.log(`== Running test suite: ${this.name}`); + + // Avoid adding newlines if nothing was logged. + let priorLogCount = this._harness.logCount; + let result = this.testcases.reduce((chain, testcase, i) => { + if (testcase.setup) { + chain = chain.then(() => { + this._harness.log("-- Running test setup."); + return new Promise(testcase.setup); + }); + } + + chain = chain.then(() => { + if (i > 0 && priorLogCount + 1 < this._harness.logCount) + this._harness.log(""); + + priorLogCount = this._harness.logCount; + this._harness.log(`-- Running test case: ${testcase.name}`); + this.runCount++; + return new Promise(testcase.test); + }); + + if (testcase.teardown) { + chain = chain.then(() => { + this._harness.log("-- Running test teardown."); + return new Promise(testcase.teardown); + }); + } + return chain; + }, Promise.resolve()); + + return result.catch((e) => { + this.failCount++; + this.logThrownObject(e); + + throw e; // Reject this promise by re-throwing the error. + }); + } +}; + +SyncTestSuite = class SyncTestSuite extends TestSuite +{ + runTestCasesAndFinish() + { + this.runTestCases(); + this._harness.completeTest(); + } + + runTestCases() + { + if (!this.testcases.length) + throw new Error("Tried to call runTestCases() for suite with no test cases"); + if (this._startedRunning) + throw new Error("Tried to call runTestCases() more than once."); + + this._startedRunning = true; + + this._harness.log(""); + this._harness.log(`== Running test suite: ${this.name}`); + + let priorLogCount = this._harness.logCount; + for (let i = 0; i < this.testcases.length; i++) { + let testcase = this.testcases[i]; + if (i > 0 && priorLogCount + 1 < this._harness.logCount) + this._harness.log(""); + + priorLogCount = this._harness.logCount; + + // Run the setup action, if one was provided. + if (testcase.setup) { + this._harness.log("-- Running test setup."); + try { + let result = testcase.setup.call(null); + if (result === false) { + this._harness.log("!! SETUP FAILED"); + return false; + } + } catch (e) { + this.logThrownObject(e); + return false; + } + } + + this._harness.log("-- Running test case: " + testcase.name); + this.runCount++; + try { + let result = testcase.test.call(null); + if (result === false) { + this.failCount++; + return false; + } + } catch (e) { + this.failCount++; + this.logThrownObject(e); + return false; + } + + // Run the teardown action, if one was provided. + if (testcase.teardown) { + this._harness.log("-- Running test teardown."); + try { + let result = testcase.teardown.call(null); + if (result === false) { + this._harness.log("!! TEARDOWN FAILED"); + return false; + } + } catch (e) { + this.logThrownObject(e); + return false; + } + } + } + + return true; + } +}; diff --git a/Source/WebInspectorUI/UserInterface/TestStub.html b/Source/WebInspectorUI/UserInterface/TestStub.html new file mode 100644 index 000000000..0cd419dac --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/TestStub.html @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/WebInspectorUI/UserInterface/TextContentView.css b/Source/WebInspectorUI/UserInterface/TextContentView.css deleted file mode 100644 index e03aa2433..000000000 --- a/Source/WebInspectorUI/UserInterface/TextContentView.css +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.content-view.text > .text-editor { - position: absolute; - top: 0; - left: 0; - right: 0; - bottom: 0; -} diff --git a/Source/WebInspectorUI/UserInterface/TextContentView.js b/Source/WebInspectorUI/UserInterface/TextContentView.js deleted file mode 100644 index c4d28b606..000000000 --- a/Source/WebInspectorUI/UserInterface/TextContentView.js +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.TextContentView = function(string, mimeType) -{ - WebInspector.ContentView.call(this, string); - - this.element.classList.add(WebInspector.TextContentView.StyleClassName); - - this._textEditor = new WebInspector.TextEditor; - this._textEditor.addEventListener(WebInspector.TextEditor.Event.NumberOfSearchResultsDidChange, this._numberOfSearchResultsDidChange, this); - this._textEditor.addEventListener(WebInspector.TextEditor.Event.FormattingDidChange, this._textEditorFormattingDidChange, this); - - this.element.appendChild(this._textEditor.element); - - this._textEditor.readOnly = true; - this._textEditor.mimeType = mimeType; - this._textEditor.string = string; - - var toolTip = WebInspector.UIString("Pretty print"); - var activatedToolTip = WebInspector.UIString("Original formatting"); - this._prettyPrintButtonNavigationItem = new WebInspector.ActivateButtonNavigationItem("pretty-print", toolTip, activatedToolTip, "Images/NavigationItemCurleyBraces.svg", 16, 16); - this._prettyPrintButtonNavigationItem.addEventListener(WebInspector.ButtonNavigationItem.Event.Clicked, this._togglePrettyPrint, this); - this._prettyPrintButtonNavigationItem.enabled = this._textEditor.canBeFormatted(); -}; - -WebInspector.TextContentView.StyleClassName = "text"; - -WebInspector.TextContentView.prototype = { - constructor: WebInspector.TextContentView, - - // Public - - get textEditor() - { - return this._textEditor; - }, - - get navigationItems() - { - return [this._prettyPrintButtonNavigationItem]; - }, - - revealPosition: function(position, textRangeToSelect, forceUnformatted) - { - this._textEditor.revealPosition(position, textRangeToSelect, forceUnformatted); - }, - - shown: function() - { - WebInspector.ResourceContentView.prototype.shown.call(this); - - this._textEditor.shown(); - }, - - hidden: function() - { - WebInspector.ResourceContentView.prototype.hidden.call(this); - - this._textEditor.hidden(); - }, - - closed: function() - { - WebInspector.ContentView.prototype.closed.call(this); - - this._textEditor.close(); - }, - - get supportsSave() - { - return true; - }, - - get saveData() - { - var url = "web-inspector:///" + encodeURI(WebInspector.UIString("Untitled")) + ".txt"; - return {url: url, content: this._textEditor.string, forceSaveAs: true}; - }, - - get supportsSearch() - { - return true; - }, - - get numberOfSearchResults() - { - return this._textEditor.numberOfSearchResults; - }, - - get hasPerformedSearch() - { - return this._textEditor.currentSearchQuery !== null; - }, - - set automaticallyRevealFirstSearchResult(reveal) - { - this._textEditor.automaticallyRevealFirstSearchResult = reveal; - }, - - performSearch: function(query) - { - this._textEditor.performSearch(query); - }, - - searchCleared: function() - { - this._textEditor.searchCleared(); - }, - - searchQueryWithSelection: function() - { - return this._textEditor.searchQueryWithSelection(); - }, - - revealPreviousSearchResult: function(changeFocus) - { - this._textEditor.revealPreviousSearchResult(changeFocus); - }, - - revealNextSearchResult: function(changeFocus) - { - this._textEditor.revealNextSearchResult(changeFocus); - }, - - updateLayout: function() - { - this._textEditor.updateLayout(); - }, - - // Private - - _togglePrettyPrint: function(event) - { - var activated = !this._prettyPrintButtonNavigationItem.activated; - this._textEditor.formatted = activated; - }, - - _textEditorFormattingDidChange: function(event) - { - this._prettyPrintButtonNavigationItem.activated = this._textEditor.formatted; - }, - - _numberOfSearchResultsDidChange: function(event) - { - this.dispatchEventToListeners(WebInspector.ContentView.Event.NumberOfSearchResultsDidChange); - } -}; - -WebInspector.TextContentView.prototype.__proto__ = WebInspector.ContentView.prototype; diff --git a/Source/WebInspectorUI/UserInterface/TextEditor.css b/Source/WebInspectorUI/UserInterface/TextEditor.css deleted file mode 100644 index a65aea306..000000000 --- a/Source/WebInspectorUI/UserInterface/TextEditor.css +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.text-editor { - position: relative; - - overflow: hidden; -} - -.text-editor > .CodeMirror { - position: absolute; - top: 0; - left: 0; - bottom: 0; - right: 0; - height: auto; -} - -.text-editor > .CodeMirror .has-breakpoint:not(.breakpoint-disabled) .CodeMirror-linenumber { - color: white; -} - -.text-editor > .CodeMirror .has-breakpoint.multiple-breakpoints .CodeMirror-linenumber { - color: transparent; -} - -.text-editor > .CodeMirror .has-breakpoint .CodeMirror-linenumber::before { - position: absolute; - top: 0; - left: 0; - bottom: 0; - right: -7px; - - content: ""; - - z-index: -2; - - border-image-source: -webkit-image-set(url(Images/BreakpointInactive.png) 1x, url(Images/BreakpointInactive@2x.png) 2x); - border-image-slice: 3 7 3 3 fill; - border-width: 3px 7px 3px 3px; -} - -.text-editor > .CodeMirror .breakpoint-resolved .CodeMirror-linenumber::before { - border-image-source: -webkit-image-set(url(Images/Breakpoint.png) 1x, url(Images/Breakpoint@2x.png) 2x); -} - -.text-editor > .CodeMirror .breakpoint-auto-continue:not(.breakpoint-disabled) .CodeMirror-linenumber::before { - opacity: 0.6; -} - -.text-editor > .CodeMirror .breakpoint-disabled .CodeMirror-linenumber::before { - opacity: 0.35; -} - -.text-editor > .CodeMirror .has-breakpoint.multiple-breakpoints .CodeMirror-linenumber::before { - content: "•••"; - color: white; - line-height: 6px; - text-align: center; - text-indent: -1px; -} - -.text-editor > .CodeMirror .execution-line .CodeMirror-linenumber::after { - position: absolute; - top: 0; - bottom: 0; - right: -9px; - width: 9px; - - content: ""; - - z-index: -1; - - background-image: -webkit-image-set(url(Images/InstructionPointer.png) 1x, url(Images/InstructionPointer@2x.png) 2x); - background-size: 9px 100%; - background-repeat: no-repeat; -} - -.text-editor > .CodeMirror .execution-line { - background-color: rgb(217, 234, 208) !important; -} - -.text-editor .bouncy-highlight { - position: absolute; - z-index: 100; - - box-shadow: inset rgb(250, 232, 140) 0 -1px 0, rgba(211, 197, 96, 1) 0 1px 1px, rgba(0, 0, 0, 0.33) 0 1px 2px 1px; - text-shadow: white 0 0 2px; - - background: -webkit-linear-gradient(top, rgb(250, 237, 108), rgb(242, 220, 100)); - border-radius: 7px; - - padding: 2px 4px; - margin-top: -2px; - margin-left: -4px; - - -webkit-user-select: none; - pointer-events: none; - - -webkit-animation-name: text-editor-bouncy; - -webkit-animation-duration: 750ms; - -webkit-animation-timing-function: ease-in-out; - - opacity: 0; -} - -@-webkit-keyframes text-editor-bouncy { - 0% { - -webkit-transform: scale(1); - opacity: 1; - } - - 12.5% { - -webkit-transform: scale(1.25); - } - - 25% { - -webkit-transform: scale(1); - } - - 62.5% { - opacity: 1; - } - - 100% { - opacity: 0; - } -} - -.text-editor > .CodeMirror .highlighted { - -webkit-animation: "text-editor-highlight-fadeout" 2s; -} - -@-webkit-keyframes text-editor-highlight-fadeout { - from { background-color: highlight; } -} - -.text-editor > .CodeMirror .hovered-expression-highlight { - -webkit-animation: "text-editor-hovered-expression-highlight-fadeout" 2s; - background-color: rgba(0, 0, 0, 0.1); -} - -@-webkit-keyframes text-editor-hovered-expression-highlight-fadeout { - from { background-color: highlight; } - to { background-color: rgba(0, 0, 0, 0.1); } -} diff --git a/Source/WebInspectorUI/UserInterface/TextEditor.js b/Source/WebInspectorUI/UserInterface/TextEditor.js deleted file mode 100644 index 0e92eb108..000000000 --- a/Source/WebInspectorUI/UserInterface/TextEditor.js +++ /dev/null @@ -1,1326 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.TextEditor = function(element, mimeType, delegate) -{ - WebInspector.Object.call(this); - - var text = (element ? element.textContent : ""); - this._element = element || document.createElement("div"); - this._element.classList.add(WebInspector.TextEditor.StyleClassName); - this._element.classList.add(WebInspector.SyntaxHighlightedStyleClassName); - - this._codeMirror = CodeMirror(this.element, { - readOnly: true, - indentWithTabs: true, - indentUnit: 4, - lineNumbers: true, - lineWrapping: true, - matchBrackets: true, - autoCloseBrackets: true - }); - - this._codeMirror.on("change", this._contentChanged.bind(this)); - this._codeMirror.on("gutterClick", this._gutterMouseDown.bind(this)); - this._codeMirror.on("gutterContextMenu", this._gutterContextMenu.bind(this)); - this._codeMirror.getScrollerElement().addEventListener("click", this._openClickedLinks.bind(this), true); - - this._completionController = new WebInspector.CodeMirrorCompletionController(this._codeMirror, this); - this._tokenTrackingController = new WebInspector.CodeMirrorTokenTrackingController(this._codeMirror, this); - - this._initialStringNotSet = true; - - this.mimeType = mimeType; - - this._breakpoints = {}; - this._executionLineNumber = NaN; - this._executionColumnNumber = NaN; - - this._searchQuery = null; - this._searchResults = []; - this._currentSearchResultIndex = -1; - this._ignoreCodeMirrorContentDidChangeEvent = 0; - - this._formatted = false; - this._formatterSourceMap = null; - - this._delegate = delegate || null; -}; - -WebInspector.Object.addConstructorFunctions(WebInspector.TextEditor); - -WebInspector.TextEditor.StyleClassName = "text-editor"; -WebInspector.TextEditor.HighlightedStyleClassName = "highlighted"; -WebInspector.TextEditor.SearchResultStyleClassName = "search-result"; -WebInspector.TextEditor.HasBreakpointStyleClassName = "has-breakpoint"; -WebInspector.TextEditor.BreakpointResolvedStyleClassName = "breakpoint-resolved"; -WebInspector.TextEditor.BreakpointAutoContinueStyleClassName = "breakpoint-auto-continue"; -WebInspector.TextEditor.BreakpointDisabledStyleClassName = "breakpoint-disabled"; -WebInspector.TextEditor.MultipleBreakpointsStyleClassName = "multiple-breakpoints"; -WebInspector.TextEditor.ExecutionLineStyleClassName = "execution-line"; -WebInspector.TextEditor.BouncyHighlightStyleClassName = "bouncy-highlight"; -WebInspector.TextEditor.NumberOfFindsPerSearchBatch = 10; -WebInspector.TextEditor.HighlightAnimationDuration = 2000; - -WebInspector.TextEditor.Event = { - ExecutionLineNumberDidChange: "text-editor-execution-line-number-did-change", - NumberOfSearchResultsDidChange: "text-editor-number-of-search-results-did-change", - ContentDidChange: "text-editor-content-did-change", - FormattingDidChange: "text-editor-formatting-did-change" -}; - -WebInspector.TextEditor.prototype = { - constructor: WebInspector.TextEditor, - - // Public - - get element() - { - return this._element; - }, - - get string() - { - return this._codeMirror.getValue(); - }, - - set string(newString) - { - function update() - { - this._codeMirror.setValue(newString); - - if (this._initialStringNotSet) { - this._codeMirror.clearHistory(); - this._codeMirror.markClean(); - delete this._initialStringNotSet; - } - - // Automatically format the content. - if (this._autoFormat) { - console.assert(!this.formatted); - this.formatted = true; - delete this._autoFormat; - } - - // Update the execution line now that we might have content for that line. - this._updateExecutionLine(); - - // Set the breakpoint styles now that we might have content for those lines. - for (var lineNumber in this._breakpoints) - this._setBreakpointStylesOnLine(lineNumber); - - // Try revealing the pending line now that we might have content with enough lines. - this._revealPendingPositionIfPossible(); - } - - this._ignoreCodeMirrorContentDidChangeEvent++; - this._codeMirror.operation(update.bind(this)); - this._ignoreCodeMirrorContentDidChangeEvent--; - console.assert(this._ignoreCodeMirrorContentDidChangeEvent >= 0); - }, - - get readOnly() - { - return this._codeMirror.getOption("readOnly") || false; - }, - - set readOnly(readOnly) - { - this._codeMirror.setOption("readOnly", readOnly); - }, - - get formatted() - { - return this._formatted; - }, - - set formatted(formatted) - { - if (this._formatted === formatted) - return; - - console.assert(!formatted || this.canBeFormatted()); - if (formatted && !this.canBeFormatted()) - return; - - this._ignoreCodeMirrorContentDidChangeEvent++; - this._prettyPrint(formatted); - this._ignoreCodeMirrorContentDidChangeEvent--; - console.assert(this._ignoreCodeMirrorContentDidChangeEvent >= 0); - - this._formatted = formatted; - - this.dispatchEventToListeners(WebInspector.TextEditor.Event.FormattingDidChange); - }, - - set autoFormat(auto) - { - this._autoFormat = auto; - }, - - hasFormatter: function() - { - const supportedModes = { - "javascript": true, - "css": true, - }; - - var mode = this._codeMirror.getMode(); - return mode.name in supportedModes; - }, - - canBeFormatted: function() - { - // Can be overriden by subclasses. - return this.hasFormatter(); - }, - - get selectedTextRange() - { - var start = this._codeMirror.getCursor(true); - var end = this._codeMirror.getCursor(false); - return this._textRangeFromCodeMirrorPosition(start, end); - }, - - set selectedTextRange(textRange) - { - var position = this._codeMirrorPositionFromTextRange(textRange); - this._codeMirror.setSelection(position.start, position.end); - }, - - get mimeType() - { - return this._mimeType; - }, - - set mimeType(newMIMEType) - { - newMIMEType = parseMIMEType(newMIMEType).type; - - this._mimeType = newMIMEType; - this._codeMirror.setOption("mode", newMIMEType); - }, - - get executionLineNumber() - { - return this._executionLineNumber; - }, - - set executionLineNumber(lineNumber) - { - // Only return early if there isn't a line handle and that isn't changing. - if (!this._executionLineHandle && isNaN(lineNumber)) - return; - - this._executionLineNumber = lineNumber; - this._updateExecutionLine(); - - // Still dispatch the event even if the number didn't change. The execution state still - // could have changed (e.g. continuing in a loop with a breakpoint inside). - this.dispatchEventToListeners(WebInspector.TextEditor.Event.ExecutionLineNumberDidChange); - }, - - get executionColumnNumber() - { - return this._executionColumnNumber; - }, - - set executionColumnNumber(columnNumber) - { - this._executionColumnNumber = columnNumber; - }, - - get formatterSourceMap() - { - return this._formatterSourceMap; - }, - - get tokenTrackingController() - { - return this._tokenTrackingController; - }, - - get delegate() - { - return this._delegate; - }, - - set delegate(newDelegate) - { - this._delegate = newDelegate || null; - }, - - get numberOfSearchResults() - { - return this._searchResults.length; - }, - - get currentSearchQuery() - { - return this._searchQuery; - }, - - set automaticallyRevealFirstSearchResult(reveal) - { - this._automaticallyRevealFirstSearchResult = reveal; - - // If we haven't shown a search result yet, reveal one now. - if (this._automaticallyRevealFirstSearchResult && this._searchResults.length > 0) { - if (this._currentSearchResultIndex === -1) - this._revealFirstSearchResultAfterCursor(); - } - }, - - performSearch: function(query) - { - if (this._searchQuery === query) - return; - - this.searchCleared(); - - this._searchQuery = query; - - // Allow subclasses to handle the searching if they have a better way. - // If we are formatted, just use CodeMirror's search. - if (typeof this.customPerformSearch === "function" && !this.formatted) { - if (this.customPerformSearch(query)) - return; - } - - // Go down the slow patch for all other text content. - var searchCursor = this._codeMirror.getSearchCursor(query, {line: 0, ch: 0}, true); - var boundBatchSearch = batchSearch.bind(this); - var numberOfSearchResultsDidChangeTimeout = null; - - function reportNumberOfSearchResultsDidChange() - { - if (numberOfSearchResultsDidChangeTimeout) { - clearTimeout(numberOfSearchResultsDidChangeTimeout); - numberOfSearchResultsDidChangeTimeout = null; - } - - this.dispatchEventToListeners(WebInspector.TextEditor.Event.NumberOfSearchResultsDidChange); - } - - function batchSearch() - { - // Bail if the query changed since we started. - if (this._searchQuery !== query) - return; - - var newSearchResults = []; - var foundResult = false; - for (var i = 0; i < WebInspector.TextEditor.NumberOfFindsPerSearchBatch && (foundResult = searchCursor.findNext()); ++i) { - var textRange = this._textRangeFromCodeMirrorPosition(searchCursor.from(), searchCursor.to()); - newSearchResults.push(textRange); - } - - this.addSearchResults(newSearchResults); - - // Don't report immediately, coalesce updates so they come in no faster than half a second. - if (!numberOfSearchResultsDidChangeTimeout) - numberOfSearchResultsDidChangeTimeout = setTimeout(reportNumberOfSearchResultsDidChange.bind(this), 500); - - if (foundResult) { - // More lines to search, set a timeout so we don't block the UI long. - setTimeout(boundBatchSearch, 50); - } else { - // Report immediately now that we are finished, canceling any pending update. - reportNumberOfSearchResultsDidChange.call(this); - } - } - - // Start the search. - boundBatchSearch(); - }, - - addSearchResults: function(textRanges) - { - console.assert(textRanges); - if (!textRanges || !textRanges.length) - return; - - function markRanges() - { - for (var i = 0; i < textRanges.length; ++i) { - var position = this._codeMirrorPositionFromTextRange(textRanges[i]); - var mark = this._codeMirror.markText(position.start, position.end, {className: WebInspector.TextEditor.SearchResultStyleClassName}); - this._searchResults.push(mark); - } - - // If we haven't shown a search result yet, reveal one now. - if (this._automaticallyRevealFirstSearchResult) { - if (this._currentSearchResultIndex === -1) - this._revealFirstSearchResultAfterCursor(); - } - } - - this._codeMirror.operation(markRanges.bind(this)); - }, - - searchCleared: function() - { - function clearResults() { - for (var i = 0; i < this._searchResults.length; ++i) - this._searchResults[i].clear(); - } - - this._codeMirror.operation(clearResults.bind(this)); - - this._searchQuery = null; - this._searchResults = []; - this._currentSearchResultIndex = -1; - }, - - searchQueryWithSelection: function() - { - if (!this._codeMirror.somethingSelected()) - return null; - - return this._codeMirror.getSelection(); - }, - - revealPreviousSearchResult: function(changeFocus) - { - if (!this._searchResults.length) - return; - - if (this._currentSearchResultIndex === -1 || this._cursorDoesNotMatchLastRevealedSearchResult()) { - this._revealFirstSearchResultBeforeCursor(changeFocus); - return; - } - - if (this._currentSearchResultIndex > 0) - --this._currentSearchResultIndex; - else - this._currentSearchResultIndex = this._searchResults.length - 1; - - this._revealSearchResult(this._searchResults[this._currentSearchResultIndex], changeFocus, -1); - }, - - revealNextSearchResult: function(changeFocus) - { - if (!this._searchResults.length) - return; - - if (this._currentSearchResultIndex === -1 || this._cursorDoesNotMatchLastRevealedSearchResult()) { - this._revealFirstSearchResultAfterCursor(changeFocus); - return; - } - - if (this._currentSearchResultIndex + 1 < this._searchResults.length) - ++this._currentSearchResultIndex; - else - this._currentSearchResultIndex = 0; - - this._revealSearchResult(this._searchResults[this._currentSearchResultIndex], changeFocus, 1); - }, - - line: function(lineNumber) - { - return this._codeMirror.getLine(lineNumber); - }, - - revealPosition: function(position, textRangeToSelect, forceUnformatted, noHighlight) - { - console.assert(position === undefined || position instanceof WebInspector.SourceCodePosition, "revealPosition called without a SourceCodePosition"); - if (!(position instanceof WebInspector.SourceCodePosition)) - return; - - var lineHandle = this._codeMirror.getLineHandle(position.lineNumber); - if (!lineHandle || !this._visible || this._initialStringNotSet) { - // If we can't get a line handle or are not visible then we wait to do the reveal. - this._positionToReveal = position; - this._textRangeToSelect = textRangeToSelect; - this._forceUnformatted = forceUnformatted; - return; - } - - // Delete now that the reveal is happening. - delete this._positionToReveal; - delete this._textRangeToSelect; - delete this._forceUnformatted; - - // If we need to unformat, reveal the line after a wait. - // Otherwise the line highlight doesn't work properly. - if (this._formatted && forceUnformatted) { - this.formatted = false; - setTimeout(this.revealPosition.bind(this), 0, position, textRangeToSelect); - return; - } - - if (!textRangeToSelect) - textRangeToSelect = new WebInspector.TextRange(position.lineNumber, position.columnNumber, position.lineNumber, position.columnNumber); - - function removeStyleClass() - { - this._codeMirror.removeLineClass(lineHandle, "wrap", WebInspector.TextEditor.HighlightedStyleClassName); - } - - function revealAndHighlightLine() - { - // If the line is not visible, reveal it as the center line in the editor. - var position = this._codeMirrorPositionFromTextRange(textRangeToSelect); - if (!this._isPositionVisible(position.start)) - this._scrollIntoViewCentered(position.start); - - this.selectedTextRange = textRangeToSelect; - - if (noHighlight) - return; - - this._codeMirror.addLineClass(lineHandle, "wrap", WebInspector.TextEditor.HighlightedStyleClassName); - - // Use a timeout instead of a webkitAnimationEnd event listener because the line element might - // be removed if the user scrolls during the animation. In that case webkitAnimationEnd isn't - // fired, and the line would highlight again the next time it scrolls into view. - setTimeout(removeStyleClass.bind(this), WebInspector.TextEditor.HighlightAnimationDuration); - } - - this._codeMirror.operation(revealAndHighlightLine.bind(this)); - }, - - updateLayout: function(force) - { - this._codeMirror.refresh(); - }, - - shown: function() - { - this._visible = true; - - // Refresh since our size might have changed. - this._codeMirror.refresh(); - - // Try revealing the pending line now that we are visible. - // This needs to be done as a separate operation from the refresh - // so that the scrollInfo coordinates are correct. - this._revealPendingPositionIfPossible(); - }, - - hidden: function() - { - this._visible = false; - }, - - setBreakpointInfoForLineAndColumn: function(lineNumber, columnNumber, breakpointInfo) - { - if (this._ignoreSetBreakpointInfoCalls) - return; - - if (breakpointInfo) - this._addBreakpointToLineAndColumnWithInfo(lineNumber, columnNumber, breakpointInfo); - else - this._removeBreakpointFromLineAndColumn(lineNumber, columnNumber); - }, - - updateBreakpointLineAndColumn: function(oldLineNumber, oldColumnNumber, newLineNumber, newColumnNumber) - { - console.assert(this._breakpoints[oldLineNumber]); - if (!this._breakpoints[oldLineNumber]) - return; - - console.assert(this._breakpoints[oldLineNumber][oldColumnNumber]); - if (!this._breakpoints[oldLineNumber][oldColumnNumber]) - return; - - var breakpointInfo = this._breakpoints[oldLineNumber][oldColumnNumber]; - this._removeBreakpointFromLineAndColumn(oldLineNumber, oldColumnNumber); - this._addBreakpointToLineAndColumnWithInfo(newLineNumber, newColumnNumber, breakpointInfo); - }, - - addStyleClassToLine: function(lineNumber, styleClassName) - { - var lineHandle = this._codeMirror.getLineHandle(lineNumber); - console.assert(lineHandle); - if (!lineHandle) - return; - - return this._codeMirror.addLineClass(lineHandle, "wrap", styleClassName); - }, - - removeStyleClassFromLine: function(lineNumber, styleClassName) - { - var lineHandle = this._codeMirror.getLineHandle(lineNumber); - console.assert(lineHandle); - if (!lineHandle) - return; - - return this._codeMirror.removeLineClass(lineHandle, "wrap", styleClassName); - }, - - toggleStyleClassForLine: function(lineNumber, styleClassName) - { - var lineHandle = this._codeMirror.getLineHandle(lineNumber); - console.assert(lineHandle); - if (!lineHandle) - return; - - return this._codeMirror.toggleLineClass(lineHandle, "wrap", styleClassName); - }, - - get lineCount() - { - return this._codeMirror.lineCount(); - }, - - focus: function() - { - this._codeMirror.focus(); - }, - - contentDidChange: function(replacedRanges, newRanges) - { - // Implemented by subclasses. - }, - - boundsForRange: function(range) - { - return this._codeMirror.boundsForRange(range); - }, - - get markers() - { - return this._codeMirror.getAllMarks().map(function(codeMirrorTextMarker) { - return WebInspector.TextMarker.textMarkerForCodeMirrorTextMarker(codeMirrorTextMarker); - }); - }, - - markersAtPosition: function(position) - { - return this._codeMirror.findMarksAt(position).map(function(codeMirrorTextMarker) { - return WebInspector.TextMarker.textMarkerForCodeMirrorTextMarker(codeMirrorTextMarker); - }); - }, - - createColorMarkers: function(lineNumber) - { - return this._codeMirror.createColorMarkers(lineNumber); - }, - - colorEditingControllerForMarker: function(colorMarker) - { - return new WebInspector.CodeMirrorColorEditingController(this._codeMirror, colorMarker); - }, - - // Private - - _contentChanged: function(codeMirror, change) - { - if (this._ignoreCodeMirrorContentDidChangeEvent > 0) - return; - - var replacedRanges = []; - var newRanges = []; - while (change) { - replacedRanges.push(new WebInspector.TextRange( - change.from.line, - change.from.ch, - change.to.line, - change.to.ch - )); - newRanges.push(new WebInspector.TextRange( - change.from.line, - change.from.ch, - change.from.line + change.text.length - 1, - change.text.length === 1 ? change.from.ch + change.text[0].length : change.text.lastValue.length - )); - change = change.next; - } - this.contentDidChange(replacedRanges, newRanges); - - if (this._formatted) { - this._formatterSourceMap = null; - this._formatted = false; - - if (this._delegate && typeof this._delegate.textEditorUpdatedFormatting === "function") - this._delegate.textEditorUpdatedFormatting(this); - - this.dispatchEventToListeners(WebInspector.TextEditor.Event.FormattingDidChange); - } - - this.dispatchEventToListeners(WebInspector.TextEditor.Event.ContentDidChange); - }, - - _textRangeFromCodeMirrorPosition: function(start, end) - { - console.assert(start); - console.assert(end); - - return new WebInspector.TextRange(start.line, start.ch, end.line, end.ch); - }, - - _codeMirrorPositionFromTextRange: function(textRange) - { - console.assert(textRange); - - var start = {line: textRange.startLine, ch: textRange.startColumn}; - var end = {line: textRange.endLine, ch: textRange.endColumn}; - return {start: start, end: end}; - }, - - _revealPendingPositionIfPossible: function() - { - // Nothing to do if we don't have a pending position. - if (!this._positionToReveal) - return; - - // Don't try to reveal unless we are visible. - if (!this._visible) - return; - - this.revealPosition(this._positionToReveal, this._textRangeToSelect, this._forceUnformatted); - }, - - _revealSearchResult: function(result, changeFocus, directionInCaseOfRevalidation) - { - var position = result.find(); - - // Check for a valid position, it might have been removed from editing by the user. - // If the position is invalide, revalidate all positions reveal as needed. - if (!position) { - this._revalidateSearchResults(directionInCaseOfRevalidation); - return; - } - - // If the line is not visible, reveal it as the center line in the editor. - if (!this._isPositionVisible(position.from)) - this._scrollIntoViewCentered(position.from); - - // Update the text selection to select the search result. - this.selectedTextRange = this._textRangeFromCodeMirrorPosition(position.from, position.to); - - // Remove the automatically reveal state now that we have revealed a search result. - this._automaticallyRevealFirstSearchResult = false; - - // Focus the editor if requested. - if (changeFocus) - this._codeMirror.focus(); - - // Remove the bouncy highlight if it is still around. The animation will not - // start unless we remove it and add it back to the document. - if (this._bouncyHighlightElement) - this._bouncyHighlightElement.remove(); - - // Create the bouncy highlight. - this._bouncyHighlightElement = document.createElement("div"); - this._bouncyHighlightElement.className = WebInspector.TextEditor.BouncyHighlightStyleClassName; - - // Collect info for the bouncy highlight. - var textContent = this._codeMirror.getSelection(); - var coordinates = this._codeMirror.cursorCoords(true, "page"); - - // Adjust the coordinates to be based in the text editor's space. - var textEditorRect = this._element.getBoundingClientRect(); - coordinates.top -= textEditorRect.top; - coordinates.left -= textEditorRect.left; - - // Position and show the bouncy highlight. - this._bouncyHighlightElement.textContent = textContent; - this._bouncyHighlightElement.style.top = coordinates.top + "px"; - this._bouncyHighlightElement.style.left = coordinates.left + "px"; - this._element.appendChild(this._bouncyHighlightElement); - - function animationEnded() - { - if (!this._bouncyHighlightElement) - return; - - this._bouncyHighlightElement.remove(); - delete this._bouncyHighlightElement; - } - - // Listen for the end of the animation so we can remove the element. - this._bouncyHighlightElement.addEventListener("webkitAnimationEnd", animationEnded.bind(this)); - }, - - _binarySearchInsertionIndexInSearchResults: function(object, comparator) - { - // It is possible that markers in the search results array may have been deleted. - // In those cases the comparator will return "null" and we immediately stop - // the binary search and return null. The search results list needs to be updated. - var array = this._searchResults; - - var first = 0; - var last = array.length - 1; - - while (first <= last) { - var mid = (first + last) >> 1; - var c = comparator(object, array[mid]); - if (c === null) - return null; - if (c > 0) - first = mid + 1; - else if (c < 0) - last = mid - 1; - else - return mid; - } - - return first - 1; - }, - - _revealFirstSearchResultBeforeCursor: function(changeFocus) - { - console.assert(this._searchResults.length); - - var currentCursorPosition = this._codeMirror.getCursor("start"); - if (currentCursorPosition.line === 0 && currentCursorPosition.ch === 0) { - this._currentSearchResultIndex = this._searchResults.length - 1; - this._revealSearchResult(this._searchResults[this._currentSearchResultIndex], changeFocus, -1); - return; - } - - var index = this._binarySearchInsertionIndexInSearchResults(currentCursorPosition, function(current, searchResult) { - var searchResultMarker = searchResult.find(); - if (!searchResultMarker) - return null; - return WebInspector.compareCodeMirrorPositions(current, searchResultMarker.from); - }); - - if (index === null) { - this._revalidateSearchResults(-1); - return; - } - - this._currentSearchResultIndex = index; - this._revealSearchResult(this._searchResults[this._currentSearchResultIndex], changeFocus); - }, - - _revealFirstSearchResultAfterCursor: function(changeFocus) - { - console.assert(this._searchResults.length); - - var currentCursorPosition = this._codeMirror.getCursor("start"); - if (currentCursorPosition.line === 0 && currentCursorPosition.ch === 0) { - this._currentSearchResultIndex = 0; - this._revealSearchResult(this._searchResults[this._currentSearchResultIndex], changeFocus, 1); - return; - } - - var index = this._binarySearchInsertionIndexInSearchResults(currentCursorPosition, function(current, searchResult) { - var searchResultMarker = searchResult.find(); - if (!searchResultMarker) - return null; - return WebInspector.compareCodeMirrorPositions(current, searchResultMarker.from); - }); - - if (index === null) { - this._revalidateSearchResults(1); - return; - } - - if (index + 1 < this._searchResults.length) - ++index; - else - index = 0; - - this._currentSearchResultIndex = index; - this._revealSearchResult(this._searchResults[this._currentSearchResultIndex], changeFocus); - }, - - _cursorDoesNotMatchLastRevealedSearchResult: function() - { - console.assert(this._currentSearchResultIndex !== -1); - console.assert(this._searchResults.length); - - var lastRevealedSearchResultMarker = this._searchResults[this._currentSearchResultIndex].find(); - if (!lastRevealedSearchResultMarker) - return true; - - var currentCursorPosition = this._codeMirror.getCursor("start"); - var lastRevealedSearchResultPosition = lastRevealedSearchResultMarker.from; - - return WebInspector.compareCodeMirrorPositions(currentCursorPosition, lastRevealedSearchResultPosition) !== 0; - }, - - _revalidateSearchResults: function(direction) - { - console.assert(direction !== undefined); - - this._currentSearchResultIndex = -1; - - var updatedSearchResults = []; - for (var i = 0; i < this._searchResults.length; ++i) { - if (this._searchResults[i].find()) - updatedSearchResults.push(this._searchResults[i]); - } - - console.assert(updatedSearchResults.length !== this._searchResults.length); - - this._searchResults = updatedSearchResults; - this.dispatchEventToListeners(WebInspector.TextEditor.Event.NumberOfSearchResultsDidChange); - - if (this._searchResults.length) { - if (direction > 0) - this._revealFirstSearchResultAfterCursor(); - else - this._revealFirstSearchResultBeforeCursor(); - } - }, - - _updateExecutionLine: function() - { - function update() - { - if (this._executionLineHandle) - this._codeMirror.removeLineClass(this._executionLineHandle, "wrap", WebInspector.TextEditor.ExecutionLineStyleClassName); - - this._executionLineHandle = !isNaN(this._executionLineNumber) ? this._codeMirror.getLineHandle(this._executionLineNumber) : null; - - if (this._executionLineHandle) - this._codeMirror.addLineClass(this._executionLineHandle, "wrap", WebInspector.TextEditor.ExecutionLineStyleClassName); - } - - this._codeMirror.operation(update.bind(this)); - }, - - _setBreakpointStylesOnLine: function(lineNumber) - { - var columnBreakpoints = this._breakpoints[lineNumber]; - console.assert(columnBreakpoints); - if (!columnBreakpoints) - return; - - var allDisabled = true; - var allResolved = true; - var allAutoContinue = true; - var multiple = Object.keys(columnBreakpoints).length > 1; - for (var columnNumber in columnBreakpoints) { - var breakpointInfo = columnBreakpoints[columnNumber]; - if (!breakpointInfo.disabled) - allDisabled = false; - if (!breakpointInfo.resolved) - allResolved = false; - if (!breakpointInfo.autoContinue) - allAutoContinue = false; - } - - function updateStyles() - { - // We might not have a line if the content isn't fully populated yet. - // This will be called again when the content is available. - var lineHandle = this._codeMirror.getLineHandle(lineNumber); - if (!lineHandle) - return; - - this._codeMirror.addLineClass(lineHandle, "wrap", WebInspector.TextEditor.HasBreakpointStyleClassName); - - if (allResolved) - this._codeMirror.addLineClass(lineHandle, "wrap", WebInspector.TextEditor.BreakpointResolvedStyleClassName); - else - this._codeMirror.removeLineClass(lineHandle, "wrap", WebInspector.TextEditor.BreakpointResolvedStyleClassName); - - if (allDisabled) - this._codeMirror.addLineClass(lineHandle, "wrap", WebInspector.TextEditor.BreakpointDisabledStyleClassName); - else - this._codeMirror.removeLineClass(lineHandle, "wrap", WebInspector.TextEditor.BreakpointDisabledStyleClassName); - - if (allAutoContinue) - this._codeMirror.addLineClass(lineHandle, "wrap", WebInspector.TextEditor.BreakpointAutoContinueStyleClassName); - else - this._codeMirror.removeLineClass(lineHandle, "wrap", WebInspector.TextEditor.BreakpointAutoContinueStyleClassName); - - if (multiple) - this._codeMirror.addLineClass(lineHandle, "wrap", WebInspector.TextEditor.MultipleBreakpointsStyleClassName); - else - this._codeMirror.removeLineClass(lineHandle, "wrap", WebInspector.TextEditor.MultipleBreakpointsStyleClassName); - } - - this._codeMirror.operation(updateStyles.bind(this)); - }, - - _addBreakpointToLineAndColumnWithInfo: function(lineNumber, columnNumber, breakpointInfo) - { - if (!this._breakpoints[lineNumber]) - this._breakpoints[lineNumber] = {}; - this._breakpoints[lineNumber][columnNumber] = breakpointInfo; - - this._setBreakpointStylesOnLine(lineNumber); - }, - - _removeBreakpointFromLineAndColumn: function(lineNumber, columnNumber) - { - console.assert(columnNumber in this._breakpoints[lineNumber]); - delete this._breakpoints[lineNumber][columnNumber]; - - // There are still breakpoints on the line. Update the breakpoint style. - if (!isEmptyObject(this._breakpoints[lineNumber])) { - this._setBreakpointStylesOnLine(lineNumber); - return; - } - - delete this._breakpoints[lineNumber]; - - function updateStyles() - { - var lineHandle = this._codeMirror.getLineHandle(lineNumber); - if (!lineHandle) - return; - - this._codeMirror.removeLineClass(lineHandle, "wrap", WebInspector.TextEditor.HasBreakpointStyleClassName); - this._codeMirror.removeLineClass(lineHandle, "wrap", WebInspector.TextEditor.BreakpointResolvedStyleClassName); - this._codeMirror.removeLineClass(lineHandle, "wrap", WebInspector.TextEditor.BreakpointDisabledStyleClassName); - this._codeMirror.removeLineClass(lineHandle, "wrap", WebInspector.TextEditor.BreakpointAutoContinueStyleClassName); - this._codeMirror.removeLineClass(lineHandle, "wrap", WebInspector.TextEditor.MultipleBreakpointsStyleClassName); - } - - this._codeMirror.operation(updateStyles.bind(this)); - }, - - _allColumnBreakpointInfoForLine: function(lineNumber) - { - return this._breakpoints[lineNumber]; - }, - - _setColumnBreakpointInfoForLine: function(lineNumber, columnBreakpointInfo) - { - console.assert(columnBreakpointInfo); - this._breakpoints[lineNumber] = columnBreakpointInfo; - this._setBreakpointStylesOnLine(lineNumber); - }, - - _gutterMouseDown: function(codeMirror, lineNumber, gutterElement, event) - { - if (event.button !== 0 || event.ctrlKey) - return; - - if (!this._codeMirror.hasLineClass(lineNumber, "wrap", WebInspector.TextEditor.HasBreakpointStyleClassName)) { - console.assert(!(lineNumber in this._breakpoints)); - - // No breakpoint, add a new one. - if (this._delegate && typeof this._delegate.textEditorBreakpointAdded === "function") { - var data = this._delegate.textEditorBreakpointAdded(this, lineNumber, 0); - if (data) { - var breakpointInfo = data.breakpointInfo; - if (breakpointInfo) - this._addBreakpointToLineAndColumnWithInfo(data.lineNumber, data.columnNumber, breakpointInfo); - } - } - - return; - } - - console.assert(lineNumber in this._breakpoints); - - if (this._codeMirror.hasLineClass(lineNumber, "wrap", WebInspector.TextEditor.MultipleBreakpointsStyleClassName)) { - console.assert(!isEmptyObject(this._breakpoints[lineNumber])); - return; - } - - // Single existing breakpoint, start tracking it for dragging. - console.assert(Object.keys(this._breakpoints[lineNumber]).length === 1); - var columnNumber = Object.keys(this._breakpoints[lineNumber])[0]; - this._draggingBreakpointInfo = this._breakpoints[lineNumber][columnNumber]; - this._lineNumberWithMousedDownBreakpoint = lineNumber; - this._lineNumberWithDraggedBreakpoint = lineNumber; - this._columnNumberWithMousedDownBreakpoint = columnNumber; - this._columnNumberWithDraggedBreakpoint = columnNumber; - - this._documentMouseMovedEventListener = this._documentMouseMoved.bind(this); - this._documentMouseUpEventListener = this._documentMouseUp.bind(this); - - // Register these listeners on the document so we can track the mouse if it leaves the gutter. - document.addEventListener("mousemove", this._documentMouseMovedEventListener, true); - document.addEventListener("mouseup", this._documentMouseUpEventListener, true); - }, - - _gutterContextMenu: function(codeMirror, lineNumber, gutterElement, event) - { - if (this._delegate && typeof this._delegate.textEditorGutterContextMenu === "function") { - var breakpoints = []; - for (var columnNumber in this._breakpoints[lineNumber]) - breakpoints.push({lineNumber:lineNumber, columnNumber:columnNumber}); - - this._delegate.textEditorGutterContextMenu(this, lineNumber, 0, breakpoints, event); - } - }, - - _documentMouseMoved: function(event) - { - console.assert("_lineNumberWithMousedDownBreakpoint" in this); - if (!("_lineNumberWithMousedDownBreakpoint" in this)) - return; - - event.preventDefault(); - - var lineNumber; - var position = this._codeMirror.coordsChar({left: event.pageX, top: event.pageY}); - - // CodeMirror's coordsChar returns a position even if it is outside the bounds. Nullify the position - // if the event is outside the bounds of the gutter so we will remove the breakpoint. - var gutterBounds = this._codeMirror.getGutterElement().getBoundingClientRect(); - if (event.pageX < gutterBounds.left || event.pageX > gutterBounds.right || event.pageY < gutterBounds.top || event.pageY > gutterBounds.bottom) - position = null; - - // If we have a position and it has a line then use it. - if (position && "line" in position) - lineNumber = position.line; - - // The _lineNumberWithDraggedBreakpoint property can be undefined if the user drags - // outside of the gutter. The lineNumber variable can be undefined for the same reason. - - if (lineNumber === this._lineNumberWithDraggedBreakpoint) - return; - - // Record that the mouse dragged some so when mouse up fires we know to do the - // work of removing and moving the breakpoint. - this._mouseDragged = true; - - if ("_lineNumberWithDraggedBreakpoint" in this) { - // We have a line that is currently showing the dragged breakpoint. Remove that breakpoint - // and restore the previous one (if any.) - if (this._previousColumnBreakpointInfo) - this._setColumnBreakpointInfoForLine(this._lineNumberWithDraggedBreakpoint, this._previousColumnBreakpointInfo); - else - this._removeBreakpointFromLineAndColumn(this._lineNumberWithDraggedBreakpoint, this._columnNumberWithDraggedBreakpoint); - - delete this._previousColumnBreakpointInfo; - delete this._lineNumberWithDraggedBreakpoint; - delete this._columnNumberWithDraggedBreakpoint; - } - - if (lineNumber !== undefined) { - // We have a new line that will now show the dragged breakpoint. - var newColumnBreakpoints = {}; - var columnNumber = (lineNumber === this._lineNumberWithMousedDownBreakpoint ? this._columnNumberWithDraggedBreakpoint : 0); - newColumnBreakpoints[columnNumber] = this._draggingBreakpointInfo; - this._previousColumnBreakpointInfo = this._allColumnBreakpointInfoForLine(lineNumber); - this._setColumnBreakpointInfoForLine(lineNumber, newColumnBreakpoints); - this._lineNumberWithDraggedBreakpoint = lineNumber; - this._columnNumberWithDraggedBreakpoint = columnNumber; - } - }, - - _documentMouseUp: function(event) - { - console.assert("_lineNumberWithMousedDownBreakpoint" in this); - if (!("_lineNumberWithMousedDownBreakpoint" in this)) - return; - - event.preventDefault(); - - document.removeEventListener("mousemove", this._documentMouseMovedEventListener, true); - document.removeEventListener("mouseup", this._documentMouseUpEventListener, true); - - const delegateImplementsBreakpointClicked = this._delegate && typeof this._delegate.textEditorBreakpointClicked === "function"; - const delegateImplementsBreakpointRemoved = this._delegate && typeof this._delegate.textEditorBreakpointRemoved === "function"; - const delegateImplementsBreakpointMoved = this._delegate && typeof this._delegate.textEditorBreakpointMoved === "function"; - - if (this._mouseDragged) { - if (!("_lineNumberWithDraggedBreakpoint" in this)) { - // The breakpoint was dragged off the gutter, remove it. - if (delegateImplementsBreakpointRemoved) { - this._ignoreSetBreakpointInfoCalls = true; - this._delegate.textEditorBreakpointRemoved(this, this._lineNumberWithMousedDownBreakpoint, this._columnNumberWithMousedDownBreakpoint); - delete this._ignoreSetBreakpointInfoCalls; - } - } else if (this._lineNumberWithMousedDownBreakpoint !== this._lineNumberWithDraggedBreakpoint) { - // The dragged breakpoint was moved to a new line. - - // If there is are breakpoints already at the drop line, tell the delegate to remove them. - // We have already updated the breakpoint info internally, so when the delegate removes the breakpoints - // and tells us to clear the breakpoint info, we can ignore those calls. - if (this._previousColumnBreakpointInfo && delegateImplementsBreakpointRemoved) { - this._ignoreSetBreakpointInfoCalls = true; - for (var columnNumber in this._previousColumnBreakpointInfo) - this._delegate.textEditorBreakpointRemoved(this, this._lineNumberWithDraggedBreakpoint, columnNumber); - delete this._ignoreSetBreakpointInfoCalls; - } - - // Tell the delegate to move the breakpoint from one line to another. - if (delegateImplementsBreakpointMoved) { - this._ignoreSetBreakpointInfoCalls = true; - this._delegate.textEditorBreakpointMoved(this, this._lineNumberWithMousedDownBreakpoint, this._columnNumberWithMousedDownBreakpoint, this._lineNumberWithDraggedBreakpoint, this._columnNumberWithDraggedBreakpoint); - delete this._ignoreSetBreakpointInfoCalls; - } - } - } else { - // Toggle the disabled state of the breakpoint. - console.assert(this._lineNumberWithMousedDownBreakpoint in this._breakpoints); - console.assert(this._columnNumberWithMousedDownBreakpoint in this._breakpoints[this._lineNumberWithMousedDownBreakpoint]); - if (this._lineNumberWithMousedDownBreakpoint in this._breakpoints && this._columnNumberWithMousedDownBreakpoint in this._breakpoints[this._lineNumberWithMousedDownBreakpoint] && delegateImplementsBreakpointClicked) - this._delegate.textEditorBreakpointClicked(this, this._lineNumberWithMousedDownBreakpoint, this._columnNumberWithMousedDownBreakpoint); - } - - delete this._documentMouseMovedEventListener; - delete this._documentMouseUpEventListener; - delete this._lineNumberWithMousedDownBreakpoint; - delete this._lineNumberWithDraggedBreakpoint; - delete this._columnNumberWithMousedDownBreakpoint; - delete this._columnNumberWithDraggedBreakpoint; - delete this._previousColumnBreakpointInfo; - delete this._mouseDragged; - }, - - _openClickedLinks: function(event) - { - // Get the position in the text and the token at that position. - var position = this._codeMirror.coordsChar({left: event.pageX, top: event.pageY}); - var tokenInfo = this._codeMirror.getTokenAt(position); - if (!tokenInfo || !tokenInfo.type || !tokenInfo.string) - return; - - // If the token is not a link, then ignore it. - if (!/\blink\b/.test(tokenInfo.type)) - return; - - // The token string is the URL we should open. It might be a relative URL. - var url = tokenInfo.string; - - // Get the base URL. - var baseURL = ""; - if (this._delegate && typeof this._delegate.textEditorBaseURL === "function") - baseURL = this._delegate.textEditorBaseURL(this); - - // Open the link after resolving the absolute URL from the base URL. - WebInspector.openURL(absoluteURL(url, baseURL)); - - // Stop processing the event. - event.preventDefault(); - event.stopPropagation(); - }, - - _isPositionVisible: function(position) - { - var scrollInfo = this._codeMirror.getScrollInfo(); - var visibleRangeStart = scrollInfo.top; - var visibleRangeEnd = visibleRangeStart + scrollInfo.clientHeight; - var coords = this._codeMirror.charCoords(position, "local"); - - return coords.top >= visibleRangeStart && coords.bottom <= visibleRangeEnd; - }, - - _scrollIntoViewCentered: function(position) - { - var scrollInfo = this._codeMirror.getScrollInfo(); - var lineHeight = Math.ceil(this._codeMirror.defaultTextHeight()); - var margin = Math.floor((scrollInfo.clientHeight - lineHeight) / 2); - this._codeMirror.scrollIntoView(position, margin); - }, - - _prettyPrint: function(pretty) - { - function prettyPrintAndUpdateEditor() - { - const start = {line: 0, ch: 0}; - const end = {line: this._codeMirror.lineCount() - 1}; - - var oldSelectionAnchor = this._codeMirror.getCursor("anchor"); - var oldSelectionHead = this._codeMirror.getCursor("head"); - var newSelectionAnchor, newSelectionHead; - var newExecutionLocation = null; - - if (pretty) { - // Provide a way to change the tab width in the Web Inspector - const indentString = " "; - var originalLineEndings = []; - var formattedLineEndings = []; - var mapping = {original: [0], formatted: [0]}; - var builder = new FormatterContentBuilder(mapping, originalLineEndings, formattedLineEndings, 0, 0, indentString); - var formatter = new Formatter(this._codeMirror, builder); - formatter.format(start, end); - - this._formatterSourceMap = WebInspector.FormatterSourceMap.fromBuilder(builder); - - this._codeMirror.setValue(builder.formattedContent); - - if (this._positionToReveal) { - var newRevealPosition = this._formatterSourceMap.originalToFormatted(this._positionToReveal.lineNumber, this._positionToReveal.columnNumber); - this._positionToReveal = new WebInspector.SourceCodePosition(newRevealPosition.lineNumber, newRevealPosition.columnNumber); - } - - if (this._textRangeToSelect) { - var mappedRevealSelectionStart = this._formatterSourceMap.originalToFormatted(this._textRangeToSelect.startLine, this._textRangeToSelect.startColumn); - var mappedRevealSelectionEnd = this._formatterSourceMap.originalToFormatted(this._textRangeToSelect.endLine, this._textRangeToSelect.endColumn); - this._textRangeToSelect = new WebInspector.TextRange(mappedRevealSelectionStart.lineNumber, mappedRevealSelectionStart.columnNumber, mappedRevealSelectionEnd.lineNumber, mappedRevealSelectionEnd.columnNumber); - } - - if (!isNaN(this._executionLineNumber)) { - console.assert(!isNaN(this._executionColumnNumber)); - newExecutionLocation = this._formatterSourceMap.originalToFormatted(this._executionLineNumber, this._executionColumnNumber); - } - - var mappedAnchorLocation = this._formatterSourceMap.originalToFormatted(oldSelectionAnchor.line, oldSelectionAnchor.ch); - var mappedHeadLocation = this._formatterSourceMap.originalToFormatted(oldSelectionHead.line, oldSelectionHead.ch); - newSelectionAnchor = {line:mappedAnchorLocation.lineNumber, ch:mappedAnchorLocation.columnNumber}; - newSelectionHead = {line:mappedHeadLocation.lineNumber, ch:mappedHeadLocation.columnNumber}; - } else { - this._codeMirror.undo(); - - if (this._positionToReveal) { - var newRevealPosition = this._formatterSourceMap.formattedToOriginal(this._positionToReveal.lineNumber, this._positionToReveal.columnNumber); - this._positionToReveal = new WebInspector.SourceCodePosition(newRevealPosition.lineNumber, newRevealPosition.columnNumber); - } - - if (this._textRangeToSelect) { - var mappedRevealSelectionStart = this._formatterSourceMap.formattedToOriginal(this._textRangeToSelect.startLine, this._textRangeToSelect.startColumn); - var mappedRevealSelectionEnd = this._formatterSourceMap.formattedToOriginal(this._textRangeToSelect.endLine, this._textRangeToSelect.endColumn); - this._textRangeToSelect = new WebInspector.TextRange(mappedRevealSelectionStart.lineNumber, mappedRevealSelectionStart.columnNumber, mappedRevealSelectionEnd.lineNumber, mappedRevealSelectionEnd.columnNumber); - } - - if (!isNaN(this._executionLineNumber)) { - console.assert(!isNaN(this._executionColumnNumber)); - newExecutionLocation = this._formatterSourceMap.formattedToOriginal(this._executionLineNumber, this._executionColumnNumber); - } - - var mappedAnchorLocation = this._formatterSourceMap.formattedToOriginal(oldSelectionAnchor.line, oldSelectionAnchor.ch); - var mappedHeadLocation = this._formatterSourceMap.formattedToOriginal(oldSelectionHead.line, oldSelectionHead.ch); - newSelectionAnchor = {line:mappedAnchorLocation.lineNumber, ch:mappedAnchorLocation.columnNumber}; - newSelectionHead = {line:mappedHeadLocation.lineNumber, ch:mappedHeadLocation.columnNumber}; - - this._formatterSourceMap = null; - } - - this._scrollIntoViewCentered(newSelectionAnchor); - this._codeMirror.setSelection(newSelectionAnchor, newSelectionHead); - - if (newExecutionLocation) { - delete this._executionLineHandle; - this.executionColumnNumber = newExecutionLocation.columnNumber; - this.executionLineNumber = newExecutionLocation.lineNumber; - } - - // FIXME: FindBanner: New searches should not lose search position (start from current selection/caret) - if (this.currentSearchQuery) { - var searchQuery = this.currentSearchQuery; - this.searchCleared(); - // Set timeout so that this happens after the current CodeMirror operation. - // The editor has to update for the value and selection changes. - setTimeout(function(query) { - this.performSearch(searchQuery); - }.bind(this), 0); - } - - if (this._delegate && typeof this._delegate.textEditorUpdatedFormatting === "function") - this._delegate.textEditorUpdatedFormatting(this); - } - - this._codeMirror.operation(prettyPrintAndUpdateEditor.bind(this)); - } -}; - -WebInspector.TextEditor.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/TextMarker.js b/Source/WebInspectorUI/UserInterface/TextMarker.js deleted file mode 100644 index efdceb156..000000000 --- a/Source/WebInspectorUI/UserInterface/TextMarker.js +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.TextMarker = function(codeMirrorTextMarker, type) -{ - WebInspector.Object.call(this); - - this._codeMirrorTextMarker = codeMirrorTextMarker; - codeMirrorTextMarker.__webInspectorTextMarker = this; - - this._type = type || WebInspector.TextMarker.Type.Plain; -} - -WebInspector.TextMarker.Type = { - Color: "text-marker-type-color", - Plain: "text-marker-type-plain" -}; - -WebInspector.TextMarker.textMarkerForCodeMirrorTextMarker = function(codeMirrorTextMarker) -{ - return codeMirrorTextMarker.__webInspectorTextMarker || new WebInspector.TextMarker(codeMirrorTextMarker); -}; - -WebInspector.TextMarker.prototype = { - constructor: WebInspector.TextMarker, - __proto__: WebInspector.Object.prototype, - - // Public - - get codeMirrorTextMarker() - { - return this._codeMirrorTextMarker; - }, - - get type() - { - return this._type; - }, - - get range() - { - var range = this._codeMirrorTextMarker.find(); - if (!range) - return null; - return new WebInspector.TextRange(range.from.line, range.from.ch, range.to.line, range.to.ch); - }, - - get bounds() - { - var range = this._codeMirrorTextMarker.find(); - if (!range) - return WebInspector.Rect.ZERO_RECT; - return this._codeMirrorTextMarker.doc.cm.boundsForRange({ - start: range.from, - end: range.to - }); - }, - - clear: function() - { - this._codeMirrorTextMarker.clear(); - } -}; diff --git a/Source/WebInspectorUI/UserInterface/TextRange.js b/Source/WebInspectorUI/UserInterface/TextRange.js deleted file mode 100644 index f01156943..000000000 --- a/Source/WebInspectorUI/UserInterface/TextRange.js +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.TextRange = function(startLineOrStartOffset, startColumnOrEndOffset, endLine, endColumn) -{ - WebInspector.Object.call(this); - - if (arguments.length === 4) { - console.assert(startLineOrStartOffset <= endLine); - console.assert(startLineOrStartOffset !== endLine || startColumnOrEndOffset <= endColumn); - - this._startLine = typeof startLineOrStartOffset === "number" ? startLineOrStartOffset : NaN; - this._startColumn = typeof startColumnOrEndOffset === "number" ? startColumnOrEndOffset : NaN; - this._endLine = typeof endLine === "number" ? endLine : NaN; - this._endColumn = typeof endColumn === "number" ? endColumn : NaN; - - this._startOffset = NaN; - this._endOffset = NaN; - } else if (arguments.length === 2) { - console.assert(startLineOrStartOffset <= startColumnOrEndOffset); - - this._startOffset = typeof startLineOrStartOffset === "number" ? startLineOrStartOffset : NaN; - this._endOffset = typeof startColumnOrEndOffset === "number" ? startColumnOrEndOffset : NaN; - - this._startLine = NaN; - this._startColumn = NaN; - this._endLine = NaN; - this._endColumn = NaN; - } -} - -WebInspector.TextRange.prototype = { - constructor: WebInspector.TextRange, - - // Public - - get startLine() - { - return this._startLine; - }, - - get startColumn() - { - return this._startColumn; - }, - - get endLine() - { - return this._endLine; - }, - - get endColumn() - { - return this._endColumn; - }, - - get startOffset() - { - return this._startOffset; - }, - - get endOffset() - { - return this._endOffset; - }, - - startPosition: function() - { - return new WebInspector.SourceCodePosition(this._startLine, this._startColumn); - }, - - endPosition: function() - { - return new WebInspector.SourceCodePosition(this._endLine, this._endColumn); - }, - - resolveLinesAndColumns: function(text) - { - console.assert(typeof text === "string"); - if (typeof text !== "string") - return; - - console.assert(!isNaN(this._startOffset)); - console.assert(!isNaN(this._endOffset)); - if (isNaN(this._startOffset) || isNaN(this._endOffset)) - return; - - function countNewLineCharacters(text) - { - var matches = text.match(/\n/g); - return matches ? matches.length : 0; - } - - var startSubstring = text.substring(0, this._startOffset); - var rangeSubstring = text.substring(this._startOffset, this._endOffset); - - var startNewLineCount = countNewLineCharacters(startSubstring); - var rangeNewLineCount = countNewLineCharacters(rangeSubstring); - - this._startLine = startNewLineCount; - this._endLine = startNewLineCount + rangeNewLineCount; - - var lastNewLineOffset = startNewLineCount ? startSubstring.lastIndexOf("\n") + 1 : 0; - this._startColumn = startSubstring.length - lastNewLineOffset; - - lastNewLineOffset = rangeNewLineCount ? rangeSubstring.lastIndexOf("\n") + 1 : 0; - this._endColumn = rangeSubstring.length - lastNewLineOffset; - - if (this._startLine === this._endLine) - this._endColumn += this._startColumn; - }, - - resolveOffsets: function(text) - { - console.assert(typeof text === "string"); - if (typeof text !== "string") - return; - - console.assert(!isNaN(this._startLine)); - console.assert(!isNaN(this._startColumn)); - console.assert(!isNaN(this._endLine)); - console.assert(!isNaN(this._endColumn)); - if (isNaN(this._startLine) || isNaN(this._startColumn) || isNaN(this._endLine) || isNaN(this._endColumn)) - return; - - var lastNewLineOffset = 0; - for (var i = 0; i < this._startLine; ++i) - lastNewLineOffset = text.indexOf("\n", lastNewLineOffset) + 1; - - this._startOffset = lastNewLineOffset + this._startColumn; - - for (var i = this._startLine; i < this._endLine; ++i) - lastNewLineOffset = text.indexOf("\n", lastNewLineOffset) + 1; - - this._endOffset = lastNewLineOffset + this._endColumn; - } -}; - -WebInspector.TextRange.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/TextResourceContentView.css b/Source/WebInspectorUI/UserInterface/TextResourceContentView.css deleted file mode 100644 index 9921f5332..000000000 --- a/Source/WebInspectorUI/UserInterface/TextResourceContentView.css +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.content-view.resource.text > .text-editor { - position: absolute; - top: 0; - left: 0; - right: 0; - bottom: 0; -} diff --git a/Source/WebInspectorUI/UserInterface/TextResourceContentView.js b/Source/WebInspectorUI/UserInterface/TextResourceContentView.js deleted file mode 100644 index b34ee2752..000000000 --- a/Source/WebInspectorUI/UserInterface/TextResourceContentView.js +++ /dev/null @@ -1,229 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.TextResourceContentView = function(resource) -{ - WebInspector.ResourceContentView.call(this, resource, WebInspector.TextResourceContentView.StyleClassName); - - resource.addEventListener(WebInspector.SourceCode.Event.ContentDidChange, this._sourceCodeContentDidChange, this); - - this._textEditor = new WebInspector.SourceCodeTextEditor(resource); - this._textEditor.addEventListener(WebInspector.TextEditor.Event.ExecutionLineNumberDidChange, this._executionLineNumberDidChange, this); - this._textEditor.addEventListener(WebInspector.TextEditor.Event.NumberOfSearchResultsDidChange, this._numberOfSearchResultsDidChange, this); - this._textEditor.addEventListener(WebInspector.TextEditor.Event.ContentDidChange, this._textEditorContentDidChange, this); - this._textEditor.addEventListener(WebInspector.TextEditor.Event.FormattingDidChange, this._textEditorFormattingDidChange, this); - this._textEditor.addEventListener(WebInspector.SourceCodeTextEditor.Event.ContentWillPopulate, this._contentWillPopulate, this); - this._textEditor.addEventListener(WebInspector.SourceCodeTextEditor.Event.ContentDidPopulate, this._contentDidPopulate, this); - - var toolTip = WebInspector.UIString("Pretty print"); - var activatedToolTip = WebInspector.UIString("Original formatting"); - this._prettyPrintButtonNavigationItem = new WebInspector.ActivateButtonNavigationItem("pretty-print", toolTip, activatedToolTip, "Images/NavigationItemCurleyBraces.svg", 16, 16); - this._prettyPrintButtonNavigationItem.addEventListener(WebInspector.ButtonNavigationItem.Event.Clicked, this._togglePrettyPrint, this); - this._prettyPrintButtonNavigationItem.enabled = false; // Enabled when the text editor is populated with content. -}; - -WebInspector.TextResourceContentView.StyleClassName = "text"; - -WebInspector.TextResourceContentView.prototype = { - constructor: WebInspector.TextResourceContentView, - - // Public - - get navigationItems() - { - return [this._prettyPrintButtonNavigationItem]; - }, - - get managesOwnIssues() - { - // SourceCodeTextEditor manages the issues, we don't need ResourceContentView doing it. - return true; - }, - - get textEditor() - { - return this._textEditor; - }, - - get supplementalRepresentedObjects() - { - if (isNaN(this._textEditor.executionLineNumber)) - return []; - - // If the SourceCodeTextEditor has an executionLineNumber, we can assume - // it is always the active call frame. - return [WebInspector.debuggerManager.activeCallFrame]; - }, - - revealPosition: function(position, textRangeToSelect, forceUnformatted) - { - this._textEditor.revealPosition(position, textRangeToSelect, forceUnformatted); - }, - - shown: function() - { - WebInspector.ResourceContentView.prototype.shown.call(this); - - this._textEditor.shown(); - }, - - hidden: function() - { - WebInspector.ResourceContentView.prototype.hidden.call(this); - - this._textEditor.hidden(); - }, - - closed: function() - { - WebInspector.ResourceContentView.prototype.closed.call(this); - - this.resource.removeEventListener(WebInspector.SourceCode.Event.ContentDidChange, this._sourceCodeContentDidChange, this); - - this._textEditor.close(); - }, - - get supportsSave() - { - return true; - }, - - get saveData() - { - return {url: this.resource.url, content: this._textEditor.string}; - }, - - get supportsSearch() - { - return true; - }, - - get numberOfSearchResults() - { - return this._textEditor.numberOfSearchResults; - }, - - get hasPerformedSearch() - { - return this._textEditor.currentSearchQuery !== null; - }, - - set automaticallyRevealFirstSearchResult(reveal) - { - this._textEditor.automaticallyRevealFirstSearchResult = reveal; - }, - - performSearch: function(query) - { - this._textEditor.performSearch(query); - }, - - searchCleared: function() - { - this._textEditor.searchCleared(); - }, - - searchQueryWithSelection: function() - { - return this._textEditor.searchQueryWithSelection(); - }, - - revealPreviousSearchResult: function(changeFocus) - { - this._textEditor.revealPreviousSearchResult(changeFocus); - }, - - revealNextSearchResult: function(changeFocus) - { - this._textEditor.revealNextSearchResult(changeFocus); - }, - - updateLayout: function() - { - this._textEditor.updateLayout(); - }, - - // Private - - _contentWillPopulate: function(event) - { - if (this._textEditor.element.parentNode === this.element) - return; - - // Check the MIME-type for CSS since Resource.Type.Stylesheet also includes XSL, which we can't edit yet. - if (this.resource.type === WebInspector.Resource.Type.Stylesheet && this.resource.syntheticMIMEType === "text/css") - this._textEditor.readOnly = false; - - // Allow editing any local file since edits can be saved and reloaded right from the Inspector. - if (this.resource.urlComponents.scheme === "file") - this._textEditor.readOnly = false; - - this.element.removeChildren(); - this.element.appendChild(this._textEditor.element); - }, - - _contentDidPopulate: function(event) - { - this._prettyPrintButtonNavigationItem.enabled = this._textEditor.canBeFormatted(); - }, - - _togglePrettyPrint: function(event) - { - var activated = !this._prettyPrintButtonNavigationItem.activated; - this._textEditor.formatted = activated; - }, - - _textEditorFormattingDidChange: function(event) - { - this._prettyPrintButtonNavigationItem.activated = this._textEditor.formatted; - }, - - _sourceCodeContentDidChange: function(event) - { - if (this._ignoreSourceCodeContentDidChangeEvent) - return; - - this._textEditor.string = this.resource.currentRevision.content; - }, - - _textEditorContentDidChange: function(event) - { - this._ignoreSourceCodeContentDidChangeEvent = true; - WebInspector.branchManager.currentBranch.revisionForRepresentedObject(this.resource).content = this._textEditor.string; - delete this._ignoreSourceCodeContentDidChangeEvent; - }, - - _executionLineNumberDidChange: function(event) - { - this.dispatchEventToListeners(WebInspector.ContentView.Event.SupplementalRepresentedObjectsDidChange); - }, - - _numberOfSearchResultsDidChange: function(event) - { - this.dispatchEventToListeners(WebInspector.ContentView.Event.NumberOfSearchResultsDidChange); - } -}; - -WebInspector.TextResourceContentView.prototype.__proto__ = WebInspector.ResourceContentView.prototype; diff --git a/Source/WebInspectorUI/UserInterface/Timeline.js b/Source/WebInspectorUI/UserInterface/Timeline.js deleted file mode 100644 index e2e272944..000000000 --- a/Source/WebInspectorUI/UserInterface/Timeline.js +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.Timeline = function() -{ - WebInspector.Object.call(this); - - this.reset(true); -}; - -WebInspector.Timeline.Event = { - Reset: "timeline-reset", - RecordAdded: "timeline-record-added", - TimesUpdated: "timeline-times-updated" -}; - -WebInspector.Timeline.prototype = { - constructor: WebInspector.Timeline, - __proto__: WebInspector.Object.prototype, - - // Public - - get startTime() - { - return this._startTime; - }, - - get endTime() - { - return this._endTime; - }, - - get records() - { - return this._records; - }, - - reset: function(suppressEvents) - { - this._records = []; - this._startTime = NaN; - this._endTime = NaN; - - if (!suppressEvents) { - this.dispatchEventToListeners(WebInspector.Timeline.Event.Reset); - this.dispatchEventToListeners(WebInspector.Timeline.Event.TimesUpdated); - } - }, - - addRecord: function(record) - { - if (record.updatesDynamically) - record.addEventListener(WebInspector.TimelineRecord.Event.Updated, this._recordUpdated, this); - - this._records.push(record); - - this._updateTimesIfNeeded(record); - - this.dispatchEventToListeners(WebInspector.Timeline.Event.RecordAdded, {record: record}); - }, - - // Private - - _updateTimesIfNeeded: function(record) - { - var changed = false; - - if (isNaN(this._startTime) || record.startTime < this._startTime) { - this._startTime = record.startTime; - changed = true; - } - - if (isNaN(this._endTime) || this._endTime < record.endTime) { - this._endTime = record.endTime; - changed = true; - } - - if (changed) - this.dispatchEventToListeners(WebInspector.Timeline.Event.TimesUpdated); - }, - - _recordUpdated: function(event) - { - this._updateTimesIfNeeded(event.target); - } -}; diff --git a/Source/WebInspectorUI/UserInterface/TimelineContentView.css b/Source/WebInspectorUI/UserInterface/TimelineContentView.css deleted file mode 100644 index 9cbc0df22..000000000 --- a/Source/WebInspectorUI/UserInterface/TimelineContentView.css +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.content-view.timeline > .timeline-overview { - position: absolute; - top: 0; - left: 0; - right: 0; - height: 130px; -} - -.content-view.timeline > .view-container { - position: absolute; - top: 130px; - left: 0; - right: 0; - bottom: 0; - overflow: hidden; -} - -.content-view.timeline > .view-container > .timeline-view > .data-grid td { - height: 16px; - line-height: 16px; -} - -.content-view.timeline > .view-container > .timeline-view > .data-grid table.data { - background-image: -webkit-linear-gradient(top, white, white 50%, rgb(243, 243, 243) 50%, rgb(243, 243, 243)); - background-size: 100% 40px; -} diff --git a/Source/WebInspectorUI/UserInterface/TimelineContentView.js b/Source/WebInspectorUI/UserInterface/TimelineContentView.js deleted file mode 100644 index 200c2c207..000000000 --- a/Source/WebInspectorUI/UserInterface/TimelineContentView.js +++ /dev/null @@ -1,417 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.TimelineContentView = function(recording) -{ - WebInspector.ContentView.call(this, recording); - - this._recording = recording; - - this.element.classList.add(WebInspector.TimelineContentView.StyleClassName); - - this._discreteTimelineOverviewGraphMap = new Map; - this._discreteTimelineOverviewGraphMap.set(WebInspector.TimelineRecord.Type.Network, new WebInspector.NetworkTimelineOverviewGraph(recording)); - this._discreteTimelineOverviewGraphMap.set(WebInspector.TimelineRecord.Type.Layout, new WebInspector.LayoutTimelineOverviewGraph(recording)); - this._discreteTimelineOverviewGraphMap.set(WebInspector.TimelineRecord.Type.Script, new WebInspector.ScriptTimelineOverviewGraph(recording)); - - this._timelineOverview = new WebInspector.TimelineOverview(this._discreteTimelineOverviewGraphMap); - this._timelineOverview.addEventListener(WebInspector.TimelineOverview.Event.TimeRangeSelectionChanged, this._timeRangeSelectionChanged, this); - this.element.appendChild(this._timelineOverview.element); - - this._viewContainer = document.createElement("div"); - this._viewContainer.classList.add(WebInspector.TimelineContentView.ViewContainerStyleClassName); - this.element.appendChild(this._viewContainer); - - this._clearTimelineNavigationItem = new WebInspector.ButtonNavigationItem("clear-timeline", WebInspector.UIString("Clear Timeline"), "Images/NavigationItemTrash.svg", 16, 16); - this._clearTimelineNavigationItem.addEventListener(WebInspector.ButtonNavigationItem.Event.Clicked, this._clearTimeline, this); - - this._overviewTimelineView = new WebInspector.OverviewTimelineView(recording); - - this._discreteTimelineViewMap = new Map; - this._discreteTimelineViewMap.set(WebInspector.TimelineRecord.Type.Network, new WebInspector.NetworkTimelineView(recording)); - this._discreteTimelineViewMap.set(WebInspector.TimelineRecord.Type.Layout, new WebInspector.LayoutTimelineView(recording)); - this._discreteTimelineViewMap.set(WebInspector.TimelineRecord.Type.Script, new WebInspector.ScriptTimelineView(recording)); - - function createPathComponent(displayName, className, representedObject) - { - var pathComponent = new WebInspector.HierarchicalPathComponent(displayName, className, representedObject); - pathComponent.addEventListener(WebInspector.HierarchicalPathComponent.Event.SiblingWasSelected, this._pathComponentSelected, this); - return pathComponent; - } - - this._pathComponentMap = new Map; - this._pathComponentMap.set(WebInspector.TimelineRecord.Type.Network, createPathComponent.call(this, WebInspector.UIString("Network Requests"), WebInspector.TimelineSidebarPanel.NetworkIconStyleClass, WebInspector.TimelineRecord.Type.Network)); - this._pathComponentMap.set(WebInspector.TimelineRecord.Type.Layout, createPathComponent.call(this, WebInspector.UIString("Layout & Rendering"), WebInspector.TimelineSidebarPanel.ColorsIconStyleClass, WebInspector.TimelineRecord.Type.Layout)); - this._pathComponentMap.set(WebInspector.TimelineRecord.Type.Script, createPathComponent.call(this, WebInspector.UIString("JavaScript & Events"), WebInspector.TimelineSidebarPanel.ScriptIconStyleClass, WebInspector.TimelineRecord.Type.Script)); - - var previousPathComponent = null; - for (var pathComponent of this._pathComponentMap.values()) { - if (previousPathComponent) { - previousPathComponent.nextSibling = pathComponent; - pathComponent.previousSibling = previousPathComponent; - } - - previousPathComponent = pathComponent; - } - - this._currentTimelineView = null; - this._currentTimelineViewIdentifier = null; - - this._updating = false; - this._currentTime = NaN; - this._lastUpdateTimestamp = NaN; - this._startTimeNeedsReset = true; - - recording.addEventListener(WebInspector.TimelineRecording.Event.Reset, this._recordingReset, this); - - WebInspector.timelineManager.addEventListener(WebInspector.TimelineManager.Event.RecordingStarted, this._recordingStarted, this); - WebInspector.timelineManager.addEventListener(WebInspector.TimelineManager.Event.RecordingStopped, this._recordingStopped, this); - - this.showOverviewTimelineView(); -}; - -WebInspector.TimelineContentView.StyleClassName = "timeline"; -WebInspector.TimelineContentView.ViewContainerStyleClassName = "view-container"; - -WebInspector.TimelineContentView.prototype = { - constructor: WebInspector.TimelineContentView, - __proto__: WebInspector.ContentView.prototype, - - // Public - - showOverviewTimelineView: function() - { - this._showTimelineView(this._overviewTimelineView); - }, - - showTimelineView: function(identifier) - { - console.assert(this._discreteTimelineViewMap.has(identifier)); - if (!this._discreteTimelineViewMap.has(identifier)) - return; - - this._showTimelineView(this._discreteTimelineViewMap.get(identifier), identifier); - }, - - get allowedNavigationSidebarPanels() - { - return ["timeline"]; - }, - - get supportsSplitContentBrowser() - { - // The layout of the overview and split content browser don't work well. - return false; - }, - - get selectionPathComponents() - { - var pathComponents = this._currentTimelineViewIdentifier ? [this._pathComponentMap.get(this._currentTimelineViewIdentifier)] : []; - pathComponents = pathComponents.concat(this._currentTimelineView.selectionPathComponents || []); - return pathComponents; - }, - - get navigationItems() - { - return [this._clearTimelineNavigationItem]; - }, - - shown: function() - { - if (!this._currentTimelineView) - return; - - this._currentTimelineView.shown(); - }, - - hidden: function() - { - if (!this._currentTimelineView) - return; - - this._currentTimelineView.hidden(); - }, - - updateLayout: function() - { - this._timelineOverview.updateLayout(); - - if (!this._currentTimelineView) - return; - - this._currentTimelineView.updateLayout(); - }, - - matchTreeElementAgainstCustomFilters: function(treeElement) - { - if (this._currentTimelineView && !this._currentTimelineView.matchTreeElementAgainstCustomFilters(treeElement)) - return false; - - var startTime = this._timelineOverview.selectionStartTime; - var endTime = this._timelineOverview.selectionStartTime + this._timelineOverview.selectionDuration; - var currentTime = this._currentTime || this._recording.startTime; - - function checkTimeBounds(itemStartTime, itemEndTime) - { - itemStartTime = itemStartTime || currentTime; - itemEndTime = itemEndTime || currentTime; - - return startTime <= itemEndTime && itemStartTime <= endTime; - } - - if (treeElement instanceof WebInspector.ResourceTreeElement) { - var resource = treeElement.resource; - return checkTimeBounds(resource.requestSentTimestamp, resource.finishedOrFailedTimestamp); - } - - if (treeElement instanceof WebInspector.SourceCodeTimelineTreeElement) { - var sourceCodeTimeline = treeElement.sourceCodeTimeline; - - // Do a quick check of the timeline bounds before we check each record. - if (!checkTimeBounds(sourceCodeTimeline.startTime, sourceCodeTimeline.endTime)) - return false; - - for (var record of sourceCodeTimeline.records) { - if (checkTimeBounds(record.startTime, record.endTime)) - return true; - } - - return false; - } - - if (treeElement instanceof WebInspector.TimelineRecordTreeElement) { - var record = treeElement.record; - return checkTimeBounds(record.startTime, record.endTime); - } - - console.error("Unknown TreeElement, can't filter by time."); - return true; - }, - - // Private - - _pathComponentSelected: function(event) - { - WebInspector.timelineSidebarPanel.showTimelineView(event.data.pathComponent.representedObject); - }, - - _timelineViewSelectionPathComponentsDidChange: function() - { - this.dispatchEventToListeners(WebInspector.ContentView.Event.SelectionPathComponentsDidChange); - }, - - _showTimelineView: function(timelineView, identifier) - { - console.assert(timelineView instanceof WebInspector.TimelineView); - - if (this._currentTimelineView === timelineView) - return; - - if (this._currentTimelineView) { - this._currentTimelineView.removeEventListener(WebInspector.TimelineView.Event.SelectionPathComponentsDidChange, this._timelineViewSelectionPathComponentsDidChange, this); - - this._currentTimelineView.hidden(); - this._currentTimelineView.element.remove(); - } - - this._currentTimelineView = timelineView; - this._currentTimelineViewIdentifier = identifier || null; - - WebInspector.timelineSidebarPanel.contentTreeOutline = timelineView && timelineView.navigationSidebarTreeOutline; - WebInspector.timelineSidebarPanel.contentTreeOutlineLabel = timelineView && timelineView.navigationSidebarTreeOutlineLabel; - - if (this._currentTimelineView) { - this._currentTimelineView.addEventListener(WebInspector.TimelineView.Event.SelectionPathComponentsDidChange, this._timelineViewSelectionPathComponentsDidChange, this); - - this._viewContainer.appendChild(this._currentTimelineView.element); - - this._currentTimelineView.startTime = this._timelineOverview.selectionStartTime; - this._currentTimelineView.endTime = this._timelineOverview.selectionStartTime + this._timelineOverview.selectionDuration; - this._currentTimelineView.currentTime = this._currentTime; - - this._currentTimelineView.shown(); - this._currentTimelineView.updateLayout(); - } - - this.dispatchEventToListeners(WebInspector.ContentView.Event.SelectionPathComponentsDidChange); - }, - - _update: function(timestamp) - { - if (this._waitingToResetCurrentTime) { - requestAnimationFrame(this._updateCallback); - return; - } - - var startTime = this._recording.startTime; - var currentTime = this._currentTime || startTime; - var endTime = this._recording.endTime; - var timespanSinceLastUpdate = (timestamp - this._lastUpdateTimestamp) / 1000 || 0; - - currentTime += timespanSinceLastUpdate; - - this._updateTimes(startTime, currentTime, endTime); - - // Only stop updating if the current time is greater than the end time. - if (!this._updating && currentTime >= endTime) { - this._lastUpdateTimestamp = NaN; - return; - } - - this._lastUpdateTimestamp = timestamp; - - requestAnimationFrame(this._updateCallback); - }, - - _updateTimes: function(startTime, currentTime, endTime) - { - if (this._startTimeNeedsReset && !isNaN(startTime)) { - var selectionOffset = this._timelineOverview.selectionStartTime - this._timelineOverview.startTime; - - this._timelineOverview.startTime = startTime; - this._timelineOverview.selectionStartTime = startTime + selectionOffset; - - this._overviewTimelineView.zeroTime = startTime; - for (var timelineView of this._discreteTimelineViewMap.values()) - timelineView.zeroTime = startTime; - - delete this._startTimeNeedsReset; - } - - this._timelineOverview.endTime = Math.max(endTime, currentTime); - - this._currentTime = currentTime; - this._timelineOverview.currentTime = currentTime; - this._currentTimelineView.currentTime = currentTime; - - // Force a layout now since we are already in an animation frame and don't need to delay it until the next. - this._timelineOverview.updateLayoutIfNeeded(); - this._currentTimelineView.updateLayoutIfNeeded(); - }, - - _startUpdatingCurrentTime: function() - { - console.assert(!this._updating); - if (this._updating) - return; - - if (!isNaN(this._currentTime)) { - // We have a current time already, so we likely need to jump into the future to a better current time. - // This happens when you stop and later restart recording. - this._waitingToResetCurrentTime = true; - this._recording.addEventListener(WebInspector.TimelineRecording.Event.TimesUpdated, this._recordingTimesUpdated, this); - } - - this._updating = true; - - if (!this._updateCallback) - this._updateCallback = this._update.bind(this); - - requestAnimationFrame(this._updateCallback); - }, - - _stopUpdatingCurrentTime: function() - { - console.assert(this._updating); - this._updating = false; - }, - - _recordingStarted: function(event) - { - this._startUpdatingCurrentTime(); - }, - - _recordingStopped: function(event) - { - this._stopUpdatingCurrentTime(); - }, - - _recordingTimesUpdated: function(event) - { - if (!this._waitingToResetCurrentTime) - return; - - // Make the current time be the start time of the last added record. This is the best way - // currently to jump to the right period of time after recording starts. - // FIXME: If no activity is happening we can sit for a while until a record is added. - // We might want to have the backend send a "start" record to get current time moving. - - for (var timeline of this._recording.timelines.values()) { - var lastRecord = timeline.records.lastValue; - if (!lastRecord) - continue; - this._currentTime = Math.max(this._currentTime, lastRecord.startTime); - } - - this._recording.removeEventListener(WebInspector.TimelineRecording.Event.TimesUpdated, this._recordingTimesUpdated, this); - delete this._waitingToResetCurrentTime; - }, - - _clearTimeline: function(event) - { - this._recording.reset(); - }, - - _recordingReset: function(event) - { - this._currentTime = NaN; - - if (!this._updating) { - // Force the time ruler and views to reset to 0. - this._startTimeNeedsReset = true; - this._updateTimes(0, 0, 0); - } - - this._lastUpdateTimestamp = NaN; - this._startTimeNeedsReset = true; - - this._recording.removeEventListener(WebInspector.TimelineRecording.Event.TimesUpdated, this._recordingTimesUpdated, this); - delete this._waitingToResetCurrentTime; - - this._overviewTimelineView.reset(); - for (var timelineView of this._discreteTimelineViewMap.values()) - timelineView.reset(); - - for (var timelineOverviewGraph of this._discreteTimelineOverviewGraphMap.values()) - timelineOverviewGraph.reset(); - }, - - _timeRangeSelectionChanged: function(event) - { - this._currentTimelineView.startTime = this._timelineOverview.selectionStartTime; - this._currentTimelineView.endTime = this._timelineOverview.selectionStartTime + this._timelineOverview.selectionDuration; - - // Delay until the next frame to stay in sync with the current timeline view's time-based layout changes. - requestAnimationFrame(function() { - var selectedTreeElement = this._currentTimelineView && this._currentTimelineView.navigationSidebarTreeOutline ? this._currentTimelineView.navigationSidebarTreeOutline.selectedTreeElement : null; - var selectionWasHidden = selectedTreeElement && selectedTreeElement.hidden; - - WebInspector.timelineSidebarPanel.updateFilter(); - - if (selectedTreeElement && selectedTreeElement.hidden !== selectionWasHidden) - this.dispatchEventToListeners(WebInspector.ContentView.Event.SelectionPathComponentsDidChange); - }.bind(this)); - } -}; diff --git a/Source/WebInspectorUI/UserInterface/TimelineDataGrid.css b/Source/WebInspectorUI/UserInterface/TimelineDataGrid.css deleted file mode 100644 index 7a987b08f..000000000 --- a/Source/WebInspectorUI/UserInterface/TimelineDataGrid.css +++ /dev/null @@ -1,273 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.data-grid.timeline { - border: none; -} - -.data-grid.timeline table { - font-size: 11px; -} - -.data-grid.timeline th { - height: 22px; - - font-size: 11px; - font-family: "Lucida Grande", sans-serif; - - background-image: none; - background-color: white; - - border-top: 1px solid rgb(179, 179, 179) !important; - border-bottom: 1px solid rgb(179, 179, 179) !important; -} - -.data-grid.timeline th:not(:last-child) { - border-right: 1px solid rgb(179, 179, 179); -} - -.data-grid.timeline th.sortable:active { - background-image: none !important; - background-color: rgb(210, 210, 210); -} - -.data-grid.timeline th.sort-ascending, -.data-grid.timeline th.sort-descending { - background-image: none !important; - background-color: rgb(230, 230, 230); -} - -.data-grid.timeline .data-container { - top: 23px; -} - -.data-grid.timeline th, -.data-grid.timeline td { - padding-left: 6px; - padding-right: 6px; -} - -.data-grid.timeline td:last-child { - padding-right: 12px; -} - -.data-grid.timeline td { - padding-top: 2px; - padding-bottom: 2px; - line-height: 17px; -} - -.data-grid.timeline td:not(:last-child) { - border-right: 1px solid rgb(179, 179, 179); -} - -.data-grid.timeline:focus tr.selected td:not(:last-child) { - border-right-color: rgb(53, 109, 189); -} - -.data-grid.timeline th.sort-ascending > div:first-child, -.data-grid.timeline th.sort-descending > div:first-child { - padding-right: 13px; -} - -.data-grid.timeline th.sort-ascending > div:first-child::after, -.data-grid.timeline th.sort-descending > div:first-child::after { - top: 1px; -} - -.data-grid.timeline td.error { - color: rgb(224, 16, 16); -} - -.data-grid.timeline tr.selected td.error { - color: inherit; -} - -.data-grid.timeline td .icon { - display: inline-block; - vertical-align: top; - - width: 16px; - height: 16px; - - margin-right: 2px; -} - -.data-grid.timeline td .go-to-arrow { - float: right; - - visibility: hidden; - - margin-left: 2px; -} - -.data-grid.timeline tr.selected .go-to-arrow, -.data-grid.timeline tr:hover .go-to-arrow { - visibility: visible; -} - -.data-grid.timeline td .subtitle { - color: rgba(0, 0, 0, 0.7); -} - -.data-grid.timeline td .subtitle::before { - content: " — "; -} - -.data-grid.timeline:focus tr.selected td .subtitle { - color: rgba(255, 255, 255, 0.9); -} - -.data-grid.timeline > .navigation-bar-container { - position: absolute; - bottom: 0; - left: 0; - right: 0; - height: 32px; - - pointer-events: none; - visibility: hidden; -} - -.data-grid.timeline:hover > .navigation-bar-container { - pointer-events: all; - visibility: visible; -} - -.data-grid.timeline > .navigation-bar-container > .navigation-bar { - position: absolute; - top: 10px; - left: 0; - right: 0; - height: 22px; - - border-bottom: none; - border-top: 1px solid rgb(200, 200, 200); - box-shadow: none; - - background-color: white; -} - -.timeline-data-grid-tree-outline { - position: relative; - padding: 0; - margin: 0; - outline: none; - list-style: none; - font-family: "Lucida Grande", "Helvetica", sans-serif; - font-size: 11px; -} - -.timeline-data-grid-tree-outline .item { - position: relative; - height: 36px; - line-height: 34px; - padding: 0 5px; - border-top: 1px solid transparent; - white-space: nowrap; -} - -.timeline-data-grid-tree-outline > .children, -.timeline-data-grid-tree-outline .disclosure-button, -.timeline-data-grid-tree-outline .item .status { - display: none; -} - -.timeline-data-grid-tree-outline .item .icon { - float: left; - width: 32px; - height: 32px; - margin-top: 1px; - margin-right: 3px; -} - -.timeline-data-grid-tree-outline .item:hover { - color: white; - border-radius: 4px; - box-shadow: inset rgb(87, 152, 206) 0 1px 0; - background: -webkit-linear-gradient(top, rgb(110, 167, 216), rgb(36, 114, 181)); - background-origin: padding-box; - background-clip: padding-box; - text-shadow: rgb(51, 88, 123) 0 1px 0; - -webkit-text-stroke: 0.4px; -} - -.timeline-data-grid-tree-outline .item .titles { - position: relative; - top: 5px; - line-height: 11px; - padding-bottom: 1px; - text-overflow: ellipsis; - overflow: hidden; - white-space: nowrap; -} - -.timeline-data-grid-tree-outline .item .title::after { - content: "\A"; /* Newline */ - white-space: pre; -} - -.timeline-data-grid-tree-outline .item .subtitle { - font-size: 9px; - color: rgba(0, 0, 0, 0.7); -} - -.timeline-data-grid-tree-outline .item:hover .subtitle { - color: white; -} - -.timeline-data-grid-tree-outline .item .subtitle:empty { - display: none; -} - -.timeline-data-grid-tree-outline .item.small { - height: 20px; -} - -.timeline-data-grid-tree-outline .item.small .icon { - width: 16px; - height: 16px; -} - -.timeline-data-grid-tree-outline .item.small .status { - margin-top: 1px; -} - -.timeline-data-grid-tree-outline .item.small .titles { - top: 2px; - line-height: normal; -} - -.timeline-data-grid-tree-outline .item.small .subtitle { - font-size: inherit; -} - -.timeline-data-grid-tree-outline .item.small:not(.two-line) .title::after { - content: ""; -} - -.timeline-data-grid-tree-outline .item.small:not(.two-line) .subtitle::before { - content: " — "; -} diff --git a/Source/WebInspectorUI/UserInterface/TimelineDataGrid.js b/Source/WebInspectorUI/UserInterface/TimelineDataGrid.js deleted file mode 100644 index cd47d1209..000000000 --- a/Source/WebInspectorUI/UserInterface/TimelineDataGrid.js +++ /dev/null @@ -1,459 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.TimelineDataGrid = function(treeOutline, columns, editCallback, deleteCallback) -{ - WebInspector.DataGrid.call(this, columns, editCallback, deleteCallback); - - this._treeOutlineDataGridSynchronizer = new WebInspector.TreeOutlineDataGridSynchronizer(treeOutline, this); - - this.element.classList.add(WebInspector.TimelineDataGrid.StyleClassName); - - this._filterableColumns = []; - - // Check if any of the cells can be filtered. - for (var identifier in columns) { - var scopeBar = columns[identifier].scopeBar; - if (!scopeBar) - continue; - this._filterableColumns.push(identifier); - scopeBar.columnIdenfifier = identifier; - scopeBar.addEventListener(WebInspector.ScopeBar.Event.SelectionChanged, this._scopeBarSelectedItemsDidChange, this); - } - - if (this._filterableColumns.length > 1) { - console.error("Creating a TimelineDataGrid with more than one filterable column is not yet supported."); - return; - } - - if (this._filterableColumns.length) { - var items = [new WebInspector.FlexibleSpaceNavigationItem, this.columns[this._filterableColumns[0]].scopeBar, new WebInspector.FlexibleSpaceNavigationItem]; - this._navigationBar = new WebInspector.NavigationBar(null, items); - var container = this.element.appendChild(document.createElement("div")); - container.className = "navigation-bar-container"; - container.appendChild(this._navigationBar.element); - } - - this.addEventListener(WebInspector.DataGrid.Event.SelectedNodeChanged, this._dataGridSelectedNodeChanged, this); - this.addEventListener(WebInspector.DataGrid.Event.SortChanged, this._sort, this); - - window.addEventListener("resize", this._windowResized.bind(this)); -} - -WebInspector.TimelineDataGrid.StyleClassName = "timeline"; -WebInspector.TimelineDataGrid.DelayedPopoverShowTimeout = 250; -WebInspector.TimelineDataGrid.DelayedPopoverHideContentClearTimeout = 500; - -WebInspector.TimelineDataGrid.Event = { - FiltersDidChange: "timelinedatagrid-filters-did-change" -}; - -WebInspector.TimelineDataGrid.createColumnScopeBar = function(prefix, dictionary) -{ - prefix = prefix + "-timeline-data-grid-"; - - var keys = Object.keys(dictionary).filter(function(key) { - return typeof dictionary[key] === "string" || dictionary[key] instanceof String; - }); - - var scopeBarItems = keys.map(function(key) { - var value = dictionary[key]; - var id = prefix + value; - var label = dictionary.displayName(value, true); - var item = new WebInspector.ScopeBarItem(id, label); - item.value = value; - return item; - }); - - scopeBarItems.unshift(new WebInspector.ScopeBarItem(prefix + "type-all", WebInspector.UIString("All"), true)); - - return new WebInspector.ScopeBar(prefix + "scope-bar", scopeBarItems, scopeBarItems[0]); -}; - -WebInspector.TimelineDataGrid.prototype = { - constructor: WebInspector.TimelineDataGrid, - __proto__: WebInspector.DataGrid.prototype, - - // Public - - reset: function() - { - // May be overridden by subclasses. If so, they should call the superclass. - - this._hidePopover(); - }, - - shown: function() - { - // May be overridden by subclasses. If so, they should call the superclass. - - this._treeOutlineDataGridSynchronizer.synchronize(); - }, - - hidden: function() - { - // May be overridden by subclasses. If so, they should call the superclass. - - this._hidePopover(); - }, - - treeElementForDataGridNode: function(dataGridNode) - { - return this._treeOutlineDataGridSynchronizer.treeElementForDataGridNode(dataGridNode); - }, - - dataGridNodeForTreeElement: function(treeElement) - { - return this._treeOutlineDataGridSynchronizer.dataGridNodeForTreeElement(treeElement); - }, - - callFramePopoverAnchorElement: function() - { - // Implemented by subclasses. - return null; - }, - - updateLayout: function() - { - WebInspector.DataGrid.prototype.updateLayout.call(this); - - if (this._navigationBar) - this._navigationBar.updateLayout(); - }, - - treeElementMatchesActiveScopeFilters: function(treeElement) - { - var dataGridNode = this._treeOutlineDataGridSynchronizer.dataGridNodeForTreeElement(treeElement); - console.assert(dataGridNode); - - for (var identifier of this._filterableColumns) { - var scopeBar = this.columns[identifier].scopeBar; - if (!scopeBar || scopeBar.defaultItem.selected) - continue; - - var value = dataGridNode.data[identifier]; - var matchesFilter = scopeBar.selectedItems.some(function(scopeBarItem) { - return scopeBarItem.value === value; - }); - - if (!matchesFilter) - return false; - } - - return true; - }, - - addRowInSortOrder: function(treeElement, dataGridNode) - { - this._treeOutlineDataGridSynchronizer.associate(treeElement, dataGridNode); - - var treeOutline = this._treeOutlineDataGridSynchronizer.treeOutline; - - if (this.sortColumnIdentifier) { - var insertionIndex = insertionIndexForObjectInListSortedByFunction(dataGridNode, this.children, this._sortComparator.bind(this)); - - // Insert into the tree outline, which will cause the synchronizer to insert into the data grid. - treeOutline.insertChild(treeElement, insertionIndex); - } else { - // Append to the tree outline, which will cause the synchronizer to append to the data grid. - treeOutline.appendChild(treeElement); - } - }, - - shouldIgnoreSelectionEvent: function() - { - return this._ignoreSelectionEvent || false; - }, - - // Protected - - dataGridNodeNeedsRefresh: function(dataGridNode) - { - if (!this._dirtyDataGridNodes) - this._dirtyDataGridNodes = new Set; - this._dirtyDataGridNodes.add(dataGridNode); - - if (this._scheduledDataGridNodeRefreshIdentifier) - return; - - this._scheduledDataGridNodeRefreshIdentifier = requestAnimationFrame(this._refreshDirtyDataGridNodes.bind(this)); - }, - - // Private - - _refreshDirtyDataGridNodes: function() - { - if (this._scheduledDataGridNodeRefreshIdentifier) { - cancelAnimationFrame(this._scheduledDataGridNodeRefreshIdentifier); - delete this._scheduledDataGridNodeRefreshIdentifier; - } - - if (!this._dirtyDataGridNodes) - return; - - var selectedNode = this.selectedNode; - var sortComparator = this._sortComparator.bind(this); - var treeOutline = this._treeOutlineDataGridSynchronizer.treeOutline; - - this._treeOutlineDataGridSynchronizer.enabled = false; - - for (var dataGridNode of this._dirtyDataGridNodes) { - dataGridNode.refresh(); - - if (!this.sortColumnIdentifier) - continue; - - if (dataGridNode === selectedNode) - this._ignoreSelectionEvent = true; - - var treeElement = this._treeOutlineDataGridSynchronizer.treeElementForDataGridNode(dataGridNode); - console.assert(treeElement); - - treeOutline.removeChild(treeElement); - this.removeChild(dataGridNode); - - var insertionIndex = insertionIndexForObjectInListSortedByFunction(dataGridNode, this.children, sortComparator); - treeOutline.insertChild(treeElement, insertionIndex); - this.insertChild(dataGridNode, insertionIndex); - - // Adding the tree element back to the tree outline subjects it to filters. - // Make sure we keep the hidden state in-sync while the synchronizer is disabled. - dataGridNode.element.classList.toggle("hidden", treeElement.hidden); - - if (dataGridNode === selectedNode) { - selectedNode.revealAndSelect(); - delete this._ignoreSelectionEvent; - } - } - - this._treeOutlineDataGridSynchronizer.enabled = true; - - delete this._dirtyDataGridNodes; - }, - - _sort: function() - { - var sortColumnIdentifier = this.sortColumnIdentifier; - if (!sortColumnIdentifier) - return; - - var selectedNode = this.selectedNode; - this._ignoreSelectionEvent = true; - - var dataGridNodes = this.children.slice(); - dataGridNodes.sort(this._sortComparator.bind(this)); - - this._treeOutlineDataGridSynchronizer.enabled = false; - - var treeOutline = this._treeOutlineDataGridSynchronizer.treeOutline; - - this.removeChildren(); - treeOutline.removeChildren(); - - for (var dataGridNode of dataGridNodes) { - var treeElement = this._treeOutlineDataGridSynchronizer.treeElementForDataGridNode(dataGridNode); - console.assert(treeElement); - - treeOutline.appendChild(treeElement); - this.appendChild(dataGridNode); - - // Adding the tree element back to the tree outline subjects it to filters. - // Make sure we keep the hidden state in-sync while the synchronizer is disabled. - dataGridNode.element.classList.toggle("hidden", treeElement.hidden); - } - - this._treeOutlineDataGridSynchronizer.enabled = true; - - if (selectedNode) - selectedNode.revealAndSelect(); - - delete this._ignoreSelectionEvent; - }, - - _sortComparator: function(node1, node2) - { - var sortColumnIdentifier = this.sortColumnIdentifier; - if (!sortColumnIdentifier) - return 0; - - var sortDirection = this.sortOrder === "ascending" ? 1 : -1; - - var value1 = node1.data[sortColumnIdentifier]; - var value2 = node2.data[sortColumnIdentifier]; - - if (typeof value1 === "number" && typeof value2 === "number") { - if (isNaN(value1) && isNaN(value2)) - return 0; - if (isNaN(value1)) - return -sortDirection; - if (isNaN(value2)) - return sortDirection; - return (value1 - value2) * sortDirection; - } - - if (typeof value1 === "string" && typeof value2 === "string") - return value1.localeCompare(value2) * sortDirection; - - if (value1 instanceof WebInspector.CallFrame || value2 instanceof WebInspector.CallFrame) { - // Sort by function name if available, then fall back to the source code object. - value1 = value1 && value1.functionName ? value1.functionName : (value1 && value1.sourceCodeLocation ? value1.sourceCodeLocation.sourceCode : ""); - value2 = value2 && value2.functionName ? value2.functionName : (value2 && value2.sourceCodeLocation ? value2.sourceCodeLocation.sourceCode : ""); - } - - if (value1 instanceof WebInspector.SourceCode || value2 instanceof WebInspector.SourceCode) { - value1 = value1 ? value1.displayName || "" : ""; - value2 = value2 ? value2.displayName || "" : ""; - } - - // For everything else (mostly booleans). - return (value1 < value2 ? -1 : (value1 > value2 ? 1 : 0)) * sortDirection; - }, - - _scopeBarSelectedItemsDidChange: function(event) - { - var columnIdentifier = event.target.columnIdenfifier; - this.dispatchEventToListeners(WebInspector.TimelineDataGrid.Event.FiltersDidChange, {columnIdentifier: columnIdentifier}); - }, - - _dataGridSelectedNodeChanged: function(event) - { - if (!this.selectedNode) { - this._hidePopover(); - return; - } - - var record = this.selectedNode.record; - if (!record || !record.callFrames || !record.callFrames.length) { - this._hidePopover(); - return; - } - - this._showPopoverForSelectedNodeSoon(); - }, - - _windowResized: function(event) - { - if (this._popover && this._popover.visible) - this._updatePopoverForSelectedNode(false); - }, - - _showPopoverForSelectedNodeSoon: function() - { - if (this._showPopoverTimeout) - return; - - function delayedWork() - { - if (!this._popover) - this._popover = new WebInspector.Popover; - - this._updatePopoverForSelectedNode(true); - } - - this._showPopoverTimeout = setTimeout(delayedWork.bind(this), WebInspector.TimelineDataGrid.DelayedPopoverShowTimeout); - }, - - _hidePopover: function() - { - if (this._showPopoverTimeout) { - clearTimeout(this._showPopoverTimeout); - delete this._showPopoverTimeout; - } - - if (this._popover) - this._popover.dismiss(); - - function delayedWork() - { - if (this._popoverCallStackTreeOutline) - this._popoverCallStackTreeOutline.removeChildren(); - } - - if (this._hidePopoverContentClearTimeout) - clearTimeout(this._hidePopoverContentClearTimeout); - this._hidePopoverContentClearTimeout = setTimeout(delayedWork.bind(this), WebInspector.TimelineDataGrid.DelayedPopoverHideContentClearTimeout); - }, - - _updatePopoverForSelectedNode: function(updateContent) - { - if (!this._popover || !this.selectedNode) - return; - - var targetPopoverElement = this.callFramePopoverAnchorElement(); - console.assert(targetPopoverElement, "TimelineDataGrid subclass should always return a valid element from callFramePopoverAnchorElement."); - if (!targetPopoverElement) - return; - - var targetFrame = WebInspector.Rect.rectFromClientRect(targetPopoverElement.getBoundingClientRect()); - - // The element might be hidden if it does not have a width and height. - if (!targetFrame.size.width && !targetFrame.size.height) - return; - - if (this._hidePopoverContentClearTimeout) { - clearTimeout(this._hidePopoverContentClearTimeout); - delete this._hidePopoverContentClearTimeout; - } - - if (updateContent) - this._popover.content = this._createPopoverContent(); - - this._popover.present(targetFrame.pad(2), [WebInspector.RectEdge.MAX_Y, WebInspector.RectEdge.MIN_Y, WebInspector.RectEdge.MAX_X]); - }, - - _createPopoverContent: function() - { - if (!this._popoverCallStackTreeOutline) { - var contentElement = document.createElement("ol"); - contentElement.classList.add("timeline-data-grid-tree-outline"); - this._popoverCallStackTreeOutline = new TreeOutline(contentElement); - this._popoverCallStackTreeOutline.onselect = this._popoverCallStackTreeElementSelected.bind(this); - } else - this._popoverCallStackTreeOutline.removeChildren(); - - var callFrames = this.selectedNode.record.callFrames; - for (var i = 0 ; i < callFrames.length; ++i) { - var callFrameTreeElement = new WebInspector.CallFrameTreeElement(callFrames[i]); - this._popoverCallStackTreeOutline.appendChild(callFrameTreeElement); - } - - var content = document.createElement("div"); - content.className = "timeline-data-grid-popover"; - content.appendChild(this._popoverCallStackTreeOutline.element); - return content; - }, - - _popoverCallStackTreeElementSelected: function(treeElement, selectedByUser) - { - this._popover.dismiss(); - - console.assert(treeElement instanceof WebInspector.CallFrameTreeElement, "TreeElements in TimelineDataGrid popover should always be CallFrameTreeElements"); - var callFrame = treeElement.callFrame; - if (!callFrame.sourceCodeLocation) - return; - - WebInspector.resourceSidebarPanel.showSourceCodeLocation(callFrame.sourceCodeLocation); - } -}; diff --git a/Source/WebInspectorUI/UserInterface/TimelineDataGridNode.js b/Source/WebInspectorUI/UserInterface/TimelineDataGridNode.js deleted file mode 100644 index 572af145d..000000000 --- a/Source/WebInspectorUI/UserInterface/TimelineDataGridNode.js +++ /dev/null @@ -1,346 +0,0 @@ -/* - * Copyright (C) 2014 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.TimelineDataGridNode = function(graphOnly, graphDataSource) -{ - WebInspector.DataGridNode.call(this, {}); - - this._graphOnly = graphOnly || false; - this._graphDataSource = graphDataSource || null; - - if (graphDataSource) { - this._graphContainerElement = document.createElement("div"); - this._timelineRecordBars = []; - } -}; - -WebInspector.Object.addConstructorFunctions(WebInspector.TimelineDataGridNode); - -WebInspector.TimelineDataGridNode.prototype = { - constructor: WebInspector.TimelineDataGridNode, - __proto__: WebInspector.DataGridNode.prototype, - - // Public - - get records() - { - // Implemented by subclasses. - return []; - }, - - get graphDataSource() - { - return this._graphDataSource; - }, - - get data() - { - if (!this._graphDataSource) - return {}; - - var records = this.records || []; - return {graph: records.length ? records[0].startTime : 0}; - }, - - collapse: function() - { - WebInspector.DataGridNode.prototype.collapse.call(this); - - if (!this.revealed) - return; - - // Refresh to show child bars in our graph now that we collapsed. - this.refreshGraph(); - }, - - expand: function() - { - WebInspector.DataGridNode.prototype.expand.call(this); - - if (!this.revealed) - return; - - // Refresh to remove child bars from our graph now that we expanded. - this.refreshGraph(); - - // Refresh child graphs since they haven't been updating while we were collapsed. - var childNode = this.children[0]; - while (childNode) { - if (childNode instanceof WebInspector.TimelineDataGridNode) - childNode.refreshGraph(); - childNode = childNode.traverseNextNode(true, this); - } - }, - - createCellContent: function(columnIdentifier, cell) - { - if (columnIdentifier === "graph" && this._graphDataSource) { - this.needsGraphRefresh(); - return this._graphContainerElement; - } - - var value = this.data[columnIdentifier]; - if (!value) - return "\u2014"; - - if (value instanceof WebInspector.SourceCodeLocation) { - if (value.sourceCode instanceof WebInspector.Resource) { - cell.classList.add(WebInspector.ResourceTreeElement.ResourceIconStyleClassName); - cell.classList.add(value.sourceCode.type); - } else if (value.sourceCode instanceof WebInspector.Script) { - if (value.sourceCode.url) { - cell.classList.add(WebInspector.ResourceTreeElement.ResourceIconStyleClassName); - cell.classList.add(WebInspector.Resource.Type.Script); - } else - cell.classList.add(WebInspector.ScriptTreeElement.AnonymousScriptIconStyleClassName); - } else - console.error("Unknown SourceCode subclass."); - - // Give the whole cell a tooltip and keep it up to date. - value.populateLiveDisplayLocationTooltip(cell); - - var fragment = document.createDocumentFragment(); - - var goToArrowButtonLink = WebInspector.createSourceCodeLocationLink(value, false, true); - fragment.appendChild(goToArrowButtonLink); - - var icon = document.createElement("div"); - icon.className = WebInspector.ScriptTimelineDataGridNode.IconStyleClassName; - fragment.appendChild(icon); - - var titleElement = document.createElement("span"); - value.populateLiveDisplayLocationString(titleElement, "textContent"); - fragment.appendChild(titleElement); - - return fragment; - } - - if (value instanceof WebInspector.CallFrame) { - var callFrame = value; - - var isAnonymousFunction = false; - var functionName = callFrame.functionName; - if (!functionName) { - functionName = WebInspector.UIString("(anonymous function)"); - isAnonymousFunction = true; - } - - cell.classList.add(WebInspector.CallFrameTreeElement.FunctionIconStyleClassName); - - var fragment = document.createDocumentFragment(); - - if (callFrame.sourceCodeLocation && callFrame.sourceCodeLocation.sourceCode) { - // Give the whole cell a tooltip and keep it up to date. - callFrame.sourceCodeLocation.populateLiveDisplayLocationTooltip(cell); - - var goToArrowButtonLink = WebInspector.createSourceCodeLocationLink(callFrame.sourceCodeLocation, false, true); - fragment.appendChild(goToArrowButtonLink); - - var icon = document.createElement("div"); - icon.className = WebInspector.LayoutTimelineDataGridNode.IconStyleClassName; - fragment.appendChild(icon); - - if (isAnonymousFunction) { - // For anonymous functions we show the resource or script icon and name. - if (callFrame.sourceCodeLocation.sourceCode instanceof WebInspector.Resource) { - cell.classList.add(WebInspector.ResourceTreeElement.ResourceIconStyleClassName); - cell.classList.add(callFrame.sourceCodeLocation.sourceCode.type); - } else if (callFrame.sourceCodeLocation.sourceCode instanceof WebInspector.Script) { - if (callFrame.sourceCodeLocation.sourceCode.url) { - cell.classList.add(WebInspector.ResourceTreeElement.ResourceIconStyleClassName); - cell.classList.add(WebInspector.Resource.Type.Script); - } else - cell.classList.add(WebInspector.ScriptTreeElement.AnonymousScriptIconStyleClassName); - } else - console.error("Unknown SourceCode subclass."); - - var titleElement = document.createElement("span"); - callFrame.sourceCodeLocation.populateLiveDisplayLocationString(titleElement, "textContent"); - - fragment.appendChild(titleElement); - } else { - // Show the function name and icon. - cell.classList.add(WebInspector.CallFrameTreeElement.FunctionIconStyleClassName); - - fragment.appendChild(document.createTextNode(functionName)); - - var subtitleElement = document.createElement("span"); - subtitleElement.className = WebInspector.LayoutTimelineDataGridNode.SubtitleStyleClassName; - callFrame.sourceCodeLocation.populateLiveDisplayLocationString(subtitleElement, "textContent"); - - fragment.appendChild(subtitleElement); - } - - return fragment; - } - - var icon = document.createElement("div"); - icon.className = WebInspector.LayoutTimelineDataGridNode.IconStyleClassName; - fragment.appendChild(icon); - - fragment.appendChild(document.createTextNode(functionName)); - - return fragment; - } - - return WebInspector.DataGridNode.prototype.createCellContent.call(this, columnIdentifier, cell); - }, - - refresh: function() - { - if (this._graphDataSource && this._graphOnly) { - this.needsGraphRefresh(); - return; - } - - WebInspector.DataGridNode.prototype.refresh.call(this); - }, - - refreshGraph: function() - { - if (!this._graphDataSource) - return; - - if (this._scheduledGraphRefreshIdentifier) { - cancelAnimationFrame(this._scheduledGraphRefreshIdentifier); - delete this._scheduledGraphRefreshIdentifier; - } - - // We are not visible, but an ancestor will draw our graph. - // They need notified by using our needsGraphRefresh. - console.assert(this.revealed); - if (!this.revealed) - return; - - var startTime = this._graphDataSource.startTime; - var currentTime = this._graphDataSource.currentTime; - var endTime = this._graphDataSource.endTime; - var duration = endTime - startTime; - var visibleWidth = this._graphContainerElement.offsetWidth; - var secondsPerPixel = duration / visibleWidth; - var recordBarIndex = 0; - - function createBar(records, renderMode) - { - var timelineRecordBar = this._timelineRecordBars[recordBarIndex]; - if (!timelineRecordBar) - timelineRecordBar = this._timelineRecordBars[recordBarIndex] = new WebInspector.TimelineRecordBar; - timelineRecordBar.renderMode = renderMode; - timelineRecordBar.records = records; - timelineRecordBar.refresh(this._graphDataSource); - if (!timelineRecordBar.element.parentNode) - this._graphContainerElement.appendChild(timelineRecordBar.element); - ++recordBarIndex; - } - - var boundCreateBar = createBar.bind(this); - - if (this.expanded) { - // When expanded just use the records for this node. - WebInspector.TimelineRecordBar.createCombinedBars(this.records, secondsPerPixel, this._graphDataSource, boundCreateBar); - } else { - // When collapsed use the records for this node and its descendants. - // To share bars better, group records by type. - - var recordTypeMap = new Map; - - function collectRecordsByType(records) - { - for (var record of records) { - var typedRecords = recordTypeMap.get(record.type); - if (!typedRecords) { - typedRecords = []; - recordTypeMap.set(record.type, typedRecords); - } - - typedRecords.push(record); - } - } - - collectRecordsByType(this.records); - - var childNode = this.children[0]; - while (childNode) { - if (childNode instanceof WebInspector.TimelineDataGridNode) - collectRecordsByType(childNode.records); - childNode = childNode.traverseNextNode(false, this); - } - - for (var records of recordTypeMap.values()) - WebInspector.TimelineRecordBar.createCombinedBars(records, secondsPerPixel, this._graphDataSource, boundCreateBar); - } - - // Remove the remaining unused TimelineRecordBars. - for (; recordBarIndex < this._timelineRecordBars.length; ++recordBarIndex) { - this._timelineRecordBars[recordBarIndex].records = null; - this._timelineRecordBars[recordBarIndex].element.remove(); - } - }, - - needsGraphRefresh: function() - { - if (!this.revealed) { - // We are not visible, but an ancestor will be drawing our graph. - // Notify the next visible ancestor that their graph needs to refresh. - var ancestor = this; - while (ancestor && !ancestor.root) { - if (ancestor.revealed && ancestor instanceof WebInspector.TimelineDataGridNode) { - ancestor.needsGraphRefresh(); - return; - } - - ancestor = ancestor.parent; - } - - return; - } - - if (!this._graphDataSource || this._scheduledGraphRefreshIdentifier) - return; - - this._scheduledGraphRefreshIdentifier = requestAnimationFrame(this.refreshGraph.bind(this)); - }, - - // Protected - - isRecordVisible: function(record) - { - if (!this._graphDataSource) - return false; - - if (isNaN(record.startTime)) - return false; - - // If this bar is completely before the bounds of the graph, not visible. - if (record.endTime < this.graphDataSource.startTime) - return false; - - // If this record is completely after the current time or end time, not visible. - if (record.startTime > this.graphDataSource.currentTime || record.startTime > this.graphDataSource.endTime) - return false; - - return true; - } -}; diff --git a/Source/WebInspectorUI/UserInterface/TimelineIcons.css b/Source/WebInspectorUI/UserInterface/TimelineIcons.css deleted file mode 100644 index 640a37839..000000000 --- a/Source/WebInspectorUI/UserInterface/TimelineIcons.css +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.network-icon .icon { - content: -webkit-image-set(url(Images/Network.png) 1x, url(Images/Network@2x.png) 2x); -} - -.network-icon.large .icon { - content: -webkit-image-set(url(Images/NetworkLarge.png) 1x, url(Images/NetworkLarge@2x.png) 2x); -} - -.colors-icon .icon { - content: -webkit-image-set(url(Images/Colors.png) 1x, url(Images/Colors@2x.png) 2x); -} - -.colors-icon.large .icon { - content: -webkit-image-set(url(Images/ColorsLarge.png) 1x, url(Images/ColorsLarge@2x.png) 2x); -} - -.script-icon .icon { - content: -webkit-image-set(url(Images/Script.png) 1x, url(Images/Script@2x.png) 2x); -} - -.script-icon.large .icon { - content: -webkit-image-set(url(Images/ScriptLarge.png) 1x, url(Images/ScriptLarge@2x.png) 2x); -} - -.stopwatch-icon .icon { - content: -webkit-image-set(url(Images/Stopwatch.png) 1x, url(Images/Stopwatch@2x.png) 2x); -} - -.profile-icon .icon { - content: -webkit-image-set(url(Images/Profile.png) 1x, url(Images/Profile@2x.png) 2x); -} - -.style-record .icon { - content: url(Images/TimelineRecordStyle.svg); -} - -.layout-record .icon { - content: url(Images/TimelineRecordLayout.svg); -} - -.paint-record .icon { - content: url(Images/TimelineRecordPaint.svg); -} - -.evaluated-record .icon { - content: url(Images/TimelineRecordScriptEvaluated.svg); -} - -.event-record .icon { - content: url(Images/TimelineRecordEvent.svg); -} - -.timer-record .icon { - content: url(Images/TimelineRecordTimer.svg); -} - -.animation-record .icon { - content: url(Images/TimelineRecordAnimation.svg); -} diff --git a/Source/WebInspectorUI/UserInterface/TimelineManager.js b/Source/WebInspectorUI/UserInterface/TimelineManager.js deleted file mode 100644 index 0bea0c7f8..000000000 --- a/Source/WebInspectorUI/UserInterface/TimelineManager.js +++ /dev/null @@ -1,445 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.TimelineManager = function() -{ - WebInspector.Object.call(this); - - WebInspector.Frame.addEventListener(WebInspector.Frame.Event.ProvisionalLoadStarted, this._startAutoRecording, this); - WebInspector.Frame.addEventListener(WebInspector.Frame.Event.MainResourceDidChange, this._mainResourceDidChange, this); - WebInspector.Frame.addEventListener(WebInspector.Frame.Event.ResourceWasAdded, this._resourceWasAdded, this); - - this._recording = new WebInspector.TimelineRecording; - this._recordingEnabled = false; -}; - -WebInspector.TimelineManager.Event = { - RecordingStarted: "timeline-manager-recording-started", - RecordingStopped: "timeline-manager-recording-stopped" -}; - -WebInspector.TimelineManager.MaximumAutoRecordDuration = 90000; // 90 seconds -WebInspector.TimelineManager.MaximumAutoRecordDurationAfterLoadEvent = 10000; // 10 seconds -WebInspector.TimelineManager.DeadTimeRequiredToStopAutoRecordingEarly = 2000; // 2 seconds - -WebInspector.TimelineManager.prototype = { - constructor: WebInspector.TimelineManager, - - // Public - - get recording() - { - return this._recording; - }, - - get recordingEnabled() - { - return this._recordingEnabled; - }, - - startRecording: function() - { - if (this._recordingEnabled) - return; - - this._recordingEnabled = true; - - TimelineAgent.start(); - - this.dispatchEventToListeners(WebInspector.TimelineManager.Event.RecordingStarted); - }, - - stopRecording: function() - { - if (!this._recordingEnabled) - return; - - if (this._stopRecordingTimeout) { - clearTimeout(this._stopRecordingTimeout); - delete this._stopRecordingTimeout; - } - - if (this._deadTimeTimeout) { - clearTimeout(this._deadTimeTimeout); - delete this._deadTimeTimeout; - } - - TimelineAgent.stop(); - - this._recordingEnabled = false; - this._autoRecordingMainResource = null; - - this.dispatchEventToListeners(WebInspector.TimelineManager.Event.RecordingStopped); - }, - - eventRecorded: function(originalRecordPayload) - { - // Called from WebInspector.TimelineObserver. - - if (!this._recordingEnabled) - return; - - function processRecord(recordPayload, parentRecordPayload) - { - // Convert the timestamps to seconds to match the resource timestamps. - var startTime = recordPayload.startTime / 1000; - var endTime = recordPayload.endTime / 1000; - - var callFrames = this._callFramesFromPayload(recordPayload.stackTrace); - - var significantCallFrame = null; - if (callFrames) { - for (var i = 0; i < callFrames.length; ++i) { - if (callFrames[i].nativeCode) - continue; - significantCallFrame = callFrames[i]; - break; - } - } - - var sourceCodeLocation = significantCallFrame && significantCallFrame.sourceCodeLocation; - - switch (recordPayload.type) { - case TimelineAgent.EventType.MarkLoad: - console.assert(isNaN(endTime)); - - var frame = WebInspector.frameResourceManager.frameForIdentifier(recordPayload.frameId); - console.assert(frame); - if (!frame) - break; - - frame.markLoadEvent(startTime); - - if (!frame.isMainFrame()) - break; - - var eventMarker = new WebInspector.TimelineMarker(startTime, WebInspector.TimelineMarker.Type.LoadEvent); - this._recording.addEventMarker(eventMarker); - - this._stopAutoRecordingSoon(); - break; - - case TimelineAgent.EventType.MarkDOMContent: - console.assert(isNaN(endTime)); - - var frame = WebInspector.frameResourceManager.frameForIdentifier(recordPayload.frameId); - console.assert(frame); - if (!frame) - break; - - frame.markDOMContentReadyEvent(startTime); - - if (!frame.isMainFrame()) - break; - - var eventMarker = new WebInspector.TimelineMarker(startTime, WebInspector.TimelineMarker.Type.DOMContentEvent); - this._recording.addEventMarker(eventMarker); - break; - - case TimelineAgent.EventType.ScheduleStyleRecalculation: - console.assert(isNaN(endTime)); - - // Pass the startTime as the endTime since this record type has no duration. - this._addRecord(new WebInspector.LayoutTimelineRecord(WebInspector.LayoutTimelineRecord.EventType.InvalidateStyles, startTime, startTime, callFrames, sourceCodeLocation)); - break; - - case TimelineAgent.EventType.RecalculateStyles: - this._addRecord(new WebInspector.LayoutTimelineRecord(WebInspector.LayoutTimelineRecord.EventType.RecalculateStyles, startTime, endTime, callFrames, sourceCodeLocation)); - break; - - case TimelineAgent.EventType.InvalidateLayout: - console.assert(isNaN(endTime)); - - // Pass the startTime as the endTime since this record type has no duration. - this._addRecord(new WebInspector.LayoutTimelineRecord(WebInspector.LayoutTimelineRecord.EventType.InvalidateLayout, startTime, startTime, callFrames, sourceCodeLocation)); - break; - - case TimelineAgent.EventType.Layout: - // COMPATIBILITY (iOS 6): Layout records did not contain area properties. This is not exposed via a quad "root". - var quad = recordPayload.data.root ? new WebInspector.Quad(recordPayload.data.root) : null; - if (quad) - this._addRecord(new WebInspector.LayoutTimelineRecord(WebInspector.LayoutTimelineRecord.EventType.Layout, startTime, endTime, callFrames, sourceCodeLocation, quad.points[0].x, quad.points[0].y, quad.width, quad.height, quad)); - else - this._addRecord(new WebInspector.LayoutTimelineRecord(WebInspector.LayoutTimelineRecord.EventType.Layout, startTime, endTime, callFrames, sourceCodeLocation)); - break; - - case TimelineAgent.EventType.Paint: - // COMPATIBILITY (iOS 6): Paint records data contained x, y, width, height properties. This became a quad "clip". - var quad = recordPayload.data.clip ? new WebInspector.Quad(recordPayload.data.clip) : null; - if (quad) - this._addRecord(new WebInspector.LayoutTimelineRecord(WebInspector.LayoutTimelineRecord.EventType.Paint, startTime, endTime, callFrames, sourceCodeLocation, null, null, quad.width, quad.height, quad)); - else - this._addRecord(new WebInspector.LayoutTimelineRecord(WebInspector.LayoutTimelineRecord.EventType.Paint, startTime, endTime, callFrames, sourceCodeLocation, recordPayload.data.x, recordPayload.data.y, recordPayload.data.width, recordPayload.data.height)); - break; - - case TimelineAgent.EventType.EvaluateScript: - if (!sourceCodeLocation) { - var mainFrame = WebInspector.frameResourceManager.mainFrame; - var scriptResource = mainFrame.url === recordPayload.data.url ? mainFrame.mainResource : mainFrame.resourceForURL(recordPayload.data.url, true); - if (scriptResource) { - // The lineNumber is 1-based, but we expect 0-based. - var lineNumber = recordPayload.data.lineNumber - 1; - - // FIXME: No column number is provided. - sourceCodeLocation = scriptResource.createSourceCodeLocation(lineNumber, 0); - } - } - - switch (parentRecordPayload && parentRecordPayload.type) { - case TimelineAgent.EventType.TimerFire: - this._addRecord(new WebInspector.ScriptTimelineRecord(WebInspector.ScriptTimelineRecord.EventType.TimerFired, startTime, endTime, callFrames, sourceCodeLocation, parentRecordPayload.data.timerId)); - break; - default: - this._addRecord(new WebInspector.ScriptTimelineRecord(WebInspector.ScriptTimelineRecord.EventType.ScriptEvaluated, startTime, endTime, callFrames, sourceCodeLocation, null)); - break; - } - - break; - - case TimelineAgent.EventType.TimeStamp: - var eventMarker = new WebInspector.TimelineMarker(startTime, WebInspector.TimelineMarker.Type.TimeStamp); - this._recording.addEventMarker(eventMarker); - break; - - case TimelineAgent.EventType.FunctionCall: - // FunctionCall always happens as a child of another record, and since the FunctionCall record - // has useful info we just make the timeline record here (combining the data from both records). - if (!parentRecordPayload) - break; - - if (!sourceCodeLocation) { - var mainFrame = WebInspector.frameResourceManager.mainFrame; - var scriptResource = mainFrame.url === recordPayload.data.scriptName ? mainFrame.mainResource : mainFrame.resourceForURL(recordPayload.data.scriptName, true); - if (scriptResource) { - // The lineNumber is 1-based, but we expect 0-based. - var lineNumber = recordPayload.data.scriptLine - 1; - - // FIXME: No column number is provided. - sourceCodeLocation = scriptResource.createSourceCodeLocation(lineNumber, 0); - } - } - - switch (parentRecordPayload.type) { - case TimelineAgent.EventType.TimerFire: - this._addRecord(new WebInspector.ScriptTimelineRecord(WebInspector.ScriptTimelineRecord.EventType.TimerFired, startTime, endTime, callFrames, sourceCodeLocation, parentRecordPayload.data.timerId)); - break; - case TimelineAgent.EventType.EventDispatch: - this._addRecord(new WebInspector.ScriptTimelineRecord(WebInspector.ScriptTimelineRecord.EventType.EventDispatched, startTime, endTime, callFrames, sourceCodeLocation, parentRecordPayload.data.type)); - break; - case TimelineAgent.EventType.XHRLoad: - this._addRecord(new WebInspector.ScriptTimelineRecord(WebInspector.ScriptTimelineRecord.EventType.EventDispatched, startTime, endTime, callFrames, sourceCodeLocation, "load")); - break; - case TimelineAgent.EventType.XHRReadyStateChange: - this._addRecord(new WebInspector.ScriptTimelineRecord(WebInspector.ScriptTimelineRecord.EventType.EventDispatched, startTime, endTime, callFrames, sourceCodeLocation, "readystatechange")); - break; - case TimelineAgent.EventType.FireAnimationFrame: - this._addRecord(new WebInspector.ScriptTimelineRecord(WebInspector.ScriptTimelineRecord.EventType.AnimationFrameFired, startTime, endTime, callFrames, sourceCodeLocation, parentRecordPayload.data.id)); - break; - } - - break; - - case TimelineAgent.EventType.TimerInstall: - console.assert(isNaN(endTime)); - - // Pass the startTime as the endTime since this record type has no duration. - this._addRecord(new WebInspector.ScriptTimelineRecord(WebInspector.ScriptTimelineRecord.EventType.TimerInstalled, startTime, startTime, callFrames, sourceCodeLocation, recordPayload.data.timerId)); - break; - - case TimelineAgent.EventType.TimerRemove: - console.assert(isNaN(endTime)); - - // Pass the startTime as the endTime since this record type has no duration. - this._addRecord(new WebInspector.ScriptTimelineRecord(WebInspector.ScriptTimelineRecord.EventType.TimerRemoved, startTime, startTime, callFrames, sourceCodeLocation, recordPayload.data.timerId)); - break; - - case TimelineAgent.EventType.RequestAnimationFrame: - console.assert(isNaN(endTime)); - - // Pass the startTime as the endTime since this record type has no duration. - this._addRecord(new WebInspector.ScriptTimelineRecord(WebInspector.ScriptTimelineRecord.EventType.AnimationFrameRequested, startTime, startTime, callFrames, sourceCodeLocation, recordPayload.data.timerId)); - break; - - case TimelineAgent.EventType.CancelAnimationFrame: - console.assert(isNaN(endTime)); - - // Pass the startTime as the endTime since this record type has no duration. - this._addRecord(new WebInspector.ScriptTimelineRecord(WebInspector.ScriptTimelineRecord.EventType.AnimationFrameCanceled, startTime, startTime, callFrames, sourceCodeLocation, recordPayload.data.timerId)); - break; - } - } - - // Iterate over the records tree using a stack. Doing this recursively has - // been known to cause a call stack overflow. https://webkit.org/b/79106 - var stack = [{array: [originalRecordPayload], parent: null, index: 0}]; - while (stack.length) { - var entry = stack.lastValue; - var recordPayloads = entry.array; - var parentRecordPayload = entry.parent; - - if (entry.index < recordPayloads.length) { - var recordPayload = recordPayloads[entry.index]; - - processRecord.call(this, recordPayload, parentRecordPayload); - - if (recordPayload.children) - stack.push({array: recordPayload.children, parent: recordPayload, index: 0}); - ++entry.index; - } else - stack.pop(); - } - }, - - pageDidLoad: function(timestamp) - { - if (isNaN(WebInspector.frameResourceManager.mainFrame.loadEventTimestamp)) - WebInspector.frameResourceManager.mainFrame.markLoadEvent(timestamp); - }, - - // Private - - _callFramesFromPayload: function(payload) - { - if (!payload) - return null; - - function createCallFrame(payload) - { - var url = payload.url; - var nativeCode = false; - - if (url === "[native code]") { - nativeCode = true; - url = null; - } - - var sourceCode = WebInspector.frameResourceManager.resourceForURL(url); - if (!sourceCode) - sourceCode = WebInspector.debuggerManager.scriptsForURL(url)[0]; - - // The lineNumber is 1-based, but we expect 0-based. - var lineNumber = payload.lineNumber - 1; - - var sourceCodeLocation = sourceCode ? sourceCode.createSourceCodeLocation(lineNumber, payload.columnNumber) : null; - var functionName = payload.functionName !== "global code" ? payload.functionName : null; - - return new WebInspector.CallFrame(null, sourceCodeLocation, functionName, null, null, nativeCode); - } - - return payload.map(createCallFrame); - }, - - _addRecord: function(record) - { - this._recording.addRecord(record); - - // Only worry about dead time after the load event. - if (!isNaN(WebInspector.frameResourceManager.mainFrame.loadEventTimestamp)) - this._resetAutoRecordingDeadTimeTimeout(); - }, - - _startAutoRecording: function(event) - { - if (!event.target.isMainFrame() || (this._recordingEnabled && !this._autoRecordingMainResource)) - return false; - - var mainResource = event.target.provisionalMainResource || event.target.mainResource; - if (mainResource === this._autoRecordingMainResource) - return false; - - this.stopRecording(); - - this._autoRecordingMainResource = mainResource; - - this._recording.reset(); - - this.startRecording(); - - this._addRecord(new WebInspector.ResourceTimelineRecord(mainResource)); - - if (this._stopRecordingTimeout) - clearTimeout(this._stopRecordingTimeout); - this._stopRecordingTimeout = setTimeout(this.stopRecording.bind(this), WebInspector.TimelineManager.MaximumAutoRecordDuration); - - return true; - }, - - _stopAutoRecordingSoon: function() - { - // Only auto stop when auto recording. - if (!this._recordingEnabled || !this._autoRecordingMainResource) - return; - - if (this._stopRecordingTimeout) - clearTimeout(this._stopRecordingTimeout); - this._stopRecordingTimeout = setTimeout(this.stopRecording.bind(this), WebInspector.TimelineManager.MaximumAutoRecordDurationAfterLoadEvent); - }, - - _resetAutoRecordingDeadTimeTimeout: function() - { - // Only monitor dead time when auto recording. - if (!this._recordingEnabled || !this._autoRecordingMainResource) - return; - - if (this._deadTimeTimeout) - clearTimeout(this._deadTimeTimeout); - this._deadTimeTimeout = setTimeout(this.stopRecording.bind(this), WebInspector.TimelineManager.DeadTimeRequiredToStopAutoRecordingEarly); - }, - - _mainResourceDidChange: function(event) - { - // Ignore resource events when there isn't a main frame yet. Those events are triggered by - // loading the cached resources when the inspector opens, and they do not have timing information. - if (!WebInspector.frameResourceManager.mainFrame) - return; - - if (this._startAutoRecording(event)) - return; - - if (!this._recordingEnabled) - return; - - var mainResource = event.target.mainResource; - if (mainResource === this._autoRecordingMainResource) - return; - - this._addRecord(new WebInspector.ResourceTimelineRecord(mainResource)); - }, - - _resourceWasAdded: function(event) - { - // Ignore resource events when there isn't a main frame yet. Those events are triggered by - // loading the cached resources when the inspector opens, and they do not have timing information. - if (!WebInspector.frameResourceManager.mainFrame) - return; - - if (!this._recordingEnabled) - return; - - this._addRecord(new WebInspector.ResourceTimelineRecord(event.data.resource)); - } -}; - -WebInspector.TimelineManager.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/TimelineMarker.js b/Source/WebInspectorUI/UserInterface/TimelineMarker.js deleted file mode 100644 index 05e8339b2..000000000 --- a/Source/WebInspectorUI/UserInterface/TimelineMarker.js +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.TimelineMarker = function(time, type) -{ - WebInspector.Object.call(this); - - console.assert(type); - - this._time = time || 0; - this._type = type; -}; - -WebInspector.TimelineMarker.Event = { - TimeChanged: "timeline-marker-time-changed" -}; - -WebInspector.TimelineMarker.Type = { - CurrentTime: "current-time", - LoadEvent: "load-event", - DOMContentEvent: "dom-content-event", - TimeStamp: "timestamp" -}; - -WebInspector.TimelineMarker.prototype = { - constructor: WebInspector.TimelineMarker, - __proto__: WebInspector.Object.prototype, - - // Public - - get time() - { - return this._time; - }, - - set time(x) - { - if (this._time === x) - return; - - this._time = x || 0; - - this.dispatchEventToListeners(WebInspector.TimelineMarker.Event.TimeChanged); - }, - - get type() - { - return this._type; - } -}; diff --git a/Source/WebInspectorUI/UserInterface/TimelineObserver.js b/Source/WebInspectorUI/UserInterface/TimelineObserver.js deleted file mode 100644 index 1c7e0431f..000000000 --- a/Source/WebInspectorUI/UserInterface/TimelineObserver.js +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.TimelineObserver = function() -{ - WebInspector.Object.call(this); -}; - -WebInspector.TimelineObserver.prototype = { - constructor: WebInspector.TimelineObserver, - - // Events defined by the "Timeline" domain. - - eventRecorded: function(record) - { - WebInspector.timelineManager.eventRecorded(record); - } -}; - -WebInspector.TimelineObserver.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/TimelineOverview.css b/Source/WebInspectorUI/UserInterface/TimelineOverview.css deleted file mode 100644 index 225455dbe..000000000 --- a/Source/WebInspectorUI/UserInterface/TimelineOverview.css +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.timeline-overview > .scroll-container { - position: absolute; - left: 0; - right: 0; - bottom: 0; - height: 16px; - overflow-x: auto; - overflow-y: hidden; - opacity: 0; -} - -.timeline-overview:hover > .scroll-container { - opacity: 0.75; -} - -.timeline-overview > .scroll-container:hover { - opacity: 1; -} - -.timeline-overview > .timeline-ruler { - position: absolute; - top: 0; - left: 0; - bottom: 0; - right: 0; -} - -.timeline-overview > .graphs-container { - position: absolute; - top: 22px; - left: 0; - bottom: 0; - right: 0; -} - -.timeline-overview > .graphs-container > .timeline-overview-graph { - height: 36px; -} - -.timeline-overview > .graphs-container > .timeline-overview-graph:nth-child(even) { - background-color: rgb(247, 247, 247); - background-clip: padding-box; -} - -.timeline-overview > .graphs-container > .timeline-overview-graph:not(:first-child) { - border-top: 1px solid rgba(0, 0, 0, 0.09); -} - -.timeline-overview > .scroll-container > .scroll-width-sizer { - position: absolute; - top: 0; - left: 0; - height: 1px; - visibility: hidden; - pointer-events: none; -} diff --git a/Source/WebInspectorUI/UserInterface/TimelineOverview.js b/Source/WebInspectorUI/UserInterface/TimelineOverview.js deleted file mode 100644 index 7603f0b58..000000000 --- a/Source/WebInspectorUI/UserInterface/TimelineOverview.js +++ /dev/null @@ -1,346 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.TimelineOverview = function(timelineOverviewGraphsMap) -{ - WebInspector.Object.call(this); - - this._element = document.createElement("div"); - this._element.className = WebInspector.TimelineOverview.StyleClassName; - this._element.addEventListener("wheel", this._handleWheelEvent.bind(this)); - - this._graphsContainer = document.createElement("div"); - this._graphsContainer.className = WebInspector.TimelineOverview.GraphsContainerStyleClassName; - this._element.appendChild(this._graphsContainer); - - this._timelineOverviewGraphsMap = timelineOverviewGraphsMap; - - for (var timelineOverviewGraph of this._timelineOverviewGraphsMap.values()) - this._graphsContainer.appendChild(timelineOverviewGraph.element); - - this._timelineRuler = new WebInspector.TimelineRuler; - this._timelineRuler.allowsClippedLabels = true; - this._timelineRuler.allowsTimeRangeSelection = true; - this._timelineRuler.addEventListener(WebInspector.TimelineRuler.Event.TimeRangeSelectionChanged, this._timeRangeSelectionChanged, this); - this._element.appendChild(this._timelineRuler.element); - - this._currentTimeMarker = new WebInspector.TimelineMarker(0, WebInspector.TimelineMarker.Type.CurrentTime); - this._timelineRuler.addMarker(this._currentTimeMarker); - - this._scrollContainer = document.createElement("div"); - this._scrollContainer.className = WebInspector.TimelineOverview.ScrollContainerStyleClassName; - this._scrollContainer.addEventListener("scroll", this._handleScrollEvent.bind(this)); - this._element.appendChild(this._scrollContainer); - - this._scrollWidthSizer = document.createElement("div"); - this._scrollWidthSizer.className = WebInspector.TimelineOverview.ScrollWidthSizerStyleClassName; - this._scrollContainer.appendChild(this._scrollWidthSizer); - - this._secondsPerPixelSetting = new WebInspector.Setting("timeline-overview-seconds-per-pixel", 0.01); - this._selectionStartTimeSetting = new WebInspector.Setting("timeline-overview-selection-start-time", 0); - this._selectionDurationSetting = new WebInspector.Setting("timeline-overview-selection-duration", 5); - - this._startTime = 0; - this._currentTime = 0; - this._endTime = 0; - this._secondsPerPixel = this._secondsPerPixelSetting.value; - this._scrollStartTime = 0; - - this.selectionStartTime = this._selectionStartTimeSetting.value; - this.selectionDuration = this._selectionDurationSetting.value; -}; - -WebInspector.TimelineOverview.StyleClassName = "timeline-overview"; -WebInspector.TimelineOverview.GraphsContainerStyleClassName = "graphs-container"; -WebInspector.TimelineOverview.ScrollContainerStyleClassName = "scroll-container"; -WebInspector.TimelineOverview.ScrollWidthSizerStyleClassName = "scroll-width-sizer"; -WebInspector.TimelineOverview.MinimumSecondsPerPixel = 0.001; -WebInspector.TimelineOverview.ScrollDeltaDenominator = 500; - -WebInspector.TimelineOverview.Event = { - TimeRangeSelectionChanged: "timeline-overview-time-range-selection-changed" -}; - -WebInspector.TimelineOverview.prototype = { - constructor: WebInspector.TimelineOverview, - __proto__: WebInspector.Object.prototype, - - // Public - - get element() - { - return this._element; - }, - - get startTime() - { - return this._startTime; - }, - - set startTime(x) - { - if (this._startTime === x) - return; - - this._startTime = x || 0; - - this._needsLayout(); - }, - - get currentTime() - { - return this._currentTime; - }, - - set currentTime(x) - { - if (this._currentTime === x) - return; - - this._currentTime = x || 0; - this._revealCurrentTime = true; - - this._needsLayout(); - }, - - get secondsPerPixel() - { - return this._secondsPerPixel; - }, - - set secondsPerPixel(x) - { - x = Math.max(WebInspector.TimelineOverview.MinimumSecondsPerPixel, x); - - if (this._secondsPerPixel === x) - return; - - this._secondsPerPixel = x; - this._secondsPerPixelSetting.value = x; - - this._needsLayout(); - }, - - get endTime() - { - return this._endTime; - }, - - set endTime(x) - { - if (this._endTime === x) - return; - - this._endTime = x || 0; - - this._needsLayout(); - }, - - get scrollStartTime() - { - return this._scrollStartTime; - }, - - set scrollStartTime(x) - { - if (this._scrollStartTime === x) - return; - - this._scrollStartTime = x || 0; - - this._needsLayout(); - }, - - get visibleDuration() - { - return this._scrollContainer.offsetWidth * this._secondsPerPixel; - }, - - get selectionStartTime() - { - return this._timelineRuler.selectionStartTime; - }, - - set selectionStartTime(x) - { - x = x || 0; - - var selectionDuration = this.selectionDuration; - this._timelineRuler.selectionStartTime = x; - this._timelineRuler.selectionEndTime = x + selectionDuration; - }, - - get selectionDuration() - { - return this._timelineRuler.selectionEndTime - this._timelineRuler.selectionStartTime; - }, - - set selectionDuration(x) - { - x = Math.max(WebInspector.TimelineRuler.MinimumSelectionTimeRange, x); - this._timelineRuler.selectionEndTime = this._timelineRuler.selectionStartTime + x; - }, - - addMarker: function(marker) - { - this._timelineRuler.addMarker(marker); - }, - - revealMarker: function(marker) - { - this.scrollStartTime = marker.time - (this.visibleDuration / 2); - }, - - updateLayout: function() - { - if (this._scheduledLayoutUpdateIdentifier) { - cancelAnimationFrame(this._scheduledLayoutUpdateIdentifier); - delete this._scheduledLayoutUpdateIdentifier; - } - - // Calculate the required width based on the duration and seconds per pixel. - var duration = this._endTime - this._startTime; - var newWidth = Math.ceil(duration / this._secondsPerPixel); - - // Update all relevant elements to the new required width. - this._updateElementWidth(this._scrollWidthSizer, newWidth); - - this._currentTimeMarker.time = this._currentTime; - - if (this._revealCurrentTime) { - this.revealMarker(this._currentTimeMarker); - delete this._revealCurrentTime; - } - - // Clamp the scroll start time to match what the scroll bar would allow. - var scrollStartTime = Math.min(this._scrollStartTime, this._endTime - this.visibleDuration); - scrollStartTime = Math.max(this._startTime, scrollStartTime); - - this._timelineRuler.zeroTime = this._startTime; - this._timelineRuler.startTime = scrollStartTime; - this._timelineRuler.secondsPerPixel = this._secondsPerPixel; - - if (!this._dontUpdateScrollLeft) { - this._ignoreNextScrollEvent = true; - this._scrollContainer.scrollLeft = Math.ceil((scrollStartTime - this._startTime) / this._secondsPerPixel); - } - - this._timelineRuler.updateLayout(); - - for (var timelineOverviewGraph of this._timelineOverviewGraphsMap.values()) { - timelineOverviewGraph.zeroTime = this._startTime; - timelineOverviewGraph.startTime = scrollStartTime; - timelineOverviewGraph.currentTime = this._currentTime; - timelineOverviewGraph.endTime = scrollStartTime + this.visibleDuration; - timelineOverviewGraph.updateLayout(); - } - }, - - updateLayoutIfNeeded: function() - { - if (this._scheduledLayoutUpdateIdentifier) { - this.updateLayout(); - return; - } - - this._timelineRuler.updateLayoutIfNeeded(); - - for (var timelineOverviewGraph of this._timelineOverviewGraphsMap.values()) - timelineOverviewGraph.updateLayoutIfNeeded(); - }, - - // Private - - _updateElementWidth: function(element, newWidth) - { - var currentWidth = parseInt(element.style.width); - if (currentWidth !== newWidth) - element.style.width = newWidth + "px"; - }, - - _needsLayout: function() - { - if (this._scheduledLayoutUpdateIdentifier) - return; - this._scheduledLayoutUpdateIdentifier = requestAnimationFrame(this.updateLayout.bind(this)); - }, - - _handleScrollEvent: function(event) - { - if (this._ignoreNextScrollEvent) { - delete this._ignoreNextScrollEvent; - return; - } - - this._dontUpdateScrollLeft = true; - - var scrollOffset = this._scrollContainer.scrollLeft; - this.scrollStartTime = this._startTime + (scrollOffset * this._secondsPerPixel); - - // Force layout so we can update with the scroll position synchronously. - this.updateLayoutIfNeeded(); - - delete this._dontUpdateScrollLeft; - }, - - _handleWheelEvent: function(event) - { - // Ignore cloned events that come our way, we already handled the original. - if (event.__cloned) - return; - - // Require twice the vertical delta to overcome horizontal scrolling. This prevents most - // cases of inadvertent zooming for slightly diagonal scrolls. - if (Math.abs(event.deltaX) >= Math.abs(event.deltaY) * 0.5) { - // Clone the event to dispatch it on the scroll container. Mark it as cloned so we don't get into a loop. - var newWheelEvent = new event.constructor(event.type, event); - newWheelEvent.__cloned = true; - - this._scrollContainer.dispatchEvent(newWheelEvent); - return; - } - - // Remember the mouse position in time. - var mouseOffset = event.pageX - this._element.totalOffsetLeft; - var mousePositionTime = this._scrollStartTime + (mouseOffset * this._secondsPerPixel); - var deviceDirection = event.webkitDirectionInvertedFromDevice ? 1 : -1; - - this.secondsPerPixel += event.deltaY * (this._secondsPerPixel / WebInspector.TimelineOverview.ScrollDeltaDenominator) * deviceDirection; - - // Center the zoom around the mouse based on the remembered mouse position time. - this.scrollStartTime = mousePositionTime - (mouseOffset * this._secondsPerPixel); - - event.preventDefault(); - event.stopPropagation(); - }, - - _timeRangeSelectionChanged: function(event) - { - this._selectionStartTimeSetting.value = this.selectionStartTime - this._startTime; - this._selectionDurationSetting.value = this.selectionDuration; - - this.dispatchEventToListeners(WebInspector.TimelineOverview.Event.TimeRangeSelectionChanged); - } -}; diff --git a/Source/WebInspectorUI/UserInterface/TimelineOverviewGraph.js b/Source/WebInspectorUI/UserInterface/TimelineOverviewGraph.js deleted file mode 100644 index 232aa36ef..000000000 --- a/Source/WebInspectorUI/UserInterface/TimelineOverviewGraph.js +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright (C) 2014 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.TimelineOverviewGraph = function(recording) -{ - WebInspector.Object.call(this); - - this.element = document.createElement("div"); - this.element.classList.add(WebInspector.TimelineOverviewGraph.StyleClassName); - - this._zeroTime = 0; - this._startTime = 0; - this._endTime = 5; - this._currentTime = 0; -}; - -WebInspector.TimelineOverviewGraph.StyleClassName = "timeline-overview-graph"; - -WebInspector.TimelineOverviewGraph.prototype = { - constructor: WebInspector.TimelineOverviewGraph, - __proto__: WebInspector.Object.prototype, - - // Public - - get zeroTime() - { - return this._zeroTime; - }, - - set zeroTime(x) - { - if (this._zeroTime === x) - return; - - this._zeroTime = x || 0; - - this.needsLayout(); - }, - - get startTime() - { - return this._startTime; - }, - - set startTime(x) - { - if (this._startTime === x) - return; - - this._startTime = x || 0; - - this.needsLayout(); - }, - - get endTime() - { - return this._endTime; - }, - - set endTime(x) - { - if (this._endTime === x) - return; - - this._endTime = x || 0; - - this.needsLayout(); - }, - - get currentTime() - { - return this._currentTime; - }, - - set currentTime(x) - { - if (this._currentTime === x) - return; - - var oldCurrentTime = this._currentTime; - - this._currentTime = x || 0; - - if ((this._startTime <= oldCurrentTime && oldCurrentTime <= this._endTime) || (this._startTime <= this._currentTime && this._currentTime <= this._endTime)) - this.needsLayout(); - }, - - reset: function() - { - // Implemented by sub-classes if needed. - }, - - updateLayout: function() - { - if (this._scheduledLayoutUpdateIdentifier) { - cancelAnimationFrame(this._scheduledLayoutUpdateIdentifier); - delete this._scheduledLayoutUpdateIdentifier; - } - - // Implemented by sub-classes if needed. - }, - - updateLayoutIfNeeded: function() - { - if (!this._scheduledLayoutUpdateIdentifier) - return; - this.updateLayout(); - }, - - // Protected - - needsLayout: function() - { - if (this._scheduledLayoutUpdateIdentifier) - return; - - this._scheduledLayoutUpdateIdentifier = requestAnimationFrame(this.updateLayout.bind(this)); - } -}; diff --git a/Source/WebInspectorUI/UserInterface/TimelineRecord.js b/Source/WebInspectorUI/UserInterface/TimelineRecord.js deleted file mode 100644 index 66a176139..000000000 --- a/Source/WebInspectorUI/UserInterface/TimelineRecord.js +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.TimelineRecord = function(type, startTime, endTime, callFrames, sourceCodeLocation) -{ - WebInspector.Object.call(this); - - console.assert(type); - - if (type in WebInspector.TimelineRecord.Type) - type = WebInspector.TimelineRecord.Type[type]; - - this._type = type; - this._startTime = startTime || NaN; - this._endTime = endTime || NaN; - this._callFrames = callFrames || null; - this._sourceCodeLocation = sourceCodeLocation || null; -}; - -WebInspector.TimelineRecord.Event = { - Updated: "timeline-record-updated" -}; - -WebInspector.TimelineRecord.Type = { - Network: "timeline-record-type-network", - Layout: "timeline-record-type-layout", - Script: "timeline-record-type-script" -}; - -WebInspector.TimelineRecord.TypeIdentifier = "timeline-record"; -WebInspector.TimelineRecord.SourceCodeURLCookieKey = "timeline-record-source-code-url"; -WebInspector.TimelineRecord.SourceCodeLocationLineCookieKey = "timeline-record-source-code-location-line"; -WebInspector.TimelineRecord.SourceCodeLocationColumnCookieKey = "timeline-record-source-code-location-column"; -WebInspector.TimelineRecord.SourceCodeURLCookieKey = "timeline-record-source-code-url"; -WebInspector.TimelineRecord.TypeCookieKey = "timeline-record-type"; - -WebInspector.TimelineRecord.prototype = { - constructor: WebInspector.TimelineRecord, - - // Public - - get type() - { - return this._type; - }, - - get startTime() - { - // Implemented by subclasses if needed. - return this._startTime; - }, - - get activeStartTime() - { - // Implemented by subclasses if needed. - return this._startTime; - }, - - get endTime() - { - // Implemented by subclasses if needed. - return this._endTime; - }, - - get duration() - { - // Use the getters instead of the properties so this works for subclasses that override the getters. - return this.endTime - this.startTime; - }, - - get inactiveDuration() - { - // Use the getters instead of the properties so this works for subclasses that override the getters. - return this.activeStartTime - this.startTime; - }, - - get activeDuration() - { - // Use the getters instead of the properties so this works for subclasses that override the getters. - return this.endTime - this.activeStartTime; - }, - - get updatesDynamically() - { - // Implemented by subclasses if needed. - return false; - }, - - get usesActiveStartTime() - { - // Implemented by subclasses if needed. - return false; - }, - - get callFrames() - { - return this._callFrames; - }, - - get initiatorCallFrame() - { - if (!this._callFrames || !this._callFrames.length) - return null; - - // Return the first non-native code call frame as the initiator. - for (var i = 0; i < this._callFrames.length; ++i) { - if (this._callFrames[i].nativeCode) - continue; - return this._callFrames[i]; - } - - return null; - }, - - get sourceCodeLocation() - { - return this._sourceCodeLocation; - }, - - saveIdentityToCookie: function(cookie) - { - cookie[WebInspector.TimelineRecord.SourceCodeURLCookieKey] = this._sourceCodeLocation ? this._sourceCodeLocation.sourceCode.url ? this._sourceCodeLocation.sourceCode.url.hash : null : null; - cookie[WebInspector.TimelineRecord.SourceCodeLocationLineCookieKey] = this._sourceCodeLocation ? this._sourceCodeLocation.lineNumber : null; - cookie[WebInspector.TimelineRecord.SourceCodeLocationColumnCookieKey] = this._sourceCodeLocation ? this._sourceCodeLocation.columnNumber : null; - cookie[WebInspector.TimelineRecord.TypeCookieKey] = this._type || null; - } -}; - -WebInspector.TimelineRecord.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/TimelineRecordBar.css b/Source/WebInspectorUI/UserInterface/TimelineRecordBar.css deleted file mode 100644 index 2acd591dc..000000000 --- a/Source/WebInspectorUI/UserInterface/TimelineRecordBar.css +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (C) 2014 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.timeline-record-bar { - position: absolute; - height: 12px; -} - -.timeline-record-bar > .segment { - position: absolute; - height: 100%; - background-color: rgb(225, 225, 225); - border: 1px solid rgb(200, 200, 200); - border-radius: 3px; - min-width: 4px; - z-index: 1; -} - -.timeline-record-bar:not(.has-inactive-segment) > .segment { - left: 0; - width: 100%; -} - -.timeline-record-bar > .segment.inactive { - z-index: 0; -} - -.timeline-record-bar > .segment.inactive, -.timeline-record-bar.unfinished > .segment { - border-top-right-radius: 0 !important; - border-bottom-right-radius: 0 !important; - border-right: none; -} - -.timeline-record-bar.has-inactive-segment > .segment:not(.inactive) { - border-top-left-radius: 0 !important; - border-bottom-left-radius: 0 !important; -} - -:focus .selected .timeline-record-bar > .segment { - background-color: white !important; - border: none !important; -} - -:focus .selected .timeline-record-bar > .segment.inactive { - background-color: rgb(196, 215, 242) !important; -} - -:focus .selected .timeline-record-bar.has-inactive-segment > .segment:not(.inactive) { - border-left: 1px solid rgba(56, 121, 217, 0.7) !important; -} - -.timeline-record-bar.timeline-record-type-network > .segment { - background-color: rgb(120, 176, 225); - border-color: rgb(61, 147, 200); -} - -.timeline-record-bar.timeline-record-type-network > .segment.inactive { - background-color: rgb(167, 204, 237); - border-color: rgb(127, 185, 220); -} - -.timeline-record-bar.timeline-record-type-layout > .segment { - background-color: rgb(234, 153, 153); - border-color: rgb(212, 108, 108); -} - -.timeline-record-bar.timeline-record-type-script > .segment { - background-color: rgb(190, 148, 233); - border-color: rgb(153, 113, 185); -} diff --git a/Source/WebInspectorUI/UserInterface/TimelineRecordBar.js b/Source/WebInspectorUI/UserInterface/TimelineRecordBar.js deleted file mode 100644 index e04c1caa9..000000000 --- a/Source/WebInspectorUI/UserInterface/TimelineRecordBar.js +++ /dev/null @@ -1,346 +0,0 @@ -/* - * Copyright (C) 2014 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.TimelineRecordBar = function(records, renderMode) -{ - WebInspector.Object.call(this); - - this._element = document.createElement("div"); - this._element.classList.add(WebInspector.TimelineRecordBar.StyleClassName); - - this.renderMode = renderMode; - this.records = records; -}; - -WebInspector.Object.addConstructorFunctions(WebInspector.TimelineRecordBar); - -WebInspector.TimelineRecordBar.StyleClassName = "timeline-record-bar"; -WebInspector.TimelineRecordBar.BarSegmentStyleClassName = "segment"; -WebInspector.TimelineRecordBar.InactiveStyleClassName = "inactive"; -WebInspector.TimelineRecordBar.UnfinishedStyleClassName = "unfinished"; -WebInspector.TimelineRecordBar.HasInactiveSegmentStyleClassName = "has-inactive-segment"; -WebInspector.TimelineRecordBar.MinimumWidthPixels = 4; -WebInspector.TimelineRecordBar.MinimumMarginPixels = 1; - -WebInspector.TimelineRecordBar.RenderMode = { - Normal: "timeline-record-bar-normal-render-mode", - InactiveOnly: "timeline-record-bar-inactive-only-render-mode", - ActiveOnly: "timeline-record-bar-active-only-render-mode" -}; - -WebInspector.TimelineRecordBar.createCombinedBars = function(records, secondsPerPixel, graphDataSource, createBarCallback) -{ - if (!records.length) - return; - - var startTime = graphDataSource.startTime; - var currentTime = graphDataSource.currentTime; - var endTime = graphDataSource.endTime; - - var visibleRecords = []; - var usesActiveStartTime = false; - var lastRecordType = null; - - // FIXME: Do a binary search for records that fall inside start and current time. - - for (var record of records) { - if (isNaN(record.startTime)) - continue; - - // If this bar is completely before the bounds of the graph, skip this record. - if (record.endTime < startTime) - continue; - - // If this record is completely after the current time or end time, break out now. - // Records are sorted, so all records after this will be beyond the current or end time too. - if (record.startTime > currentTime || record.startTime > endTime) - break; - - if (record.usesActiveStartTime) - usesActiveStartTime = true; - - // If one record uses active time the rest are assumed to use it. - console.assert(record.usesActiveStartTime === usesActiveStartTime); - - // Only a single record type is supported right now. - console.assert(!lastRecordType || record.type === lastRecordType); - - visibleRecords.push(record); - - lastRecordType = record.type; - } - - if (!visibleRecords.length) - return; - - if (visibleRecords.length === 1) { - createBarCallback(visibleRecords, WebInspector.TimelineRecordBar.RenderMode.Normal); - return; - } - - function compareByActiveStartTime(a, b) - { - return a.activeStartTime - b.activeStartTime; - } - - var minimumDuration = secondsPerPixel * WebInspector.TimelineRecordBar.MinimumWidthPixels; - var minimumMargin = secondsPerPixel * WebInspector.TimelineRecordBar.MinimumMarginPixels; - - if (usesActiveStartTime) { - var inactiveStartTime = NaN; - var inactiveEndTime = NaN; - var inactiveRecords = []; - - for (var record of visibleRecords) { - // Check if the previous record is far enough away to create the inactive bar. - if (!isNaN(inactiveStartTime) && inactiveStartTime + Math.max(inactiveEndTime - inactiveStartTime, minimumDuration) + minimumMargin <= record.startTime) { - createBarCallback(inactiveRecords, WebInspector.TimelineRecordBar.RenderMode.InactiveOnly); - inactiveRecords = []; - inactiveStartTime = NaN; - inactiveEndTime = NaN; - } - - // If this is a new bar, peg the start time. - if (isNaN(inactiveStartTime)) - inactiveStartTime = record.startTime; - - // Update the end time to be the maximum we encounter. inactiveEndTime might be NaN, so "|| 0" to prevent Math.max from returning NaN. - inactiveEndTime = Math.max(inactiveEndTime || 0, record.activeStartTime); - - inactiveRecords.push(record); - } - - // Create the inactive bar for the last record if needed. - if (!isNaN(inactiveStartTime)) - createBarCallback(inactiveRecords, WebInspector.TimelineRecordBar.RenderMode.InactiveOnly); - - visibleRecords.sort(compareByActiveStartTime); - } - - lastRecordType = null; - - var activeStartTime = NaN; - var activeEndTime = NaN; - var activeRecords = []; - - var startTimeProperty = usesActiveStartTime ? "activeStartTime" : "startTime"; - - for (var record of visibleRecords) { - // Check if the previous record is far enough away to create the active bar. We also create it now if the current record has no active state time. - if (!isNaN(activeStartTime) && (activeStartTime + Math.max(activeEndTime - activeStartTime, minimumDuration) + minimumMargin <= record[startTimeProperty] - || (isNaN(record[startTimeProperty]) && !isNaN(activeEndTime)))) { - createBarCallback(activeRecords, WebInspector.TimelineRecordBar.RenderMode.ActiveOnly); - activeRecords = []; - activeStartTime = NaN; - activeEndTime = NaN; - } - - if (isNaN(record[startTimeProperty])) - continue; - - // If this is a new bar, peg the start time. - if (isNaN(activeStartTime)) - activeStartTime = record[startTimeProperty]; - - // Update the end time to be the maximum we encounter. activeEndTime might be NaN, so "|| 0" to prevent Math.max from returning NaN. - if (!isNaN(record.endTime)) - activeEndTime = Math.max(activeEndTime || 0, record.endTime); - - activeRecords.push(record); - } - - // Create the active bar for the last record if needed. - if (!isNaN(activeStartTime)) - createBarCallback(activeRecords, WebInspector.TimelineRecordBar.RenderMode.ActiveOnly); -}; - -WebInspector.TimelineRecordBar.prototype = { - constructor: WebInspector.TimelineRecordBar, - __proto__: WebInspector.Object.prototype, - - // Public - - get element() - { - return this._element; - }, - - get renderMode() - { - return this._renderMode; - }, - - set renderMode(renderMode) - { - this._renderMode = renderMode || WebInspector.TimelineRecordBar.RenderMode.Normal; - }, - - get records() - { - return this._records; - }, - - set records(records) - { - if (this._records && this._records.length) - this._element.classList.remove(this._records[0].type); - - records = records || []; - - if (!(records instanceof Array)) - records = [records]; - - this._records = records; - - // Assume all records are the same type. - if (this._records.length) - this._element.classList.add(this._records[0].type); - }, - - refresh: function(graphDataSource) - { - if (!this._records || !this._records.length) - return false; - - var firstRecord = this._records[0]; - var barStartTime = firstRecord.startTime; - - // If this bar has no time info, return early. - if (isNaN(barStartTime)) - return false; - - var graphStartTime = graphDataSource.startTime; - var graphEndTime = graphDataSource.endTime; - var graphCurrentTime = graphDataSource.currentTime; - - var barEndTime = this._records.reduce(function(previousValue, currentValue) { return Math.max(previousValue, currentValue.endTime); }, 0); - - // If this bar is completely after the current time, return early. - if (barStartTime > graphCurrentTime) - return false; - - // If this bar is completely before or after the bounds of the graph, return early. - if (barEndTime < graphStartTime || barStartTime > graphEndTime) - return false; - - var barUnfinished = isNaN(barEndTime) || barEndTime >= graphCurrentTime; - if (barUnfinished) - barEndTime = graphCurrentTime; - - var graphDuration = graphEndTime - graphStartTime; - - this._element.classList.toggle(WebInspector.TimelineRecordBar.UnfinishedStyleClassName, barUnfinished); - - var newBarLeftPosition = (barStartTime - graphStartTime) / graphDuration; - this._updateElementPosition(this._element, newBarLeftPosition, "left"); - - var newBarWidth = ((barEndTime - graphStartTime) / graphDuration) - newBarLeftPosition; - this._updateElementPosition(this._element, newBarWidth, "width"); - - if (!this._activeBarElement && this._renderMode !== WebInspector.TimelineRecordBar.RenderMode.InactiveOnly) { - this._activeBarElement = document.createElement("div"); - this._activeBarElement.classList.add(WebInspector.TimelineRecordBar.BarSegmentStyleClassName); - } - - if (!firstRecord.usesActiveStartTime) { - this._element.classList.remove(WebInspector.TimelineRecordBar.HasInactiveSegmentStyleClassName); - - if (this._inactiveBarElement) - this._inactiveBarElement.remove(); - - if (this._renderMode === WebInspector.TimelineRecordBar.RenderMode.InactiveOnly) { - if (this._activeBarElement) - this._activeBarElement.remove(); - - return false; - } - - // If this TimelineRecordBar is reused and had an inactive bar previously, clean it up. - this._activeBarElement.style.removeProperty("left"); - this._activeBarElement.style.removeProperty("width"); - - if (!this._activeBarElement.parentNode) - this._element.appendChild(this._activeBarElement); - - return true; - } - - this._element.classList.add(WebInspector.TimelineRecordBar.HasInactiveSegmentStyleClassName); - - // Find the earliest active start time for active only rendering, and the latest for the other modes. - // This matches the values that TimelineRecordBar.createCombinedBars uses when combining. - if (this._renderMode === WebInspector.TimelineRecordBar.RenderMode.ActiveOnly) - var barActiveStartTime = this._records.reduce(function(previousValue, currentValue) { return Math.min(previousValue, currentValue.activeStartTime); }, Infinity); - else - var barActiveStartTime = this._records.reduce(function(previousValue, currentValue) { return Math.max(previousValue, currentValue.activeStartTime); }, 0); - - var barDuration = barEndTime - barStartTime; - - var inactiveUnfinished = isNaN(barActiveStartTime) || barActiveStartTime >= graphCurrentTime; - this._element.classList.toggle(WebInspector.TimelineRecordBar.UnfinishedStyleClassName, inactiveUnfinished); - - if (inactiveUnfinished) - barActiveStartTime = graphCurrentTime; - - var middlePercentage = (barActiveStartTime - barStartTime) / barDuration; - - if (this._renderMode !== WebInspector.TimelineRecordBar.RenderMode.ActiveOnly) { - if (!this._inactiveBarElement) { - this._inactiveBarElement = document.createElement("div"); - this._inactiveBarElement.classList.add(WebInspector.TimelineRecordBar.BarSegmentStyleClassName); - this._inactiveBarElement.classList.add(WebInspector.TimelineRecordBar.InactiveStyleClassName); - } - - this._updateElementPosition(this._inactiveBarElement, 1 - middlePercentage, "right"); - this._updateElementPosition(this._inactiveBarElement, middlePercentage, "width"); - - if (!this._inactiveBarElement.parentNode) - this._element.insertBefore(this._inactiveBarElement, this._element.firstChild); - } - - if (!inactiveUnfinished && this._renderMode !== WebInspector.TimelineRecordBar.RenderMode.InactiveOnly) { - this._updateElementPosition(this._activeBarElement, middlePercentage, "left"); - this._updateElementPosition(this._activeBarElement, 1 - middlePercentage, "width"); - - if (!this._activeBarElement.parentNode) - this._element.appendChild(this._activeBarElement); - } else if (this._activeBarElement) - this._activeBarElement.remove(); - - return true; - }, - - // Private - - _updateElementPosition: function(element, newPosition, property) - { - newPosition *= 100; - newPosition = newPosition.toFixed(2); - - var currentPosition = parseFloat(element.style[property]).toFixed(2); - if (currentPosition !== newPosition) - element.style[property] = newPosition + "%"; - } -}; diff --git a/Source/WebInspectorUI/UserInterface/TimelineRecordTreeElement.js b/Source/WebInspectorUI/UserInterface/TimelineRecordTreeElement.js deleted file mode 100644 index 2d5c2aca5..000000000 --- a/Source/WebInspectorUI/UserInterface/TimelineRecordTreeElement.js +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Copyright (C) 2014 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.TimelineRecordTreeElement = function(timelineRecord, subtitleNameStyle, includeTimerIdentifierInMainTitle, sourceCodeLocation, representedObject) -{ - console.assert(timelineRecord); - - this._record = timelineRecord; - this._sourceCodeLocation = sourceCodeLocation || timelineRecord.sourceCodeLocation || null; - - var title = ""; - var subtitle = ""; - - if (this._sourceCodeLocation) { - subtitle = document.createElement("span"); - - if (subtitleNameStyle !== WebInspector.SourceCodeLocation.NameStyle.None) - this._sourceCodeLocation.populateLiveDisplayLocationString(subtitle, "textContent", null, subtitleNameStyle); - else - this._sourceCodeLocation.populateLiveDisplayLocationString(subtitle, "textContent", null, WebInspector.SourceCodeLocation.NameStyle.None, WebInspector.UIString("line ")); - } - - var iconStyleClass = null; - - switch (timelineRecord.type) { - case WebInspector.TimelineRecord.Type.Layout: - title = WebInspector.LayoutTimelineRecord.EventType.displayName(timelineRecord.eventType); - - switch (timelineRecord.eventType) { - case WebInspector.LayoutTimelineRecord.EventType.InvalidateStyles: - case WebInspector.LayoutTimelineRecord.EventType.RecalculateStyles: - iconStyleClass = WebInspector.TimelineRecordTreeElement.StyleRecordIconStyleClass; - break; - case WebInspector.LayoutTimelineRecord.EventType.InvalidateLayout: - case WebInspector.LayoutTimelineRecord.EventType.Layout: - iconStyleClass = WebInspector.TimelineRecordTreeElement.LayoutRecordIconStyleClass; - break; - case WebInspector.LayoutTimelineRecord.EventType.Paint: - iconStyleClass = WebInspector.TimelineRecordTreeElement.PaintRecordIconStyleClass; - break; - default: - console.error("Unknown LayoutTimelineRecord eventType: " + timelineRecord.eventType, timelineRecord); - } - - break; - - case WebInspector.TimelineRecord.Type.Script: - title = WebInspector.ScriptTimelineRecord.EventType.displayName(timelineRecord.eventType, timelineRecord.details, includeTimerIdentifierInMainTitle); - - switch (timelineRecord.eventType) { - case WebInspector.ScriptTimelineRecord.EventType.ScriptEvaluated: - iconStyleClass = WebInspector.TimelineRecordTreeElement.EvaluatedRecordIconStyleClass; - break; - case WebInspector.ScriptTimelineRecord.EventType.EventDispatched: - iconStyleClass = WebInspector.TimelineRecordTreeElement.EventRecordIconStyleClass; - break; - case WebInspector.ScriptTimelineRecord.EventType.TimerFired: - case WebInspector.ScriptTimelineRecord.EventType.TimerInstalled: - case WebInspector.ScriptTimelineRecord.EventType.TimerRemoved: - iconStyleClass = WebInspector.TimelineRecordTreeElement.TimerRecordIconStyleClass; - break; - case WebInspector.ScriptTimelineRecord.EventType.AnimationFrameFired: - case WebInspector.ScriptTimelineRecord.EventType.AnimationFrameRequested: - case WebInspector.ScriptTimelineRecord.EventType.AnimationFrameCanceled: - iconStyleClass = WebInspector.TimelineRecordTreeElement.AnimationRecordIconStyleClass; - break; - default: - console.error("Unknown ScriptTimelineRecord eventType: " + timelineRecord.eventType, timelineRecord); - } - - break; - - default: - console.error("Unknown TimelineRecord type: " + timelineRecord.type, timelineRecord); - } - - WebInspector.GeneralTreeElement.call(this, [iconStyleClass], title, subtitle, representedObject || timelineRecord, false); - - this.small = true; - - if (this._sourceCodeLocation) - this.tooltipHandledSeparately = true; -}; - -WebInspector.TimelineRecordTreeElement.StyleRecordIconStyleClass = "style-record"; -WebInspector.TimelineRecordTreeElement.LayoutRecordIconStyleClass = "layout-record"; -WebInspector.TimelineRecordTreeElement.PaintRecordIconStyleClass = "paint-record"; -WebInspector.TimelineRecordTreeElement.EvaluatedRecordIconStyleClass = "evaluated-record"; -WebInspector.TimelineRecordTreeElement.EventRecordIconStyleClass = "event-record"; -WebInspector.TimelineRecordTreeElement.TimerRecordIconStyleClass = "timer-record"; -WebInspector.TimelineRecordTreeElement.AnimationRecordIconStyleClass = "animation-record"; - -WebInspector.TimelineRecordTreeElement.prototype = { - constructor: WebInspector.TimelineRecordTreeElement, - __proto__: WebInspector.GeneralTreeElement.prototype, - - // Public - - get record() - { - return this._record; - }, - - get filterableData() - { - var url = this._sourceCodeLocation ? this._sourceCodeLocation.sourceCode.url : ""; - return {text: [this.mainTitle, url || "", this._record.details || ""]}; - }, - - // Protected - - onattach: function() - { - WebInspector.GeneralTreeElement.prototype.onattach.call(this); - - console.assert(this.element); - - if (!this.tooltipHandledSeparately) - return; - - var tooltipPrefix = this.mainTitle + "\n"; - this._sourceCodeLocation.populateLiveDisplayLocationTooltip(this.element, tooltipPrefix); - } -}; diff --git a/Source/WebInspectorUI/UserInterface/TimelineRecording.js b/Source/WebInspectorUI/UserInterface/TimelineRecording.js deleted file mode 100644 index a4ea6145d..000000000 --- a/Source/WebInspectorUI/UserInterface/TimelineRecording.js +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.TimelineRecording = function() -{ - WebInspector.Object.call(this); - - this._timelines = new Map; - this._timelines.set(WebInspector.TimelineRecord.Type.Network, new WebInspector.NetworkTimeline); - this._timelines.set(WebInspector.TimelineRecord.Type.Script, new WebInspector.Timeline); - this._timelines.set(WebInspector.TimelineRecord.Type.Layout, new WebInspector.Timeline); - - for (var timeline of this._timelines.values()) - timeline.addEventListener(WebInspector.Timeline.Event.TimesUpdated, this._timelineTimesUpdated, this); - - this.reset(true); -}; - -WebInspector.TimelineRecording.Event = { - Reset: "timeline-recording-reset", - SourceCodeTimelineAdded: "timeline-recording-source-code-timeline-added", - TimesUpdated: "timeline-recording-times-updated" -}; - -WebInspector.TimelineRecording.prototype = { - constructor: WebInspector.TimelineRecording, - __proto__: WebInspector.Object.prototype, - - // Public - - get timelines() - { - return this._timelines; - }, - - get startTime() - { - return this._startTime; - }, - - get endTime() - { - return this._endTime; - }, - - reset: function(suppressEvents) - { - this._sourceCodeTimelinesMap = new Map; - this._eventMarkers = []; - this._startTime = NaN; - this._endTime = NaN; - - for (var timeline of this._timelines.values()) - timeline.reset(suppressEvents); - - if (!suppressEvents) { - this.dispatchEventToListeners(WebInspector.TimelineRecording.Event.Reset); - this.dispatchEventToListeners(WebInspector.TimelineRecording.Event.TimesUpdated); - } - }, - - sourceCodeTimelinesForSourceCode: function(sourceCode) - { - var timelines = this._sourceCodeTimelinesMap.get(sourceCode); - if (!timelines) - return []; - return timelines.values(); - }, - - addEventMarker: function(eventMarker) - { - this._eventMarkers.push(eventMarker); - }, - - addRecord: function(record) - { - // Add the record to the global timeline by type. - this._timelines.get(record.type).addRecord(record); - - // Netowrk records don't have source code timelines. - if (record.type === WebInspector.TimelineRecord.Type.Network) - return; - - // Add the record to the source code timelines. - var activeMainResource = WebInspector.frameResourceManager.mainFrame.provisionalMainResource || WebInspector.frameResourceManager.mainFrame.mainResource; - var sourceCode = record.sourceCodeLocation ? record.sourceCodeLocation.sourceCode : activeMainResource; - - var sourceCodeTimelines = this._sourceCodeTimelinesMap.get(sourceCode); - if (!sourceCodeTimelines) { - sourceCodeTimelines = new Map; - this._sourceCodeTimelinesMap.set(sourceCode, sourceCodeTimelines); - } - - var newTimeline = false; - var key = this._keyForRecord(record); - var sourceCodeTimeline = sourceCodeTimelines.get(key); - if (!sourceCodeTimeline) { - sourceCodeTimeline = new WebInspector.SourceCodeTimeline(sourceCode, record.sourceCodeLocation, record.type, record.eventType); - sourceCodeTimelines.set(key, sourceCodeTimeline); - newTimeline = true; - } - - sourceCodeTimeline.addRecord(record); - - if (newTimeline) - this.dispatchEventToListeners(WebInspector.TimelineRecording.Event.SourceCodeTimelineAdded, {sourceCodeTimeline: sourceCodeTimeline}); - }, - - // Private - - _keyForRecord: function(record) - { - var key = record.type; - if (record instanceof WebInspector.ScriptTimelineRecord || record instanceof WebInspector.LayoutTimelineRecord) - key += ":" + record.eventType; - if (record instanceof WebInspector.ScriptTimelineRecord && record.eventType === WebInspector.ScriptTimelineRecord.EventType.EventDispatched) - key += ":" + record.details; - if (record.sourceCodeLocation) - key += ":" + record.sourceCodeLocation.lineNumber + ":" + record.sourceCodeLocation.columnNumber; - return key; - }, - - _timelineTimesUpdated: function(event) - { - var timeline = event.target; - var changed = false; - - if (isNaN(this._startTime) || timeline.startTime < this._startTime) { - this._startTime = timeline.startTime; - changed = true; - } - - if (isNaN(this._endTime) || this._endTime < timeline.endTime) { - this._endTime = timeline.endTime; - changed = true; - } - - if (changed) - this.dispatchEventToListeners(WebInspector.TimelineRecording.Event.TimesUpdated); - } -}; diff --git a/Source/WebInspectorUI/UserInterface/TimelineRuler.css b/Source/WebInspectorUI/UserInterface/TimelineRuler.css deleted file mode 100644 index a49d88ee2..000000000 --- a/Source/WebInspectorUI/UserInterface/TimelineRuler.css +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.timeline-ruler { - position: relative; - pointer-events: none; -} - -.timeline-ruler.allows-time-range-selection { - pointer-events: all; -} - -.timeline-ruler > * { - pointer-events: none; -} - -.timeline-ruler > .header { - border-bottom: 1px solid rgb(200, 200, 200); - - position: absolute; - top: 0; - left: 0; - right: 0; - height: 22px; -} - -.timeline-ruler > .header > .divider { - position: absolute; - width: 1px; - top: 0; - bottom: 0; - -webkit-transform: translateX(-1px); - background-image: -webkit-linear-gradient(bottom, rgba(200, 200, 200, 1), rgba(200, 200, 200, 0) 85%); -} - -.timeline-ruler > .header > .divider > .label { - position: absolute; - top: 5px; - right: 5px; - font-size: 9px; - font-family: "Lucida Grande", sans-serif; - color: rgb(128, 128, 128); - white-space: nowrap; -} - -.timeline-ruler > .markers { - position: absolute; - top: 22px; - left: 0; - right: 0; - bottom: 0; - z-index: 10; -} - -.timeline-ruler > .markers > .divider { - position: absolute; - width: 1px; - top: 1px; - bottom: 0; - -webkit-transform: translateX(-1px); - background-color: rgba(0, 0, 0, 0.05); -} - -.timeline-ruler > .markers > .marker { - position: absolute; - top: 0; - bottom: 0; - - -webkit-transform: translateX(-1px); - - border-left-width: 1px; - border-left-style: dashed; - border-left-color: rgba(128, 128, 128, 0.5); -} - -.timeline-ruler > .markers > .marker.current-time { - border-left-color: red; - border-left-style: solid; -} - -.timeline-ruler > .markers > .marker.current-time::before { - position: absolute; - top: -5px; - left: -5px; - - width: 9px; - height: 9px; - border-radius: 5px; - - background-color: red; - - content: ""; -} - -.timeline-ruler > .markers > .marker.load-event { - border-left-color: rgba(255, 0, 0, 0.5); -} - -.timeline-ruler > .markers > .marker.dom-content-event { - border-left-color: rgba(0, 0, 255, 0.5); -} - -.timeline-ruler > .markers > .marker.timestamp { - border-left-color: rgba(0, 110, 0, 0.5); -} - -.timeline-ruler > .selection-drag { - position: absolute; - top: 0; - height: 22px; - cursor: -webkit-grab; - pointer-events: all; -} - -.timeline-ruler > .selection-drag:active { - cursor: -webkit-grabbing; -} - -.timeline-ruler > .selection-handle { - position: absolute; - top: 0; - width: 8px; - height: 21px; - border-radius: 5px; - background-color: rgb(164, 164, 164); - border: 1px solid white; - cursor: col-resize; - pointer-events: all; - z-index: 15; -} - -.timeline-ruler > .selection-handle.left { - -webkit-transform: translateX(-4px); -} - -.timeline-ruler > .selection-handle.right { - -webkit-transform: translateX(4px); -} - -.timeline-ruler > .shaded-area { - position: absolute; - top: 0; - bottom: 0; - background-color: rgba(0, 0, 0, 0.1); - z-index: 15; -} - -.timeline-ruler > .shaded-area.left { - left: 0; -} - -.timeline-ruler > .shaded-area.right { - right: 0; -} diff --git a/Source/WebInspectorUI/UserInterface/TimelineRuler.js b/Source/WebInspectorUI/UserInterface/TimelineRuler.js deleted file mode 100644 index 2fa6d85c1..000000000 --- a/Source/WebInspectorUI/UserInterface/TimelineRuler.js +++ /dev/null @@ -1,753 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.TimelineRuler = function() -{ - WebInspector.Object.call(this); - - this._element = document.createElement("div"); - this._element.className = WebInspector.TimelineRuler.StyleClassName; - - this._headerElement = document.createElement("div"); - this._headerElement.className = WebInspector.TimelineRuler.HeaderElementStyleClassName; - this._element.appendChild(this._headerElement); - - this._markersElement = document.createElement("div"); - this._markersElement.className = WebInspector.TimelineRuler.MarkersElementStyleClassName; - this._element.appendChild(this._markersElement); - - this._zeroTime = 0; - this._startTime = 0; - this._endTime = 0; - this._duration = NaN; - this._secondsPerPixel = 0; - this._selectionStartTime = 0; - this._selectionEndTime = Infinity; - this._endTimePinned = false; - this._allowsClippedLabels = false; - this._allowsTimeRangeSelection = false; - - this._markerElementMap = new Map; -} - -WebInspector.TimelineRuler.MinimumLeftDividerSpacing = 48; -WebInspector.TimelineRuler.MinimumDividerSpacing = 64; - -WebInspector.TimelineRuler.StyleClassName = "timeline-ruler"; -WebInspector.TimelineRuler.AllowsTimeRangeSelectionStyleClassName = "allows-time-range-selection"; -WebInspector.TimelineRuler.HeaderElementStyleClassName = "header"; -WebInspector.TimelineRuler.DividerElementStyleClassName = "divider"; -WebInspector.TimelineRuler.DividerLabelElementStyleClassName = "label"; - -WebInspector.TimelineRuler.MarkersElementStyleClassName = "markers"; -WebInspector.TimelineRuler.BaseMarkerElementStyleClassName = "marker"; -WebInspector.TimelineRuler.ShadedAreaElementStyleClassName = "shaded-area"; -WebInspector.TimelineRuler.SelectionDragElementStyleClassName = "selection-drag"; -WebInspector.TimelineRuler.SelectionHandleElementStyleClassName = "selection-handle"; -WebInspector.TimelineRuler.LeftSelectionElementStyleClassName = "left"; -WebInspector.TimelineRuler.RightSelectionElementStyleClassName = "right"; -WebInspector.TimelineRuler.MinimumSelectionTimeRange = 0.01; - -WebInspector.TimelineRuler.Event = { - TimeRangeSelectionChanged: "time-ruler-time-range-selection-changed" -}; - -WebInspector.TimelineRuler.prototype = { - constructor: WebInspector.TimelineRuler, - - // Public - - get element() - { - return this._element; - }, - - get allowsClippedLabels() - { - return this._allowsClippedLabels - }, - - set allowsClippedLabels(x) - { - if (this._allowsClippedLabels === x) - return; - - this._allowsClippedLabels = x || false; - - this._needsLayout(); - }, - - get allowsTimeRangeSelection() - { - return this._allowsTimeRangeSelection; - }, - - set allowsTimeRangeSelection(x) - { - if (this._allowsTimeRangeSelection === x) - return; - - this._allowsTimeRangeSelection = x || false; - - if (x) { - this._mouseDownEventListener = this._handleMouseDown.bind(this); - this._element.addEventListener("mousedown", this._mouseDownEventListener); - - this._leftShadedAreaElement = document.createElement("div"); - this._leftShadedAreaElement.classList.add(WebInspector.TimelineRuler.ShadedAreaElementStyleClassName); - this._leftShadedAreaElement.classList.add(WebInspector.TimelineRuler.LeftSelectionElementStyleClassName); - - this._rightShadedAreaElement = document.createElement("div"); - this._rightShadedAreaElement.classList.add(WebInspector.TimelineRuler.ShadedAreaElementStyleClassName); - this._rightShadedAreaElement.classList.add(WebInspector.TimelineRuler.RightSelectionElementStyleClassName); - - this._leftSelectionHandleElement = document.createElement("div"); - this._leftSelectionHandleElement.classList.add(WebInspector.TimelineRuler.SelectionHandleElementStyleClassName); - this._leftSelectionHandleElement.classList.add(WebInspector.TimelineRuler.LeftSelectionElementStyleClassName); - this._leftSelectionHandleElement.addEventListener("mousedown", this._handleSelectionHandleMouseDown.bind(this)); - - this._rightSelectionHandleElement = document.createElement("div"); - this._rightSelectionHandleElement.classList.add(WebInspector.TimelineRuler.SelectionHandleElementStyleClassName); - this._rightSelectionHandleElement.classList.add(WebInspector.TimelineRuler.RightSelectionElementStyleClassName); - this._rightSelectionHandleElement.addEventListener("mousedown", this._handleSelectionHandleMouseDown.bind(this)); - - this._selectionDragElement = document.createElement("div"); - this._selectionDragElement.classList.add(WebInspector.TimelineRuler.SelectionDragElementStyleClassName); - - this._needsSelectionLayout(); - } else { - this._element.removeEventListener("mousedown", this._mouseDownEventListener); - delete this._mouseDownEventListener; - - this._leftShadedAreaElement.remove(); - this._rightShadedAreaElement.remove(); - this._leftSelectionHandleElement.remove(); - this._rightSelectionHandleElement.remove(); - this._selectionDragElement.remove(); - - delete this._leftShadedAreaElement; - delete this._rightShadedAreaElement; - delete this._leftSelectionHandleElement; - delete this._rightSelectionHandleElement; - delete this._selectionDragElement; - } - }, - - get zeroTime() - { - return this._zeroTime; - }, - - set zeroTime(x) - { - if (this._zeroTime === x) - return; - - this._zeroTime = x || 0; - - this._needsLayout(); - }, - - get startTime() - { - return this._startTime; - }, - - set startTime(x) - { - if (this._startTime === x) - return; - - this._startTime = x || 0; - - if (!isNaN(this._duration)) - this._endTime = this._startTime + this._duration; - - this._needsLayout(); - }, - - get duration() - { - if (!isNaN(this._duration)) - return this._duration; - return this.endTime - this.startTime; - }, - - set duration(x) - { - if (this._duration === x) - return; - - this._duration = x || NaN; - - if (!isNaN(this._duration)) { - this._endTime = this._startTime + this._duration; - this._endTimePinned = true; - } else - this._endTimePinned = false; - - this._needsLayout(); - }, - - get endTime() - { - if (!this._endTimePinned && this._scheduledLayoutUpdateIdentifier) - this._recalculate(); - return this._endTime; - }, - - set endTime(x) - { - if (this._endTime === x) - return; - - this._endTime = x || 0; - this._endTimePinned = true; - - this._needsLayout(); - }, - - get secondsPerPixel() - { - if (this._scheduledLayoutUpdateIdentifier) - this._recalculate(); - return this._secondsPerPixel; - }, - - set secondsPerPixel(x) - { - if (this._secondsPerPixel === x) - return; - - this._secondsPerPixel = x || 0; - this._endTimePinned = false; - this._currentSliceTime = 0; - - this._needsLayout(); - }, - - get selectionStartTime() - { - return this._selectionStartTime; - }, - - set selectionStartTime(x) - { - if (this._selectionStartTime === x) - return; - - this._selectionStartTime = x || 0; - this._timeRangeSelectionChanged = true; - - this._needsSelectionLayout(); - }, - - get selectionEndTime() - { - return this._selectionEndTime; - }, - - set selectionEndTime(x) - { - if (this._selectionEndTime === x) - return; - - this._selectionEndTime = x || 0; - this._timeRangeSelectionChanged = true; - - this._needsSelectionLayout(); - }, - - addMarker: function(marker) - { - console.assert(marker instanceof WebInspector.TimelineMarker); - - if (this._markerElementMap.has(marker)) - return; - - marker.addEventListener(WebInspector.TimelineMarker.Event.TimeChanged, this._timelineMarkerTimeChanged, this); - - var markerElement = document.createElement("div"); - markerElement.classList.add(WebInspector.TimelineRuler.BaseMarkerElementStyleClassName); - markerElement.classList.add(marker.type); - - this._markerElementMap.set(marker, markerElement); - - this._needsMarkerLayout(); - }, - - elementForMarker: function(marker) - { - return this._markerElementMap.get(marker) || null; - }, - - updateLayout: function() - { - if (this._scheduledLayoutUpdateIdentifier) { - cancelAnimationFrame(this._scheduledLayoutUpdateIdentifier); - delete this._scheduledLayoutUpdateIdentifier; - } - - var visibleWidth = this._recalculate(); - if (visibleWidth <= 0) - return; - - var duration = this.duration; - - var pixelsPerSecond = visibleWidth / duration; - - // Calculate a divider count based on the maximum allowed divider density. - var dividerCount = Math.round(visibleWidth / WebInspector.TimelineRuler.MinimumDividerSpacing); - - if (this._endTimePinned || !this._currentSliceTime) { - // Calculate the slice time based on the rough divider count and the time span. - var sliceTime = duration / dividerCount; - - // Snap the slice time to a nearest number (e.g. 0.1, 0.2, 0.5, 1, 2, 5, 10, 20, 50, etc.) - sliceTime = Math.pow(10, Math.ceil(Math.log(sliceTime) / Math.LN10)); - if (sliceTime * pixelsPerSecond >= 5 * WebInspector.TimelineRuler.MinimumDividerSpacing) - sliceTime = sliceTime / 5; - if (sliceTime * pixelsPerSecond >= 2 * WebInspector.TimelineRuler.MinimumDividerSpacing) - sliceTime = sliceTime / 2; - - this._currentSliceTime = sliceTime; - } else { - // Reuse the last slice time since the time duration does not scale to fit when the end time isn't pinned. - var sliceTime = this._currentSliceTime; - } - - var firstDividerTime = (Math.ceil((this._startTime - this._zeroTime) / sliceTime) * sliceTime) + this._zeroTime; - var lastDividerTime = this._endTime; - - // Calculate the divider count now based on the final slice time. - dividerCount = Math.ceil((lastDividerTime - firstDividerTime) / sliceTime); - - // Make an extra divider in case the last one is partially visible. - if (!this._endTimePinned) - ++dividerCount; - - var markerDividers = this._markersElement.querySelectorAll("." + WebInspector.TimelineRuler.DividerElementStyleClassName); - - var dividerElement = this._headerElement.firstChild; - - for (var i = 0; i <= dividerCount; ++i) { - if (!dividerElement) { - dividerElement = document.createElement("div"); - dividerElement.className = WebInspector.TimelineRuler.DividerElementStyleClassName; - this._headerElement.appendChild(dividerElement); - - var labelElement = document.createElement("div"); - labelElement.className = WebInspector.TimelineRuler.DividerLabelElementStyleClassName; - dividerElement._labelElement = labelElement; - dividerElement.appendChild(labelElement); - } - - var markerDividerElement = markerDividers[i]; - if (!markerDividerElement) { - markerDividerElement = document.createElement("div"); - markerDividerElement.className = WebInspector.TimelineRuler.DividerElementStyleClassName; - this._markersElement.appendChild(markerDividerElement); - } - - var dividerTime = firstDividerTime + (sliceTime * i); - - var newLeftPosition = (dividerTime - this._startTime) / duration; - - if (!this._allowsClippedLabels) { - // Don't allow dividers under 0% where they will be completely hidden. - if (newLeftPosition < 0) - continue; - - // When over 100% it is time to stop making/updating dividers. - if (newLeftPosition > 1) - break; - - // Don't allow the left-most divider spacing to be so tight it clips. - if ((newLeftPosition * visibleWidth) < WebInspector.TimelineRuler.MinimumLeftDividerSpacing) - continue; - } - - this._updatePositionOfElement(dividerElement, newLeftPosition, visibleWidth); - this._updatePositionOfElement(markerDividerElement, newLeftPosition, visibleWidth); - - dividerElement._labelElement.textContent = isNaN(dividerTime) ? "" : Number.secondsToString(dividerTime - this._zeroTime, true); - dividerElement = dividerElement.nextSibling; - } - - // Remove extra dividers. - while (dividerElement) { - var nextDividerElement = dividerElement.nextSibling; - dividerElement.remove(); - dividerElement = nextDividerElement; - } - - for (; i < markerDividers.length; ++i) - markerDividers[i].remove(); - - this._updateMarkers(visibleWidth, duration); - this._updateSelection(visibleWidth, duration); - }, - - updateLayoutIfNeeded: function() - { - // If there is a main layout scheduled we can just update layout and return, since that - // will update markers and the selection at the same time. - if (this._scheduledLayoutUpdateIdentifier) { - this.updateLayout(); - return; - } - - var visibleWidth = this._element.clientWidth; - if (visibleWidth <= 0) - return; - - if (this._scheduledMarkerLayoutUpdateIdentifier) - this._updateMarkers(visibleWidth, this.duration); - - if (this._scheduledSelectionLayoutUpdateIdentifier) - this._updateSelection(visibleWidth, this.duration); - }, - - // Private - - _needsLayout: function() - { - if (this._scheduledLayoutUpdateIdentifier) - return; - - if (this._scheduledMarkerLayoutUpdateIdentifier) { - cancelAnimationFrame(this._scheduledMarkerLayoutUpdateIdentifier); - delete this._scheduledMarkerLayoutUpdateIdentifier; - } - - if (this._scheduledSelectionLayoutUpdateIdentifier) { - cancelAnimationFrame(this._scheduledSelectionLayoutUpdateIdentifier); - delete this._scheduledSelectionLayoutUpdateIdentifier; - } - - this._scheduledLayoutUpdateIdentifier = requestAnimationFrame(this.updateLayout.bind(this)); - }, - - _needsMarkerLayout: function() - { - // If layout is scheduled, abort since markers will be updated when layout happens. - if (this._scheduledLayoutUpdateIdentifier) - return; - - if (this._scheduledMarkerLayoutUpdateIdentifier) - return; - - function update() - { - delete this._scheduledMarkerLayoutUpdateIdentifier; - - var visibleWidth = this._element.clientWidth; - if (visibleWidth <= 0) - return; - - this._updateMarkers(visibleWidth, this.duration); - } - - this._scheduledMarkerLayoutUpdateIdentifier = requestAnimationFrame(update.bind(this)); - }, - - _needsSelectionLayout: function() - { - if (!this._allowsTimeRangeSelection) - return; - - // If layout is scheduled, abort since the selection will be updated when layout happens. - if (this._scheduledLayoutUpdateIdentifier) - return; - - if (this._scheduledSelectionLayoutUpdateIdentifier) - return; - - function update() - { - delete this._scheduledSelectionLayoutUpdateIdentifier; - - var visibleWidth = this._element.clientWidth; - if (visibleWidth <= 0) - return; - - this._updateSelection(visibleWidth, this.duration); - } - - this._scheduledSelectionLayoutUpdateIdentifier = requestAnimationFrame(update.bind(this)); - }, - - _recalculate: function() - { - var visibleWidth = this._element.clientWidth; - if (visibleWidth <= 0) - return 0; - - if (this._endTimePinned) - var duration = this._endTime - this._startTime; - else - var duration = visibleWidth * this._secondsPerPixel; - - this._secondsPerPixel = duration / visibleWidth; - - if (!this._endTimePinned) - this._endTime = this._startTime + (visibleWidth * this._secondsPerPixel); - - return visibleWidth; - }, - - _updatePositionOfElement: function(element, newPosition, visibleWidth, property) - { - property = property || "left"; - - newPosition *= this._endTimePinned ? 100 : visibleWidth; - newPosition = newPosition.toFixed(2); - - var currentPosition = parseFloat(element.style[property]).toFixed(2); - if (currentPosition !== newPosition) - element.style[property] = newPosition + (this._endTimePinned ? "%" : "px"); - }, - - _updateMarkers: function(visibleWidth, duration) - { - if (this._scheduledMarkerLayoutUpdateIdentifier) { - cancelAnimationFrame(this._scheduledMarkerLayoutUpdateIdentifier); - delete this._scheduledMarkerLayoutUpdateIdentifier; - } - - this._markerElementMap.forEach(function(markerElement, marker) { - var newLeftPosition = (marker.time - this._startTime) / duration; - - this._updatePositionOfElement(markerElement, newLeftPosition, visibleWidth); - - if (!markerElement.parentNode) - this._markersElement.appendChild(markerElement); - }, this); - }, - - _updateSelection: function(visibleWidth, duration) - { - if (this._scheduledSelectionLayoutUpdateIdentifier) { - cancelAnimationFrame(this._scheduledSelectionLayoutUpdateIdentifier); - delete this._scheduledSelectionLayoutUpdateIdentifier; - } - - this._element.classList.toggle(WebInspector.TimelineRuler.AllowsTimeRangeSelectionStyleClassName, this._allowsTimeRangeSelection); - - if (!this._allowsTimeRangeSelection) - return; - - var newLeftPosition = Math.max(0, (this._selectionStartTime - this._startTime) / duration); - this._updatePositionOfElement(this._leftShadedAreaElement, newLeftPosition, visibleWidth, "width"); - this._updatePositionOfElement(this._leftSelectionHandleElement, newLeftPosition, visibleWidth, "left"); - this._updatePositionOfElement(this._selectionDragElement, newLeftPosition, visibleWidth, "left"); - - var newRightPosition = 1 - Math.min((this._selectionEndTime - this._startTime) / duration, 1); - this._updatePositionOfElement(this._rightShadedAreaElement, newRightPosition, visibleWidth, "width"); - this._updatePositionOfElement(this._rightSelectionHandleElement, newRightPosition, visibleWidth, "right"); - this._updatePositionOfElement(this._selectionDragElement, newRightPosition, visibleWidth, "right"); - - if (!this._selectionDragElement.parentNode) { - this._element.appendChild(this._selectionDragElement); - this._element.appendChild(this._leftShadedAreaElement); - this._element.appendChild(this._leftSelectionHandleElement); - this._element.appendChild(this._rightShadedAreaElement); - this._element.appendChild(this._rightSelectionHandleElement); - } - - if (this._timeRangeSelectionChanged) - this._dispatchTimeRangeSelectionChangedEvent(); - }, - - _dispatchTimeRangeSelectionChangedEvent: function() - { - delete this._timeRangeSelectionChanged; - - if (this._suppressTimeRangeSelectionChangedEvent) - return; - - this.dispatchEventToListeners(WebInspector.TimelineRuler.Event.TimeRangeSelectionChanged); - }, - - _timelineMarkerTimeChanged: function() - { - this._needsMarkerLayout(); - }, - - _handleMouseDown: function(event) - { - // Only handle left mouse clicks. - if (event.button !== 0 || event.ctrlKey) - return; - - this._selectionIsMove = event.target === this._selectionDragElement; - this._suppressTimeRangeSelectionChangedEvent = !this._selectionIsMove; - - if (this._selectionIsMove) - this._lastMousePosition = event.pageX; - else - this._mouseDownPosition = event.pageX - this._element.totalOffsetLeft; - - this._mouseMoveEventListener = this._handleMouseMove.bind(this); - this._mouseUpEventListener = this._handleMouseUp.bind(this); - - // Register these listeners on the document so we can track the mouse if it leaves the ruler. - document.addEventListener("mousemove", this._mouseMoveEventListener); - document.addEventListener("mouseup", this._mouseUpEventListener); - - event.preventDefault(); - event.stopPropagation(); - }, - - _handleMouseMove: function(event) - { - console.assert(event.button === 0); - - if (this._selectionIsMove) { - var currentMousePosition = event.pageX; - - var offsetTime = (currentMousePosition - this._lastMousePosition) * this.secondsPerPixel; - var selectionDuration = this.selectionEndTime - this.selectionStartTime; - - this.selectionStartTime = Math.max(this.startTime, Math.min(this.selectionStartTime + offsetTime, this.endTime - selectionDuration)); - this.selectionEndTime = this.selectionStartTime + selectionDuration; - - this._lastMousePosition = currentMousePosition; - } else { - var currentMousePosition = event.pageX - this._element.totalOffsetLeft; - - this.selectionStartTime = Math.max(this.startTime, this.startTime + (Math.min(currentMousePosition, this._mouseDownPosition) * this.secondsPerPixel)); - this.selectionEndTime = Math.min(this.startTime + (Math.max(currentMousePosition, this._mouseDownPosition) * this.secondsPerPixel), this.endTime); - } - - this._updateSelection(this._element.clientWidth, this.duration); - - event.preventDefault(); - event.stopPropagation(); - }, - - _handleMouseUp: function(event) - { - console.assert(event.button === 0); - - if (!this._selectionIsMove && this.selectionEndTime - this.selectionStartTime < WebInspector.TimelineRuler.MinimumSelectionTimeRange) { - // The section is smaller than allowed, grow in the direction of the drag to meet the minumum. - var currentMousePosition = event.pageX - this._element.totalOffsetLeft; - if (currentMousePosition > this._mouseDownPosition) { - this.selectionEndTime = Math.min(this.selectionStartTime + WebInspector.TimelineRuler.MinimumSelectionTimeRange, this.endTime); - this.selectionStartTime = this.selectionEndTime - WebInspector.TimelineRuler.MinimumSelectionTimeRange; - } else { - this.selectionStartTime = Math.max(this.startTime, this.selectionEndTime - WebInspector.TimelineRuler.MinimumSelectionTimeRange); - this.selectionEndTime = this.selectionStartTime + WebInspector.TimelineRuler.MinimumSelectionTimeRange - } - } - - delete this._suppressTimeRangeSelectionChangedEvent; - - this._dispatchTimeRangeSelectionChangedEvent(); - - document.removeEventListener("mousemove", this._mouseMoveEventListener); - document.removeEventListener("mouseup", this._mouseUpEventListener); - - delete this._mouseMovedEventListener; - delete this._mouseUpEventListener; - delete this._mouseDownPosition; - delete this._lastMousePosition; - delete this._selectionIsMove; - - event.preventDefault(); - event.stopPropagation(); - }, - - _handleSelectionHandleMouseDown: function(event) - { - // Only handle left mouse clicks. - if (event.button !== 0 || event.ctrlKey) - return; - - this._dragHandleIsStartTime = event.target === this._leftSelectionHandleElement; - this._mouseDownPosition = event.pageX - this._element.totalOffsetLeft; - - this._selectionHandleMouseMoveEventListener = this._handleSelectionHandleMouseMove.bind(this); - this._selectionHandleMouseUpEventListener = this._handleSelectionHandleMouseUp.bind(this); - - // Register these listeners on the document so we can track the mouse if it leaves the ruler. - document.addEventListener("mousemove", this._selectionHandleMouseMoveEventListener); - document.addEventListener("mouseup", this._selectionHandleMouseUpEventListener); - - event.preventDefault(); - event.stopPropagation(); - }, - - _handleSelectionHandleMouseMove: function(event) - { - console.assert(event.button === 0); - - var currentMousePosition = event.pageX - this._element.totalOffsetLeft; - var currentTime = this.startTime + (currentMousePosition * this.secondsPerPixel); - - if (event.altKey && !event.ctrlKey && !event.metaKey && !event.shiftKey) { - // Resize the selection on both sides when the Option keys is held down. - if (this._dragHandleIsStartTime) { - var timeDifference = currentTime - this.selectionStartTime; - this.selectionStartTime = Math.max(this.startTime, Math.min(currentTime, this.selectionEndTime - WebInspector.TimelineRuler.MinimumSelectionTimeRange)); - this.selectionEndTime = Math.min(Math.max(this.selectionStartTime + WebInspector.TimelineRuler.MinimumSelectionTimeRange, this.selectionEndTime - timeDifference), this.endTime); - } else { - var timeDifference = currentTime - this.selectionEndTime; - this.selectionEndTime = Math.min(Math.max(this.selectionStartTime + WebInspector.TimelineRuler.MinimumSelectionTimeRange, currentTime), this.endTime); - this.selectionStartTime = Math.max(this.startTime, Math.min(this.selectionStartTime - timeDifference, this.selectionEndTime - WebInspector.TimelineRuler.MinimumSelectionTimeRange)); - } - } else { - // Resize the selection on side being dragged. - if (this._dragHandleIsStartTime) - this.selectionStartTime = Math.max(this.startTime, Math.min(currentTime, this.selectionEndTime - WebInspector.TimelineRuler.MinimumSelectionTimeRange)); - else - this.selectionEndTime = Math.min(Math.max(this.selectionStartTime + WebInspector.TimelineRuler.MinimumSelectionTimeRange, currentTime), this.endTime); - } - - this._updateSelection(this._element.clientWidth, this.duration); - - event.preventDefault(); - event.stopPropagation(); - }, - - _handleSelectionHandleMouseUp: function(event) - { - console.assert(event.button === 0); - - document.removeEventListener("mousemove", this._selectionHandleMouseMoveEventListener); - document.removeEventListener("mouseup", this._selectionHandleMouseUpEventListener); - - delete this._selectionHandleMouseMoveEventListener; - delete this._selectionHandleMouseUpEventListener; - delete this._dragHandleIsStartTime; - delete this._mouseDownPosition; - - event.preventDefault(); - event.stopPropagation(); - } -} - -WebInspector.TimelineRuler.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/TimelineSidebarPanel.css b/Source/WebInspectorUI/UserInterface/TimelineSidebarPanel.css deleted file mode 100644 index e662ea256..000000000 --- a/Source/WebInspectorUI/UserInterface/TimelineSidebarPanel.css +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.sidebar > .panel.timeline > .status-bar { - position: absolute; - top: 0; - left: 5px; - right: 0; - height: 22px; - border-bottom: 1px solid rgb(179, 179, 179); -} - -.sidebar > .panel.timeline > .status-bar > .record-glyph { - position: absolute; - top: 0; - left: 0; - width: 21px; - height: 21px; - padding: 0; - border: none; - outline: none; - color: transparent; - overflow: hidden; - - -webkit-appearance: none; - - background-color: transparent; - background-image: -webkit-image-set(url(Images/RecordingStopped.png) 1x, url(Images/RecordingStopped@2x.png) 2x); - background-repeat: no-repeat; - background-size: 21px 21px; -} - -.sidebar > .panel.timeline > .status-bar > .record-glyph.recording { - background-image: -webkit-image-set(url(Images/Recording.png) 1x, url(Images/Recording@2x.png) 2x); -} - -.sidebar > .panel.timeline > .status-bar > .record-glyph:hover { - background-image: -webkit-image-set(url(Images/RecordingHovered.png) 1x, url(Images/RecordingHovered@2x.png) 2x); -} - -.sidebar > .panel.timeline > .status-bar > .record-glyph.recording:hover { - background-image: -webkit-image-set(url(Images/RecordingStopped.png) 1x, url(Images/RecordingStopped@2x.png) 2x); -} - -.sidebar > .panel.timeline > .status-bar > .record-glyph.forced { - background-image: -webkit-image-set(url(Images/RecordingStopped.png) 1x, url(Images/RecordingStopped@2x.png) 2x) !important; -} - -.sidebar > .panel.timeline > .status-bar > .record-glyph.recording.forced { - background-image: -webkit-image-set(url(Images/Recording.png) 1x, url(Images/Recording@2x.png) 2x) !important; -} - -.sidebar > .panel.timeline > .status-bar > .record-status { - position: absolute; - top: 0; - right: 21px; - left: 21px; - - text-align: center; - - line-height: 20px; - font-size: 11px; - font-family: "Lucida Grande", sans-serif; - font-weight: bold; - - color: rgb(76, 76, 76); - text-shadow: rgba(255, 255, 255, 0.5) 0 1px 0; -} - -.sidebar > .panel.timeline > .title-bar { - position: absolute; - left: 0; - right: 0; - - height: 22px; - - border-bottom: 1px solid rgb(179, 179, 179); - background-image: -webkit-linear-gradient(top, rgb(238, 240, 244), rgb(224, 226, 230)); - - color: rgb(57, 57, 57); - text-shadow: rgba(255, 255, 255, 0.5) 0 1px 0; - - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; - - font-size: 11px; - font-family: "Lucida Grande", sans-serif; - font-weight: bold; - - padding: 4px 9px; - - white-space: nowrap; - overflow: hidden; -} - -.sidebar > .panel.timeline > .title-bar.timelines { - top: 22px; -} - -.sidebar > .panel.timeline > .title-bar.timeline-events { - height: 23px; - border-top: 1px solid rgb(179, 179, 179); - top: 152px; -} - -.sidebar > .panel.timeline > .timelines-content { - position: absolute; - top: 44px; - height: 108px; - left: 0; - right: 0; - - overflow: hidden; -} - -.sidebar > .panel.timeline > .timelines-content .close-button { - margin-top: 2px; - width: 12px; - height: 12px; - - content: -webkit-image-set(url(Images/CloseTimeline.png) 1x, url(Images/CloseTimeline@2x.png) 2x); - - visibility: hidden; -} - -.sidebar > .panel.timeline > .timelines-content li.item .icon { - width: 24px; - height: 24px; - margin-top: 5px; -} - -.sidebar > .panel.timeline > .timelines-content li.item.selected .close-button { - visibility: visible; -} - -.sidebar > .panel.timeline > .timelines-content li.item:not(.selected):nth-child(even) { - background-color: rgba(0, 0, 0, 0.03); - background-clip: padding-box; -} - -.sidebar > .panel.timeline > .timelines-content li.item:not(.selected):not(:first-child) { - border-top: 1px solid rgba(0, 0, 0, 0.09); -} - -.sidebar > .panel.timeline > .timelines-content li.item.selected + li.item { - border-top-color: rgb(120, 139, 168); -} - -.sidebar > .panel.timeline > .timelines-content :focus li.item.selected + li.item { - border-top-color: rgb(107, 130, 164); -} - -.sidebar > .panel.timeline > .timelines-content .close-button:active { - opacity: 0.8; -} - -.sidebar > .panel.timeline > .content, -.sidebar > .panel.timeline > .empty-content-placeholder { - top: 175px; -} - -.sidebar > .panel.timeline.timeline-content-view-showing > .content { - /* This hides the scrollbar. The view shows a scrollbar, we don't need two. */ - padding-right: 16px; - right: -16px; -} - -.sidebar > .panel.timeline > .content > .stripe-background { - position: absolute; - top: 0; - left: 0; - right: 0; - min-height: 100%; - - background-image: -webkit-linear-gradient(top, transparent, transparent 50%, rgba(0, 0, 0, 0.03) 50%, rgba(0, 0, 0, 0.03)); - background-size: 100% 40px; - - pointer-events: none; - display: none; -} - -.sidebar > .panel.timeline.timeline-content-view-showing > .content > .stripe-background { - display: block; -} diff --git a/Source/WebInspectorUI/UserInterface/TimelineSidebarPanel.js b/Source/WebInspectorUI/UserInterface/TimelineSidebarPanel.js deleted file mode 100644 index 30c76d8ea..000000000 --- a/Source/WebInspectorUI/UserInterface/TimelineSidebarPanel.js +++ /dev/null @@ -1,354 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.TimelineSidebarPanel = function() -{ - WebInspector.NavigationSidebarPanel.call(this, "timeline", WebInspector.UIString("Timelines"), "Images/NavigationItemStopwatch.svg", "2"); - - this._timelineEventsTitleBarElement = document.createElement("div"); - this._timelineEventsTitleBarElement.classList.add(WebInspector.TimelineSidebarPanel.TitleBarStyleClass); - this._timelineEventsTitleBarElement.classList.add(WebInspector.TimelineSidebarPanel.TimelineEventsTitleBarStyleClass); - this.element.insertBefore(this._timelineEventsTitleBarElement, this.element.firstChild); - - this.contentTreeOutlineLabel = ""; - - this._timelinesContentContainer = document.createElement("div"); - this._timelinesContentContainer.classList.add(WebInspector.TimelineSidebarPanel.TimelinesContentContainerStyleClass); - this.element.insertBefore(this._timelinesContentContainer, this.element.firstChild); - - this._timelinesTreeOutline = this.createContentTreeOutline(true, true); - this._timelinesTreeOutline.element.classList.add(WebInspector.NavigationSidebarPanel.HideDisclosureButtonsStyleClassName); - this._timelinesTreeOutline.onselect = this._timelinesTreeElementSelected.bind(this); - this._timelinesContentContainer.appendChild(this._timelinesTreeOutline.element); - - var timelinesTitleBarElement = document.createElement("div"); - timelinesTitleBarElement.textContent = WebInspector.UIString("Timelines"); - timelinesTitleBarElement.classList.add(WebInspector.TimelineSidebarPanel.TitleBarStyleClass); - timelinesTitleBarElement.classList.add(WebInspector.TimelineSidebarPanel.TimelinesTitleBarStyleClass); - this.element.insertBefore(timelinesTitleBarElement, this.element.firstChild); - - var statusBarElement = document.createElement("div"); - statusBarElement.classList.add(WebInspector.TimelineSidebarPanel.StatusBarStyleClass); - this.element.insertBefore(statusBarElement, this.element.firstChild); - - this._recordGlyphElement = document.createElement("div"); - this._recordGlyphElement.className = WebInspector.TimelineSidebarPanel.RecordGlyphStyleClass; - this._recordGlyphElement.addEventListener("mouseover", this._recordGlyphMousedOver.bind(this)); - this._recordGlyphElement.addEventListener("mouseout", this._recordGlyphMousedOut.bind(this)); - this._recordGlyphElement.addEventListener("click", this._recordGlyphClicked.bind(this)); - statusBarElement.appendChild(this._recordGlyphElement); - - this._recordStatusElement = document.createElement("div"); - this._recordStatusElement.className = WebInspector.TimelineSidebarPanel.RecordStatusStyleClass; - statusBarElement.appendChild(this._recordStatusElement); - - function createTimelineTreeElement(label, iconClass, identifier) - { - var treeElement = new WebInspector.GeneralTreeElement([iconClass, WebInspector.TimelineSidebarPanel.LargeIconStyleClass], label, null, identifier); - var closeButton = document.createElement("img"); - closeButton.classList.add(WebInspector.TimelineSidebarPanel.CloseButtonStyleClass); - closeButton.addEventListener("click", this.showTimelineOverview.bind(this)); - treeElement.status = closeButton; - return treeElement; - } - - this._timelineTreeElementMap = new Map; - this._timelineTreeElementMap.set(WebInspector.TimelineRecord.Type.Network, createTimelineTreeElement.call(this, WebInspector.UIString("Network Requests"), WebInspector.TimelineSidebarPanel.NetworkIconStyleClass, WebInspector.TimelineRecord.Type.Network)); - this._timelineTreeElementMap.set(WebInspector.TimelineRecord.Type.Layout, createTimelineTreeElement.call(this, WebInspector.UIString("Layout & Rendering"), WebInspector.TimelineSidebarPanel.ColorsIconStyleClass, WebInspector.TimelineRecord.Type.Layout)); - this._timelineTreeElementMap.set(WebInspector.TimelineRecord.Type.Script, createTimelineTreeElement.call(this, WebInspector.UIString("JavaScript & Events"), WebInspector.TimelineSidebarPanel.ScriptIconStyleClass, WebInspector.TimelineRecord.Type.Script)); - - for (var timelineTreeElement of this._timelineTreeElementMap.values()) - this._timelinesTreeOutline.appendChild(timelineTreeElement); - - this._timelineOverviewTreeElement = new WebInspector.GeneralTreeElement(WebInspector.TimelineSidebarPanel.StopwatchIconStyleClass, WebInspector.UIString("Timelines"), null, WebInspector.timelineManager.recording); - this._timelineOverviewTreeElement.addEventListener(WebInspector.HierarchicalPathComponent.Event.SiblingWasSelected, this.showTimelineOverview, this); - - this._stripeBackgroundElement = document.createElement("div"); - this._stripeBackgroundElement.className = WebInspector.TimelineSidebarPanel.StripeBackgroundStyleClass; - this.contentElement.insertBefore(this._stripeBackgroundElement, this.contentElement.firstChild); - - WebInspector.contentBrowser.addEventListener(WebInspector.ContentBrowser.Event.CurrentContentViewDidChange, this._contentBrowserCurrentContentViewDidChange, this); - WebInspector.timelineManager.addEventListener(WebInspector.TimelineManager.Event.RecordingStarted, this._recordingStarted, this); - WebInspector.timelineManager.addEventListener(WebInspector.TimelineManager.Event.RecordingStopped, this._recordingStopped, this); - - function delayedWork() - { - // Prime the creation of the singleton TimelineContentCiew since it needs to listen for events. - // It needs to be delayed since TimelineContentView depends on WebInspector.timelineSidebarPanel existing. - this._timelineContentView = WebInspector.contentBrowser.contentViewForRepresentedObject(WebInspector.timelineManager.recording); - } - - setTimeout(delayedWork.bind(this), 0); -}; - -WebInspector.TimelineSidebarPanel.StatusBarStyleClass = "status-bar"; -WebInspector.TimelineSidebarPanel.RecordGlyphStyleClass = "record-glyph"; -WebInspector.TimelineSidebarPanel.RecordGlyphRecordingStyleClass = "recording"; -WebInspector.TimelineSidebarPanel.RecordGlyphRecordingForcedStyleClass = "forced"; -WebInspector.TimelineSidebarPanel.RecordStatusStyleClass = "record-status"; -WebInspector.TimelineSidebarPanel.TitleBarStyleClass = "title-bar"; -WebInspector.TimelineSidebarPanel.TimelinesTitleBarStyleClass = "timelines"; -WebInspector.TimelineSidebarPanel.TimelineEventsTitleBarStyleClass = "timeline-events"; -WebInspector.TimelineSidebarPanel.TimelinesContentContainerStyleClass = "timelines-content"; -WebInspector.TimelineSidebarPanel.StripeBackgroundStyleClass = "stripe-background"; -WebInspector.TimelineSidebarPanel.CloseButtonStyleClass = "close-button"; -WebInspector.TimelineSidebarPanel.LargeIconStyleClass = "large"; -WebInspector.TimelineSidebarPanel.StopwatchIconStyleClass = "stopwatch-icon"; -WebInspector.TimelineSidebarPanel.NetworkIconStyleClass = "network-icon"; -WebInspector.TimelineSidebarPanel.ColorsIconStyleClass = "colors-icon"; -WebInspector.TimelineSidebarPanel.ScriptIconStyleClass = "script-icon"; -WebInspector.TimelineSidebarPanel.TimelineContentViewShowingStyleClass = "timeline-content-view-showing"; -WebInspector.TimelineSidebarPanel.ShowingTimelineContentViewCookieKey = "timeline-sidebar-panel-showing-timeline-content-view"; -WebInspector.TimelineSidebarPanel.SelectedTimelineViewIdentifierCookieKey = "timeline-sidebar-panel-selected-timeline-view-identifier"; -WebInspector.TimelineSidebarPanel.OverviewTimelineIdentifierCookieValue = "overview"; - -WebInspector.TimelineSidebarPanel.prototype = { - constructor: WebInspector.TimelineSidebarPanel, - __proto__: WebInspector.NavigationSidebarPanel.prototype, - - // Public - - showDefaultContentView: function() - { - WebInspector.contentBrowser.showContentView(this._timelineContentView); - }, - - treeElementForRepresentedObject: function(representedObject) - { - if (representedObject instanceof WebInspector.TimelineRecording) - return this._timelineOverviewTreeElement; - - // The main resource is used as the representedObject instead of Frame in our tree. - if (representedObject instanceof WebInspector.Frame) - representedObject = representedObject.mainResource; - - var foundTreeElement = this.contentTreeOutline.getCachedTreeElement(representedObject); - if (foundTreeElement) - return foundTreeElement; - - // Look for TreeElements loosely based on represented objects that can contain the represented - // object we are really looking for. This allows a SourceCodeTimelineTreeElement or a - // TimelineRecordTreeElement to stay selected when the Resource it represents is showing. - - function looselyCompareRepresentedObjects(candidateTreeElement) - { - if (!candidateTreeElement) - return false; - - var candidateRepresentedObject = candidateTreeElement.representedObject; - if (candidateRepresentedObject instanceof WebInspector.SourceCodeTimeline) { - if (candidateRepresentedObject.sourceCode === representedObject) - return true; - return false; - } - - if (candidateRepresentedObject instanceof WebInspector.TimelineRecord) { - if (!candidateRepresentedObject.sourceCodeLocation) - return false; - if (candidateRepresentedObject.sourceCodeLocation.sourceCode === representedObject) - return true; - return false; - } - - console.error("Unknown TreeElement"); - return false; - } - - // Check the selected tree element first so we don't need to do a longer search and it is - // likely to be the best candidate for the current view. - if (looselyCompareRepresentedObjects(this.contentTreeOutline.selectedTreeElement)) - return this.contentTreeOutline.selectedTreeElement; - - var currentTreeElement = this._contentTreeOutline.children[0]; - while (currentTreeElement && !currentTreeElement.root) { - if (looselyCompareRepresentedObjects(currentTreeElement)) - return currentTreeElement; - currentTreeElement = currentTreeElement.traverseNextTreeElement(false, null, false); - } - - return null; - }, - - get contentTreeOutlineLabel() - { - return this._timelineEventsTitleBarElement.textContent; - }, - - set contentTreeOutlineLabel(label) - { - label = label || WebInspector.UIString("Timeline Events"); - - this._timelineEventsTitleBarElement.textContent = label; - this.filterBar.placeholder = WebInspector.UIString("Filter %s").format(label); - }, - - showTimelineOverview: function() - { - if (this._timelinesTreeOutline.selectedTreeElement) - this._timelinesTreeOutline.selectedTreeElement.deselect(); - - this._timelineContentView.showOverviewTimelineView(); - WebInspector.contentBrowser.showContentView(this._timelineContentView); - }, - - showTimelineView: function(identifier) - { - console.assert(this._timelineTreeElementMap.has(identifier)); - if (!this._timelineTreeElementMap.has(identifier)) - return; - - this._timelineTreeElementMap.get(identifier).select(true, false, true, true); - - this._timelineContentView.showTimelineView(identifier); - WebInspector.contentBrowser.showContentView(this._timelineContentView); - }, - - // Protected - - updateCustomContentOverflow: function() - { - if (!this._stripeBackgroundElement) - return; - - var contentHeight = this.contentTreeOutline.element.offsetHeight; - var currentHeight = parseInt(this._stripeBackgroundElement.style.height); - if (currentHeight !== contentHeight) - this._stripeBackgroundElement.style.height = contentHeight + "px"; - }, - - hasCustomFilters: function() - { - return true; - }, - - matchTreeElementAgainstCustomFilters: function(treeElement) - { - if (!this._timelineContentView) - return true; - - return this._timelineContentView.matchTreeElementAgainstCustomFilters(treeElement); - }, - - canShowDifferentContentView: function() - { - return !this.restoringState || !this._restoredShowingTimelineContentView; - }, - - saveStateToCookie: function(cookie) - { - console.assert(cookie); - - cookie[WebInspector.timelineSidebarPanel.ShowingTimelineContentViewCookieKey] = WebInspector.contentBrowser.currentContentView instanceof WebInspector.TimelineContentView; - - var selectedTreeElement = this._timelinesTreeOutline.selectedTreeElement; - if (selectedTreeElement) - cookie[WebInspector.TimelineSidebarPanel.SelectedTimelineViewIdentifierCookieKey] = selectedTreeElement.representedObject; - else - cookie[WebInspector.TimelineSidebarPanel.SelectedTimelineViewIdentifierCookieKey] = WebInspector.TimelineSidebarPanel.OverviewTimelineIdentifierCookieValue; - - WebInspector.NavigationSidebarPanel.prototype.saveStateToCookie.call(this, cookie); - }, - - restoreStateFromCookie: function(cookie, relaxedMatchDelay) - { - console.assert(cookie); - - // The _timelineContentView is not ready on initial load, so delay the restore. - // This matches the delayed work in the WebInspector.TimelineSidebarPanel constructor. - if (!this._timelineContentView) { - setTimeout(this.restoreStateFromCookie.bind(this, cookie, relaxedMatchDelay), 0); - return; - } - - this._restoredShowingTimelineContentView = cookie[WebInspector.timelineSidebarPanel.ShowingTimelineContentViewCookieKey]; - - var selectedTimelineViewIdentifier = cookie[WebInspector.TimelineSidebarPanel.SelectedTimelineViewIdentifierCookieKey]; - if (selectedTimelineViewIdentifier === WebInspector.TimelineSidebarPanel.OverviewTimelineIdentifierCookieValue) - this.showTimelineOverview(); - else - this.showTimelineView(selectedTimelineViewIdentifier); - - WebInspector.NavigationSidebarPanel.prototype.restoreStateFromCookie.call(this, cookie, relaxedMatchDelay); - }, - - // Private - - _timelinesTreeElementSelected: function(treeElement, selectedByUser) - { - console.assert(this._timelineTreeElementMap.get(treeElement.representedObject) === treeElement); - this.showTimelineView(treeElement.representedObject); - }, - - _contentBrowserCurrentContentViewDidChange: function(event) - { - if (WebInspector.contentBrowser.currentContentView instanceof WebInspector.TimelineContentView) - this.element.classList.add(WebInspector.TimelineSidebarPanel.TimelineContentViewShowingStyleClass); - else - this.element.classList.remove(WebInspector.TimelineSidebarPanel.TimelineContentViewShowingStyleClass); - }, - - _recordingStarted: function(event) - { - this._recordStatusElement.textContent = WebInspector.UIString("Recording"); - this._recordGlyphElement.classList.add(WebInspector.TimelineSidebarPanel.RecordGlyphRecordingStyleClass); - }, - - _recordingStopped: function(event) - { - this._recordStatusElement.textContent = ""; - this._recordGlyphElement.classList.remove(WebInspector.TimelineSidebarPanel.RecordGlyphRecordingStyleClass); - }, - - _recordGlyphMousedOver: function(event) - { - this._recordGlyphElement.classList.remove(WebInspector.TimelineSidebarPanel.RecordGlyphRecordingForcedStyleClass); - - if (WebInspector.timelineManager.recordingEnabled) - this._recordStatusElement.textContent = WebInspector.UIString("Stop Recording"); - else - this._recordStatusElement.textContent = WebInspector.UIString("Start Recording"); - }, - - _recordGlyphMousedOut: function(event) - { - this._recordGlyphElement.classList.remove(WebInspector.TimelineSidebarPanel.RecordGlyphRecordingForcedStyleClass); - - if (WebInspector.timelineManager.recordingEnabled) - this._recordStatusElement.textContent = WebInspector.UIString("Recording"); - else - this._recordStatusElement.textContent = ""; - }, - - _recordGlyphClicked: function(event) - { - // Add forced class to prevent the glyph from showing a confusing status after click. - this._recordGlyphElement.classList.add(WebInspector.TimelineSidebarPanel.RecordGlyphRecordingForcedStyleClass); - - if (WebInspector.timelineManager.recordingEnabled) - WebInspector.timelineManager.stopRecording(); - else - WebInspector.timelineManager.startRecording(); - } -}; diff --git a/Source/WebInspectorUI/UserInterface/TimelineView.css b/Source/WebInspectorUI/UserInterface/TimelineView.css deleted file mode 100644 index 923ed7e20..000000000 --- a/Source/WebInspectorUI/UserInterface/TimelineView.css +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.timeline-view { - position: absolute; - top: 0; - left: 0; - right: 0; - bottom: 0; -} diff --git a/Source/WebInspectorUI/UserInterface/TimelineView.js b/Source/WebInspectorUI/UserInterface/TimelineView.js deleted file mode 100644 index 08e8191b0..000000000 --- a/Source/WebInspectorUI/UserInterface/TimelineView.js +++ /dev/null @@ -1,208 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.TimelineView = function() -{ - WebInspector.Object.call(this); - - this._contentTreeOutline = WebInspector.timelineSidebarPanel.createContentTreeOutline(); - - this.element = document.createElement("div"); - this.element.classList.add(WebInspector.TimelineView.StyleClassName); - - this._zeroTime = 0; - this._startTime = 0; - this._endTime = 5; - this._currentTime = 0; -}; - -WebInspector.TimelineView.StyleClassName = "timeline-view"; - -WebInspector.TimelineView.Event = { - SelectionPathComponentsDidChange: "timeline-view-selection-path-components-did-change" -}; - -WebInspector.TimelineView.prototype = { - constructor: WebInspector.TimelineView, - __proto__: WebInspector.Object.prototype, - - // Public - - get navigationSidebarTreeOutline() - { - return this._contentTreeOutline; - }, - - get navigationSidebarTreeOutlineLabel() - { - // Implemented by sub-classes if needed. - return null; - }, - - get selectionPathComponents() - { - if (!this._contentTreeOutline.selectedTreeElement || this._contentTreeOutline.selectedTreeElement.hidden) - return null; - - var pathComponent = new WebInspector.GeneralTreeElementPathComponent(this._contentTreeOutline.selectedTreeElement); - pathComponent.addEventListener(WebInspector.HierarchicalPathComponent.Event.SiblingWasSelected, this.treeElementPathComponentSelected, this); - return [pathComponent]; - }, - - get zeroTime() - { - return this._zeroTime; - }, - - set zeroTime(x) - { - if (this._zeroTime === x) - return; - - this._zeroTime = x || 0; - - this.needsLayout(); - }, - - get startTime() - { - return this._startTime; - }, - - set startTime(x) - { - if (this._startTime === x) - return; - - this._startTime = x || 0; - - this.needsLayout(); - }, - - get endTime() - { - return this._endTime; - }, - - set endTime(x) - { - if (this._endTime === x) - return; - - this._endTime = x || 0; - - this.needsLayout(); - }, - - get currentTime() - { - return this._currentTime; - }, - - set currentTime(x) - { - if (this._currentTime === x) - return; - - var oldCurrentTime = this._currentTime; - - this._currentTime = x || 0; - - function checkIfLayoutIsNeeded(currentTime) - { - // Include some wiggle room since the current time markers can be clipped off the ends a bit and still partially visible. - const wiggleTime = 0.05; // 50ms - return this._startTime - wiggleTime <= currentTime && currentTime <= this._endTime + wiggleTime; - } - - if (checkIfLayoutIsNeeded.call(this, oldCurrentTime) || checkIfLayoutIsNeeded.call(this, this._currentTime)) - this.needsLayout(); - }, - - get visible() - { - return this._visible; - }, - - reset: function() - { - this._contentTreeOutline.removeChildren(); - }, - - shown: function() - { - this._visible = true; - - // Implemented by sub-classes if needed. - }, - - hidden: function() - { - // Implemented by sub-classes if needed. - - this._visible = false; - }, - - matchTreeElementAgainstCustomFilters: function(treeElement) - { - // Implemented by sub-classes if needed. - return true; - }, - - updateLayout: function() - { - if (this._scheduledLayoutUpdateIdentifier) { - cancelAnimationFrame(this._scheduledLayoutUpdateIdentifier); - delete this._scheduledLayoutUpdateIdentifier; - } - - // Implemented by sub-classes if needed. - }, - - updateLayoutIfNeeded: function() - { - if (!this._scheduledLayoutUpdateIdentifier) - return; - this.updateLayout(); - }, - - // Protected - - treeElementPathComponentSelected: function(event) - { - // Implemented by sub-classes if needed. - }, - - needsLayout: function() - { - if (!this._visible) - return; - - if (this._scheduledLayoutUpdateIdentifier) - return; - - this._scheduledLayoutUpdateIdentifier = requestAnimationFrame(this.updateLayout.bind(this)); - } -}; diff --git a/Source/WebInspectorUI/UserInterface/ToggleButtonNavigationItem.js b/Source/WebInspectorUI/UserInterface/ToggleButtonNavigationItem.js deleted file mode 100644 index fd44a6e7a..000000000 --- a/Source/WebInspectorUI/UserInterface/ToggleButtonNavigationItem.js +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ToggleButtonNavigationItem = function(identifier, defaultToolTip, alternateToolTip, defaultImage, alternateImage, imageWidth, imageHeight, suppressEmboss) { - WebInspector.ButtonNavigationItem.call(this, identifier, defaultToolTip, defaultImage, imageWidth, imageHeight, suppressEmboss); - - this._toggled = false; - this._defaultImage = defaultImage; - this._alternateImage = alternateImage; - this._defaultToolTip = defaultToolTip; - this._alternateToolTip = alternateToolTip || defaultToolTip; -}; - -WebInspector.ToggleButtonNavigationItem.StyleClassName = "toggle"; - -WebInspector.ToggleButtonNavigationItem.prototype = { - constructor: WebInspector.ToggleButtonNavigationItem, - - // Public - - get defaultToolTip() - { - return this._defaultToolTip; - }, - - get alternateToolTip() - { - return this._alternateToolTip; - }, - - set alternateToolTip(toolTip) - { - this._alternateToolTip = toolTip; - - if (this._toggled) - this.toolTip = this._alternateToolTip; - }, - - get defaultImage() - { - return this._defaultImage; - }, - - get alternateImage() - { - return this._alternateImage; - }, - - set alternateImage(image) - { - this._alternateImage = image; - - if (this._toggled) - this.image = this._alternateImage; - }, - - get toggled() - { - return this._toggled; - }, - - set toggled(flag) - { - flag = flag || false; - - if (this._toggled === flag) - return; - - this._toggled = flag; - - if (this._toggled) { - this.toolTip = this._alternateToolTip; - this.image = this._alternateImage; - } else { - this.toolTip = this._defaultToolTip; - this.image = this._defaultImage; - } - }, - - // Private - - _additionalClassNames: [WebInspector.ToggleButtonNavigationItem.StyleClassName, WebInspector.ButtonNavigationItem.StyleClassName], - - // The image isn't cacheable because it dynamically changes and the same canvas identifier is reused. - // FIXME: We could try overriding _canvasIdentifier() to return different identifiers. If we did that - // we would also need to override generateStyleText() to use the different identifiers. - _imageCacheable: false -}; - -WebInspector.ToggleButtonNavigationItem.prototype.__proto__ = WebInspector.ButtonNavigationItem.prototype; diff --git a/Source/WebInspectorUI/UserInterface/ToggleControlToolbarItem.js b/Source/WebInspectorUI/UserInterface/ToggleControlToolbarItem.js deleted file mode 100644 index b9a3bdb8f..000000000 --- a/Source/WebInspectorUI/UserInterface/ToggleControlToolbarItem.js +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.ToggleControlToolbarItem = function(identifier, defaultToolTip, alternateToolTip, defaultImage, alternateImage, imageWidth, imageHeight) { - WebInspector.ToggleButtonNavigationItem.call(this, identifier, defaultToolTip, alternateToolTip, defaultImage, alternateImage, imageWidth, imageHeight, false); -}; - -WebInspector.ToggleControlToolbarItem.StyleClassName = "toggle"; - -WebInspector.ToggleControlToolbarItem.prototype = { - constructor: WebInspector.ToggleControlToolbarItem, - - // Private - - _additionalClassNames: [WebInspector.ToggleControlToolbarItem.StyleClassName, WebInspector.ControlToolbarItem.StyleClassName] -}; - -WebInspector.ToggleControlToolbarItem.prototype.__proto__ = WebInspector.ToggleButtonNavigationItem.prototype; diff --git a/Source/WebInspectorUI/UserInterface/Toolbar.css b/Source/WebInspectorUI/UserInterface/Toolbar.css deleted file mode 100644 index f3f65674d..000000000 --- a/Source/WebInspectorUI/UserInterface/Toolbar.css +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.toolbar { - display: -webkit-flex; - - white-space: nowrap; - overflow: hidden; - - border-bottom: 1px solid rgb(85, 85, 85); - - outline: none; -} - -.toolbar.icon-and-label-vertical { - height: 56px; -} - -.toolbar.icon-and-label-vertical.small-size { - height: 48px; -} - -.toolbar.icon-and-label-horizontal, -.toolbar.icon-only { - height: 40px; -} - -.toolbar.icon-and-label-horizontal.small-size, -.toolbar.icon-only.small-size, -.toolbar.label-only { - height: 32px; -} - -body.docked .toolbar { - background-image: -webkit-linear-gradient(top, rgb(216, 216, 216), rgb(190, 190, 190)); - box-shadow: inset rgba(255, 255, 255, 0.1) 0 1px 0, inset rgba(0, 0, 0, 0.02) 0 -1px 0; -} - -body:not(.docked) .toolbar .item.button > .label { - /* We need to disable sub-pixel antialiasing in the toolbar when not docked because the - toolbar is transparent and so is the WebView. */ - -webkit-font-smoothing: antialiased; - - /* Compensate for the text not being sub-pixel antialiased by adding a small stroke. */ - -webkit-text-stroke: 0.2px; -} - -body.window-inactive .toolbar { - border-bottom: 1px solid rgb(128, 128, 128); -} - -.toolbar .control-section { - display: -webkit-flex; - - -webkit-flex-direction: column; - -webkit-align-items: center; - -webkit-justify-content: center; - - padding-left: 6px; - padding-right: 6px; - - min-width: -webkit-min-content; -} - -.toolbar.icon-and-label-horizontal.small-size .control-section, -.toolbar.icon-only.small-size .control-section, -.toolbar.label-only .control-section { - -webkit-flex-direction: row; -} - -.toolbar .item-section { - display: -webkit-flex; - min-width: -webkit-min-content; -} - -.toolbar .item-section:not(.center) { - -webkit-flex: 1; -} - -.toolbar .item-section.left { - -webkit-justify-content: flex-start; - margin-right: 12px; -} - -.toolbar .item-section.center { - -webkit-flex: 2; - -webkit-justify-content: center; -} - -.toolbar .item-section.right { - -webkit-justify-content: flex-end; - margin-left: 12px; - margin-right: 12px; -} - -.toolbar .item { - display: -webkit-flex; - outline: none; -} diff --git a/Source/WebInspectorUI/UserInterface/Toolbar.js b/Source/WebInspectorUI/UserInterface/Toolbar.js deleted file mode 100644 index 643fdb4f2..000000000 --- a/Source/WebInspectorUI/UserInterface/Toolbar.js +++ /dev/null @@ -1,240 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.Toolbar = function(element, navigationItems) { - WebInspector.NavigationBar.call(this, element, navigationItems, "toolbar"); - - this.displayMode = WebInspector.Toolbar.DisplayMode.IconAndLabelVertical; - this.sizeMode = WebInspector.Toolbar.SizeMode.Normal; - - this._controlSectionElement = document.createElement("div"); - this._controlSectionElement.className = WebInspector.Toolbar.ControlSectionStyleClassName; - this._element.appendChild(this._controlSectionElement); - - this._leftSectionElement = document.createElement("div"); - this._leftSectionElement.className = WebInspector.Toolbar.ItemSectionStyleClassName + " " + WebInspector.Toolbar.LeftItemSectionStyleClassName; - this._leftSectionElement.setAttribute("role", "tablist"); - this._element.appendChild(this._leftSectionElement); - - this._centerSectionElement = document.createElement("div"); - this._centerSectionElement.className = WebInspector.Toolbar.ItemSectionStyleClassName + " " + WebInspector.Toolbar.CenterItemSectionStyleClassName; - this._element.appendChild(this._centerSectionElement); - - this._rightSectionElement = document.createElement("div"); - this._rightSectionElement.className = WebInspector.Toolbar.ItemSectionStyleClassName + " " + WebInspector.Toolbar.RightItemSectionStyleClassName; - this._rightSectionElement.setAttribute("role", "tablist"); - this._element.appendChild(this._rightSectionElement); - - this._element.addEventListener("contextmenu", this._handleContextMenuEvent.bind(this), false); -}; - -WebInspector.Object.addConstructorFunctions(WebInspector.Toolbar); - -WebInspector.Toolbar.StyleClassName = "toolbar"; -WebInspector.Toolbar.ControlSectionStyleClassName = "control-section"; -WebInspector.Toolbar.ItemSectionStyleClassName = "item-section"; -WebInspector.Toolbar.LeftItemSectionStyleClassName = "left"; -WebInspector.Toolbar.CenterItemSectionStyleClassName = "center"; -WebInspector.Toolbar.RightItemSectionStyleClassName = "right"; -WebInspector.Toolbar.TotalSectionMargins = 12 * 3; - -WebInspector.Toolbar.Event = { - DisplayModeDidChange: "toolbar-display-mode-did-change", - SizeModeDidChange: "toolbar-size-mode-did-change" -}; - -WebInspector.Toolbar.Section = { - Control: "control", - Left: "left", - Center: "center", - Right: "right" -}; - -WebInspector.Toolbar.DisplayMode = { - IconAndLabelVertical: "icon-and-label-vertical", - IconAndLabelHorizontal: "icon-and-label-horizontal", - IconOnly: "icon-only", - LabelOnly: "label-only" -}; - -WebInspector.Toolbar.SizeMode = { - Normal: "normal-size", - Small: "small-size" -}; - -WebInspector.Toolbar.prototype = { - constructor: WebInspector.Toolbar, - - // Public - - get displayMode() - { - return this._displayMode; - }, - - set displayMode(mode) - { - if (mode === this._displayMode) - return; - - if (this._displayMode) - this._element.classList.remove(this._displayMode); - - // Revert the forced icon-only mode if it was applied. - if (this._displayMode === WebInspector.Toolbar.DisplayMode.IconAndLabelHorizontal) - this._element.classList.remove(WebInspector.Toolbar.DisplayMode.IconOnly); - - this._displayMode = mode; - - this._element.classList.add(mode); - - this.updateLayout(); - - this.dispatchEventToListeners(WebInspector.Toolbar.Event.DisplayModeDidChange); - }, - - get sizeMode() - { - return this._sizeMode; - }, - - set sizeMode(mode) - { - if (mode === this._sizeMode) - return; - - if (this._sizeMode) - this._element.classList.remove(this._sizeMode); - - this._sizeMode = mode; - - this._element.classList.add(mode); - - this.updateLayout(); - - this.dispatchEventToListeners(WebInspector.Toolbar.Event.SizeModeDidChange); - }, - - customUpdateLayout: function() - { - // Bail early if our sections are not created yet. This means we are being called during construction. - if (!this._leftSectionElement || !this._centerSectionElement || !this._rightSectionElement) - return; - - // Remove the collapsed style class to test if the items can fit at full width. - this._element.classList.remove(WebInspector.NavigationBar.CollapsedStyleClassName); - - // Revert the forced icon-only mode if it was applied. - if (this._displayMode === WebInspector.Toolbar.DisplayMode.IconAndLabelHorizontal) { - this._element.classList.remove(WebInspector.Toolbar.DisplayMode.IconOnly); - this._element.classList.add(WebInspector.Toolbar.DisplayMode.IconAndLabelHorizontal); - } - - function isOverflowingToolbar() - { - var controlSectionWidth = this._controlSectionElement.offsetWidth; - var leftSectionWidth = this._leftSectionElement.offsetWidth; - var rightSectionWidth = this._rightSectionElement.offsetWidth; - var centerSectionWidth = this._centerSectionElement.offsetWidth; - - // Add one to the actual toolbar width to allow some slop. This wasn't needed when sub-pixel layout was on, - // but that was disabled in: http://webkit.org/b/149209 - var toolbarWidth = this.element.offsetWidth + 1; - - return controlSectionWidth + leftSectionWidth + centerSectionWidth + rightSectionWidth + WebInspector.Toolbar.TotalSectionMargins > toolbarWidth; - } - - // Only the horizontal display mode supports collapsing labels. - // If any sections are overflowing the toolbar then force the display mode to be icon only. - if (this._displayMode === WebInspector.Toolbar.DisplayMode.IconAndLabelHorizontal && isOverflowingToolbar.call(this)) { - this._element.classList.remove(WebInspector.Toolbar.DisplayMode.IconAndLabelHorizontal); - this._element.classList.add(WebInspector.Toolbar.DisplayMode.IconOnly); - } - - if (!isOverflowingToolbar.call(this)) - return; - - this._element.classList.add(WebInspector.NavigationBar.CollapsedStyleClassName); - }, - - addToolbarItem: function(toolbarItem, sectionIdentifier) - { - var sectionElement; - - switch (sectionIdentifier) { - case WebInspector.Toolbar.Section.Control: - sectionElement = this._controlSectionElement; - break; - - case WebInspector.Toolbar.Section.Left: - sectionElement = this._leftSectionElement; - break; - - default: - case WebInspector.Toolbar.Section.Center: - sectionElement = this._centerSectionElement; - break; - - case WebInspector.Toolbar.Section.Right: - sectionElement = this._rightSectionElement; - break; - } - - console.assert(sectionElement); - - this.addNavigationItem(toolbarItem, sectionElement); - }, - - // Private - - _handleContextMenuEvent: function(event) - { - var contextMenu = new WebInspector.ContextMenu(event); - - contextMenu.appendCheckboxItem(WebInspector.UIString("Icon and Text (Vertical)"), this._changeDisplayMode.bind(this, WebInspector.Toolbar.DisplayMode.IconAndLabelVertical), this._displayMode === WebInspector.Toolbar.DisplayMode.IconAndLabelVertical); - contextMenu.appendCheckboxItem(WebInspector.UIString("Icon and Text (Horizontal)"), this._changeDisplayMode.bind(this, WebInspector.Toolbar.DisplayMode.IconAndLabelHorizontal), this._displayMode === WebInspector.Toolbar.DisplayMode.IconAndLabelHorizontal); - contextMenu.appendCheckboxItem(WebInspector.UIString("Icon Only"), this._changeDisplayMode.bind(this, WebInspector.Toolbar.DisplayMode.IconOnly), this._displayMode === WebInspector.Toolbar.DisplayMode.IconOnly); - contextMenu.appendCheckboxItem(WebInspector.UIString("Text Only"), this._changeDisplayMode.bind(this, WebInspector.Toolbar.DisplayMode.LabelOnly), this._displayMode === WebInspector.Toolbar.DisplayMode.LabelOnly); - - if (this._displayMode !== WebInspector.Toolbar.DisplayMode.LabelOnly) { - contextMenu.appendSeparator(); - contextMenu.appendCheckboxItem(WebInspector.UIString("Small Icons"), this._toggleSmallIcons.bind(this), this._sizeMode === WebInspector.Toolbar.SizeMode.Small); - } - - contextMenu.show(); - }, - - _changeDisplayMode: function(displayMode) - { - this.displayMode = displayMode; - }, - - _toggleSmallIcons: function() - { - this.sizeMode = this._sizeMode === WebInspector.Toolbar.SizeMode.Normal ? WebInspector.Toolbar.SizeMode.Small : WebInspector.Toolbar.SizeMode.Normal; - } -}; - -WebInspector.Toolbar.prototype.__proto__ = WebInspector.NavigationBar.prototype; diff --git a/Source/WebInspectorUI/UserInterface/TopDownProfileDataGridTree.js b/Source/WebInspectorUI/UserInterface/TopDownProfileDataGridTree.js deleted file mode 100644 index bfcc25eee..000000000 --- a/Source/WebInspectorUI/UserInterface/TopDownProfileDataGridTree.js +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (C) 2009 280 North Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.TopDownProfileDataGridNode = function(/*ProfileView*/ profileView, /*ProfileNode*/ profileNode, /*TopDownProfileDataGridTree*/ owningTree) -{ - var hasChildren = (profileNode.children && profileNode.children.length); - - WebInspector.ProfileDataGridNode.call(this, profileView, profileNode, owningTree, hasChildren); - - this._remainingChildren = profileNode.children; -} - -WebInspector.TopDownProfileDataGridNode.prototype = { - _sharedPopulate: function() - { - var children = this._remainingChildren; - var childrenLength = children.length; - - for (var i = 0; i < childrenLength; ++i) - this.appendChild(new WebInspector.TopDownProfileDataGridNode(this.profileView, children[i], this.tree)); - - this._remainingChildren = null; - }, - - _exclude: function(aCallUID) - { - if (this._remainingChildren) - this._populate(); - - this._save(); - - var children = this.children; - var index = this.children.length; - - while (index--) - children[index]._exclude(aCallUID); - - var child = this.childrenByCallUID[aCallUID]; - - if (child) - this._merge(child, true); - } -} - -WebInspector.TopDownProfileDataGridNode.prototype.__proto__ = WebInspector.ProfileDataGridNode.prototype; - -WebInspector.TopDownProfileDataGridTree = function(/*ProfileView*/ profileView, /*ProfileNode*/ profileNode) -{ - WebInspector.ProfileDataGridTree.call(this, profileView, profileNode); - - this._remainingChildren = profileNode.children; - - WebInspector.TopDownProfileDataGridNode.prototype._populate.call(this); -} - -WebInspector.TopDownProfileDataGridTree.prototype = { - focus: function(/*ProfileDataGridNode*/ profileDataGrideNode) - { - if (!profileDataGrideNode) - return; - - this._save(); - profileDataGrideNode.savePosition(); - - this.children = [profileDataGrideNode]; - this.totalTime = profileDataGrideNode.totalTime; - }, - - exclude: function(/*ProfileDataGridNode*/ profileDataGrideNode) - { - if (!profileDataGrideNode) - return; - - this._save(); - - var excludedCallUID = profileDataGrideNode.callUID; - - WebInspector.TopDownProfileDataGridNode.prototype._exclude.call(this, excludedCallUID); - - if (this.lastComparator) - this.sort(this.lastComparator, true); - }, - - restore: function() - { - if (!this._savedChildren) - return; - - this.children[0].restorePosition(); - - WebInspector.ProfileDataGridTree.prototype.restore.call(this); - }, - - _merge: WebInspector.TopDownProfileDataGridNode.prototype._merge, - - _sharedPopulate: WebInspector.TopDownProfileDataGridNode.prototype._sharedPopulate -} - -WebInspector.TopDownProfileDataGridTree.prototype.__proto__ = WebInspector.ProfileDataGridTree.prototype; diff --git a/Source/WebInspectorUI/UserInterface/TreeElementStatusButton.css b/Source/WebInspectorUI/UserInterface/TreeElementStatusButton.css deleted file mode 100644 index 52aa562d3..000000000 --- a/Source/WebInspectorUI/UserInterface/TreeElementStatusButton.css +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -.item > .status > .status-button { - width: 16px; - height: 16px; - display: inline-block; -} - -.item > .status > .status-button > svg * { - fill: rgb(112, 126, 139); -} - -.item.selected > .status > .status-button > svg * { - fill: white; -} - -.item.selected > .status > .status-button:active > svg * { - fill: rgba(255, 255, 255, 0.75); -} - -.item > .status > .status-button.disabled > svg * { - fill: rgba(112, 126, 139, 0.5) !important; -} - -.item.selected > .status > .status-button.disabled > svg * { - fill: rgba(255, 255, 255, 0.5) !important; -} diff --git a/Source/WebInspectorUI/UserInterface/TreeElementStatusButton.js b/Source/WebInspectorUI/UserInterface/TreeElementStatusButton.js deleted file mode 100644 index 8ee6d82a3..000000000 --- a/Source/WebInspectorUI/UserInterface/TreeElementStatusButton.js +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.TreeElementStatusButton = function(element) { - WebInspector.Object.call(this); - - console.assert(element); - - this._element = element; - this._element.classList.add(WebInspector.TreeElementStatusButton.StyleClassName); - this._element.addEventListener("click", this._clicked.bind(this)); -}; - -WebInspector.TreeElementStatusButton.StyleClassName = "status-button"; -WebInspector.TreeElementStatusButton.DisabledStyleClassName = "disabled"; - -WebInspector.TreeElementStatusButton.Event = { - Clicked: "status-button-clicked" -}; - -WebInspector.TreeElementStatusButton.prototype = { - constructor: WebInspector.TreeElementStatusButton, - - // Public - - get element() - { - return this._element; - }, - - get hidden() - { - return !this._element.classList.contains(WebInspector.TreeElementStatusButton.DisabledStyleClassName); - }, - - set hidden(flag) - { - if (flag) - this._element.classList.remove("hidden"); - else - this._element.classList.add("hidden"); - }, - - get enabled() - { - return !this._element.classList.contains(WebInspector.TreeElementStatusButton.DisabledStyleClassName); - }, - - set enabled(flag) - { - if (flag) - this._element.classList.remove(WebInspector.TreeElementStatusButton.DisabledStyleClassName); - else - this._element.classList.add(WebInspector.TreeElementStatusButton.DisabledStyleClassName); - }, - - // Private - - _clicked: function(event) - { - if (!this.enabled) - return; - - event.stopPropagation(); - - this.dispatchEventToListeners(WebInspector.TreeElementStatusButton.Event.Clicked, event); - } -}; - -WebInspector.TreeElementStatusButton.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/TreeOutline.js b/Source/WebInspectorUI/UserInterface/TreeOutline.js deleted file mode 100644 index ec21c70a8..000000000 --- a/Source/WebInspectorUI/UserInterface/TreeOutline.js +++ /dev/null @@ -1,1094 +0,0 @@ -/* - * Copyright (C) 2007, 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/** - * @constructor - */ -function TreeOutline(listNode) -{ - WebInspector.Object.call(this); - - this.element = listNode; - - /** - * @type {Array.} - */ - this.children = []; - this.selectedTreeElement = null; - this._childrenListNode = listNode; - this._childrenListNode.removeChildren(); - this._knownTreeElements = []; - this._treeElementsExpandedState = []; - this.expandTreeElementsWhenArrowing = false; - this.allowsRepeatSelection = false; - this.root = true; - this.hasChildren = false; - this.expanded = true; - this.selected = false; - this.treeOutline = this; - - this._childrenListNode.tabIndex = 0; - this._childrenListNode.addEventListener("keydown", this._treeKeyDown.bind(this), true); -} - -TreeOutline._knownTreeElementNextIdentifier = 1; -TreeOutline.prototype.constructor = TreeOutline; - -TreeOutline.prototype.appendChild = function(child) -{ - if (!child) - throw("child can't be undefined or null"); - - var lastChild = this.children[this.children.length - 1]; - if (lastChild) { - lastChild.nextSibling = child; - child.previousSibling = lastChild; - } else { - child.previousSibling = null; - child.nextSibling = null; - } - - var isFirstChild = !this.children.length; - - this.children.push(child); - this.hasChildren = true; - child.parent = this; - child.treeOutline = this.treeOutline; - child.treeOutline._rememberTreeElement(child); - - var current = child.children[0]; - while (current) { - current.treeOutline = this.treeOutline; - current.treeOutline._rememberTreeElement(current); - current = current.traverseNextTreeElement(false, child, true); - } - - if (child.hasChildren && child.treeOutline._treeElementsExpandedState[child.identifier] !== undefined) - child.expanded = child.treeOutline._treeElementsExpandedState[child.identifier]; - - if (this._childrenListNode) - child._attach(); - - if (this.treeOutline.onadd) - this.treeOutline.onadd(child); - - if (isFirstChild && this.expanded) - this.expand(); -} - -TreeOutline.prototype.insertChild = function(child, index) -{ - if (!child) - throw("child can't be undefined or null"); - - var previousChild = (index > 0 ? this.children[index - 1] : null); - if (previousChild) { - previousChild.nextSibling = child; - child.previousSibling = previousChild; - } else { - child.previousSibling = null; - } - - var nextChild = this.children[index]; - if (nextChild) { - nextChild.previousSibling = child; - child.nextSibling = nextChild; - } else { - child.nextSibling = null; - } - - var isFirstChild = !this.children.length; - - this.children.splice(index, 0, child); - this.hasChildren = true; - child.parent = this; - child.treeOutline = this.treeOutline; - child.treeOutline._rememberTreeElement(child); - - var current = child.children[0]; - while (current) { - current.treeOutline = this.treeOutline; - current.treeOutline._rememberTreeElement(current); - current = current.traverseNextTreeElement(false, child, true); - } - - if (child.hasChildren && child.treeOutline._treeElementsExpandedState[child.identifier] !== undefined) - child.expanded = child.treeOutline._treeElementsExpandedState[child.identifier]; - - if (this._childrenListNode) - child._attach(); - - if (this.treeOutline.onadd) - this.treeOutline.onadd(child); - - if (isFirstChild && this.expanded) - this.expand(); -} - -TreeOutline.prototype.removeChildAtIndex = function(childIndex, suppressOnDeselect, suppressSelectSibling) -{ - if (childIndex < 0 || childIndex >= this.children.length) - throw("childIndex out of range"); - - var child = this.children[childIndex]; - this.children.splice(childIndex, 1); - - var parent = child.parent; - if (child.deselect(suppressOnDeselect)) { - if (child.previousSibling && !suppressSelectSibling) - child.previousSibling.select(true, false); - else if (child.nextSibling && !suppressSelectSibling) - child.nextSibling.select(true, false); - else if (!suppressSelectSibling) - parent.select(true, false); - } - - if (child.previousSibling) - child.previousSibling.nextSibling = child.nextSibling; - if (child.nextSibling) - child.nextSibling.previousSibling = child.previousSibling; - - if (child.treeOutline) { - child.treeOutline._forgetTreeElement(child); - child.treeOutline._forgetChildrenRecursive(child); - } - - child._detach(); - child.treeOutline = null; - child.parent = null; - child.nextSibling = null; - child.previousSibling = null; - - if (this.treeOutline && this.treeOutline.onremove) - this.treeOutline.onremove(child); -} - -TreeOutline.prototype.removeChild = function(child, suppressOnDeselect, suppressSelectSibling) -{ - if (!child) - throw("child can't be undefined or null"); - - var childIndex = this.children.indexOf(child); - if (childIndex === -1) - throw("child not found in this node's children"); - - this.removeChildAtIndex(childIndex, suppressOnDeselect, suppressSelectSibling); -} - -TreeOutline.prototype.removeChildren = function(suppressOnDeselect) -{ - var treeOutline = this.treeOutline; - - for (var i = 0; i < this.children.length; ++i) { - var child = this.children[i]; - child.deselect(suppressOnDeselect); - - if (child.treeOutline) { - child.treeOutline._forgetTreeElement(child); - child.treeOutline._forgetChildrenRecursive(child); - } - - child._detach(); - child.treeOutline = null; - child.parent = null; - child.nextSibling = null; - child.previousSibling = null; - - if (treeOutline && treeOutline.onremove) - treeOutline.onremove(child); - } - - this.children = []; -} - -TreeOutline.prototype.removeChildrenRecursive = function(suppressOnDeselect) -{ - var childrenToRemove = this.children; - - var treeOutline = this.treeOutline; - - var child = this.children[0]; - while (child) { - if (child.children.length) - childrenToRemove = childrenToRemove.concat(child.children); - child = child.traverseNextTreeElement(false, this, true); - } - - for (var i = 0; i < childrenToRemove.length; ++i) { - child = childrenToRemove[i]; - child.deselect(suppressOnDeselect); - - if (child.treeOutline) - child.treeOutline._forgetTreeElement(child); - - child._detach(); - child.children = []; - child.treeOutline = null; - child.parent = null; - child.nextSibling = null; - child.previousSibling = null; - - if (treeOutline && treeOutline.onremove) - treeOutline.onremove(child); - } - - this.children = []; -} - -TreeOutline.prototype._rememberTreeElement = function(element) -{ - if (!this._knownTreeElements[element.identifier]) - this._knownTreeElements[element.identifier] = []; - - // check if the element is already known - var elements = this._knownTreeElements[element.identifier]; - if (elements.indexOf(element) !== -1) - return; - - // add the element - elements.push(element); -} - -TreeOutline.prototype._forgetTreeElement = function(element) -{ - if (this.selectedTreeElement === element) - this.selectedTreeElement = null; - if (this._knownTreeElements[element.identifier]) - this._knownTreeElements[element.identifier].remove(element, true); -} - -TreeOutline.prototype._forgetChildrenRecursive = function(parentElement) -{ - var child = parentElement.children[0]; - while (child) { - this._forgetTreeElement(child); - child = child.traverseNextTreeElement(false, parentElement, true); - } -} - -TreeOutline.prototype.getCachedTreeElement = function(representedObject) -{ - if (!representedObject) - return null; - - if (representedObject.__treeElementIdentifier) { - // If this representedObject has a tree element identifier, and it is a known TreeElement - // in our tree we can just return that tree element. - var elements = this._knownTreeElements[representedObject.__treeElementIdentifier]; - if (elements) { - for (var i = 0; i < elements.length; ++i) - if (elements[i].representedObject === representedObject) - return elements[i]; - } - } - return null; -} - -TreeOutline.prototype.findTreeElement = function(representedObject, isAncestor, getParent) -{ - if (!representedObject) - return null; - - var cachedElement = this.getCachedTreeElement(representedObject); - if (cachedElement) - return cachedElement; - - // The representedObject isn't known, so we start at the top of the tree and work down to find the first - // tree element that represents representedObject or one of its ancestors. - var item; - var found = false; - for (var i = 0; i < this.children.length; ++i) { - item = this.children[i]; - if (item.representedObject === representedObject || (isAncestor && isAncestor(item.representedObject, representedObject))) { - found = true; - break; - } - } - - if (!found) - return null; - - // Make sure the item that we found is connected to the root of the tree. - // Build up a list of representedObject's ancestors that aren't already in our tree. - var ancestors = []; - var currentObject = representedObject; - while (currentObject) { - ancestors.unshift(currentObject); - if (currentObject === item.representedObject) - break; - currentObject = getParent(currentObject); - } - - // For each of those ancestors we populate them to fill in the tree. - for (var i = 0; i < ancestors.length; ++i) { - // Make sure we don't call findTreeElement with the same representedObject - // again, to prevent infinite recursion. - if (ancestors[i] === representedObject) - continue; - // FIXME: we could do something faster than findTreeElement since we will know the next - // ancestor exists in the tree. - item = this.findTreeElement(ancestors[i], isAncestor, getParent); - if (item) - item.onpopulate(); - } - - return this.getCachedTreeElement(representedObject); -} - -TreeOutline.prototype._treeElementDidChange = function(treeElement) -{ - if (treeElement.treeOutline !== this) - return; - - if (this.onchange) - this.onchange(treeElement); -} - -TreeOutline.prototype.treeElementFromPoint = function(x, y) -{ - var node = this._childrenListNode.ownerDocument.elementFromPoint(x, y); - if (!node) - return null; - - var listNode = node.enclosingNodeOrSelfWithNodeNameInArray(["ol", "li"]); - if (listNode) - return listNode.parentTreeElement || listNode.treeElement; - return null; -} - -TreeOutline.prototype._treeKeyDown = function(event) -{ - if (event.target !== this._childrenListNode) - return; - - if (!this.selectedTreeElement || event.shiftKey || event.metaKey || event.ctrlKey) - return; - - var handled = false; - var nextSelectedElement; - if (event.keyIdentifier === "Up" && !event.altKey) { - nextSelectedElement = this.selectedTreeElement.traversePreviousTreeElement(true); - while (nextSelectedElement && !nextSelectedElement.selectable) - nextSelectedElement = nextSelectedElement.traversePreviousTreeElement(!this.expandTreeElementsWhenArrowing); - handled = nextSelectedElement ? true : false; - } else if (event.keyIdentifier === "Down" && !event.altKey) { - nextSelectedElement = this.selectedTreeElement.traverseNextTreeElement(true); - while (nextSelectedElement && !nextSelectedElement.selectable) - nextSelectedElement = nextSelectedElement.traverseNextTreeElement(!this.expandTreeElementsWhenArrowing); - handled = nextSelectedElement ? true : false; - } else if (event.keyIdentifier === "Left") { - if (this.selectedTreeElement.expanded) { - if (event.altKey) - this.selectedTreeElement.collapseRecursively(); - else - this.selectedTreeElement.collapse(); - handled = true; - } else if (this.selectedTreeElement.parent && !this.selectedTreeElement.parent.root) { - handled = true; - if (this.selectedTreeElement.parent.selectable) { - nextSelectedElement = this.selectedTreeElement.parent; - while (nextSelectedElement && !nextSelectedElement.selectable) - nextSelectedElement = nextSelectedElement.parent; - handled = nextSelectedElement ? true : false; - } else if (this.selectedTreeElement.parent) - this.selectedTreeElement.parent.collapse(); - } - } else if (event.keyIdentifier === "Right") { - if (!this.selectedTreeElement.revealed()) { - this.selectedTreeElement.reveal(); - handled = true; - } else if (this.selectedTreeElement.hasChildren) { - handled = true; - if (this.selectedTreeElement.expanded) { - nextSelectedElement = this.selectedTreeElement.children[0]; - while (nextSelectedElement && !nextSelectedElement.selectable) - nextSelectedElement = nextSelectedElement.nextSibling; - handled = nextSelectedElement ? true : false; - } else { - if (event.altKey) - this.selectedTreeElement.expandRecursively(); - else - this.selectedTreeElement.expand(); - } - } - } else if (event.keyCode === 8 /* Backspace */ || event.keyCode === 46 /* Delete */) { - if (this.selectedTreeElement.ondelete) - handled = this.selectedTreeElement.ondelete(); - if (!handled && this.treeOutline.ondelete) - handled = this.treeOutline.ondelete(this.selectedTreeElement); - } else if (isEnterKey(event)) { - if (this.selectedTreeElement.onenter) - handled = this.selectedTreeElement.onenter(); - if (!handled && this.treeOutline.onenter) - handled = this.treeOutline.onenter(this.selectedTreeElement); - } else if (event.keyIdentifier === "U+0020" /* Space */) { - if (this.selectedTreeElement.onspace) - handled = this.selectedTreeElement.onspace(); - if (!handled && this.treeOutline.onspace) - handled = this.treeOutline.onspace(this.selectedTreeElement); - } - - if (nextSelectedElement) { - nextSelectedElement.reveal(); - nextSelectedElement.select(false, true); - } - - if (handled) { - event.preventDefault(); - event.stopPropagation(); - } -} - -TreeOutline.prototype.expand = function() -{ - // this is the root, do nothing -} - -TreeOutline.prototype.collapse = function() -{ - // this is the root, do nothing -} - -TreeOutline.prototype.revealed = function() -{ - return true; -} - -TreeOutline.prototype.reveal = function() -{ - // this is the root, do nothing -} - -TreeOutline.prototype.select = function() -{ - // this is the root, do nothing -} - -/** - * @param {boolean=} omitFocus - */ -TreeOutline.prototype.revealAndSelect = function(omitFocus) -{ - // this is the root, do nothing -} - -TreeOutline.prototype.__proto__ = WebInspector.Object.prototype; - -/** - * @constructor - * @param {Object=} representedObject - * @param {boolean=} hasChildren - */ -function TreeElement(title, representedObject, hasChildren) -{ - WebInspector.Object.call(this); - - this._title = title; - this.representedObject = (representedObject || {}); - - if (this.representedObject.__treeElementIdentifier) - this.identifier = this.representedObject.__treeElementIdentifier; - else { - this.identifier = TreeOutline._knownTreeElementNextIdentifier++; - this.representedObject.__treeElementIdentifier = this.identifier; - } - - this._hidden = false; - this._selectable = true; - this.expanded = false; - this.selected = false; - this.hasChildren = hasChildren; - this.children = []; - this.treeOutline = null; - this.parent = null; - this.previousSibling = null; - this.nextSibling = null; - this._listItemNode = null; -} - -TreeElement.prototype = { - constructor: TreeElement, - - arrowToggleWidth: 10, - - get selectable() { - if (this._hidden) - return false; - return this._selectable; - }, - - set selectable(x) { - this._selectable = x; - }, - - get listItemElement() { - return this._listItemNode; - }, - - get childrenListElement() { - return this._childrenListNode; - }, - - get title() { - return this._title; - }, - - set title(x) { - this._title = x; - this._setListItemNodeContent(); - this.didChange(); - }, - - get titleHTML() { - return this._titleHTML; - }, - - set titleHTML(x) { - this._titleHTML = x; - this._setListItemNodeContent(); - this.didChange(); - }, - - get tooltip() { - return this._tooltip; - }, - - set tooltip(x) { - this._tooltip = x; - if (this._listItemNode) - this._listItemNode.title = x ? x : ""; - this.didChange(); - }, - - get hasChildren() { - return this._hasChildren; - }, - - set hasChildren(x) { - if (this._hasChildren === x) - return; - - this._hasChildren = x; - - if (!this._listItemNode) - return; - - if (x) - this._listItemNode.classList.add("parent"); - else { - this._listItemNode.classList.remove("parent"); - this.collapse(); - } - - this.didChange(); - }, - - get hidden() { - return this._hidden; - }, - - set hidden(x) { - if (this._hidden === x) - return; - - this._hidden = x; - - if (x) { - if (this._listItemNode) - this._listItemNode.classList.add("hidden"); - if (this._childrenListNode) - this._childrenListNode.classList.add("hidden"); - } else { - if (this._listItemNode) - this._listItemNode.classList.remove("hidden"); - if (this._childrenListNode) - this._childrenListNode.classList.remove("hidden"); - } - - if (this.treeOutline && this.treeOutline.onhidden) - this.treeOutline.onhidden(this, x); - }, - - get shouldRefreshChildren() { - return this._shouldRefreshChildren; - }, - - set shouldRefreshChildren(x) { - this._shouldRefreshChildren = x; - if (x && this.expanded) - this.expand(); - }, - - _fireDidChange: function() - { - delete this._didChangeTimeoutIdentifier; - - if (this.treeOutline) - this.treeOutline._treeElementDidChange(this); - }, - - didChange: function() - { - if (!this.treeOutline) - return; - - // Prevent telling the TreeOutline multiple times in a row by delaying it with a timeout. - if (!this._didChangeTimeoutIdentifier) - this._didChangeTimeoutIdentifier = setTimeout(this._fireDidChange.bind(this), 0); - }, - - _setListItemNodeContent: function() - { - if (!this._listItemNode) - return; - - if (!this._titleHTML && !this._title) - this._listItemNode.removeChildren(); - else if (typeof this._titleHTML === "string") - this._listItemNode.innerHTML = this._titleHTML; - else if (typeof this._title === "string") - this._listItemNode.textContent = this._title; - else { - this._listItemNode.removeChildren(); - if (this._title.parentNode) - this._title.parentNode.removeChild(this._title); - this._listItemNode.appendChild(this._title); - } - } -} - -TreeElement.prototype.appendChild = TreeOutline.prototype.appendChild; -TreeElement.prototype.insertChild = TreeOutline.prototype.insertChild; -TreeElement.prototype.removeChild = TreeOutline.prototype.removeChild; -TreeElement.prototype.removeChildAtIndex = TreeOutline.prototype.removeChildAtIndex; -TreeElement.prototype.removeChildren = TreeOutline.prototype.removeChildren; -TreeElement.prototype.removeChildrenRecursive = TreeOutline.prototype.removeChildrenRecursive; - -TreeElement.prototype._attach = function() -{ - if (!this._listItemNode || this.parent._shouldRefreshChildren) { - if (this._listItemNode && this._listItemNode.parentNode) - this._listItemNode.parentNode.removeChild(this._listItemNode); - - this._listItemNode = this.treeOutline._childrenListNode.ownerDocument.createElement("li"); - this._listItemNode.treeElement = this; - this._setListItemNodeContent(); - this._listItemNode.title = this._tooltip ? this._tooltip : ""; - - if (this.hidden) - this._listItemNode.classList.add("hidden"); - if (this.hasChildren) - this._listItemNode.classList.add("parent"); - if (this.expanded) - this._listItemNode.classList.add("expanded"); - if (this.selected) - this._listItemNode.classList.add("selected"); - - this._listItemNode.addEventListener("mousedown", TreeElement.treeElementMouseDown, false); - this._listItemNode.addEventListener("click", TreeElement.treeElementToggled, false); - this._listItemNode.addEventListener("dblclick", TreeElement.treeElementDoubleClicked, false); - - if (this.onattach) - this.onattach(this); - } - - var nextSibling = null; - if (this.nextSibling && this.nextSibling._listItemNode && this.nextSibling._listItemNode.parentNode === this.parent._childrenListNode) - nextSibling = this.nextSibling._listItemNode; - this.parent._childrenListNode.insertBefore(this._listItemNode, nextSibling); - if (this._childrenListNode) - this.parent._childrenListNode.insertBefore(this._childrenListNode, this._listItemNode.nextSibling); - if (this.selected) - this.select(); - if (this.expanded) - this.expand(); -} - -TreeElement.prototype._detach = function() -{ - if (this.ondetach) - this.ondetach(this); - if (this._listItemNode && this._listItemNode.parentNode) - this._listItemNode.parentNode.removeChild(this._listItemNode); - if (this._childrenListNode && this._childrenListNode.parentNode) - this._childrenListNode.parentNode.removeChild(this._childrenListNode); -} - -TreeElement.treeElementMouseDown = function(event) -{ - var element = event.currentTarget; - if (!element || !element.treeElement || !element.treeElement.selectable) - return; - - if (element.treeElement.isEventWithinDisclosureTriangle(event)) { - event.preventDefault(); - return; - } - - element.treeElement.selectOnMouseDown(event); -} - -TreeElement.treeElementToggled = function(event) -{ - var element = event.currentTarget; - if (!element || !element.treeElement) - return; - - var toggleOnClick = element.treeElement.toggleOnClick && !element.treeElement.selectable; - var isInTriangle = element.treeElement.isEventWithinDisclosureTriangle(event); - if (!toggleOnClick && !isInTriangle) - return; - - if (element.treeElement.expanded) { - if (event.altKey) - element.treeElement.collapseRecursively(); - else - element.treeElement.collapse(); - } else { - if (event.altKey) - element.treeElement.expandRecursively(); - else - element.treeElement.expand(); - } - event.stopPropagation(); -} - -TreeElement.treeElementDoubleClicked = function(event) -{ - var element = event.currentTarget; - if (!element || !element.treeElement) - return; - - if (element.treeElement.isEventWithinDisclosureTriangle(event)) - return; - - if (element.treeElement.ondblclick) - element.treeElement.ondblclick.call(element.treeElement, event); - else if (element.treeElement.hasChildren && !element.treeElement.expanded) - element.treeElement.expand(); -} - -TreeElement.prototype.collapse = function() -{ - if (this._listItemNode) - this._listItemNode.classList.remove("expanded"); - if (this._childrenListNode) - this._childrenListNode.classList.remove("expanded"); - - this.expanded = false; - if (this.treeOutline) - this.treeOutline._treeElementsExpandedState[this.identifier] = false; - - if (this.oncollapse) - this.oncollapse(this); - - if (this.treeOutline && this.treeOutline.oncollapse) - this.treeOutline.oncollapse(this); -} - -TreeElement.prototype.collapseRecursively = function() -{ - var item = this; - while (item) { - if (item.expanded) - item.collapse(); - item = item.traverseNextTreeElement(false, this, true); - } -} - -TreeElement.prototype.expand = function() -{ - if (this.expanded && !this._shouldRefreshChildren && this._childrenListNode) - return; - - // Set this before onpopulate. Since onpopulate can add elements and call onadd, this makes - // sure the expanded flag is true before calling those functions. This prevents the possibility - // of an infinite loop if onpopulate or onadd were to call expand. - - this.expanded = true; - if (this.treeOutline) - this.treeOutline._treeElementsExpandedState[this.identifier] = true; - - // If there are no children, return. We will be expanded once we have children. - if (!this.hasChildren) - return; - - if (this.treeOutline && (!this._childrenListNode || this._shouldRefreshChildren)) { - if (this._childrenListNode && this._childrenListNode.parentNode) - this._childrenListNode.parentNode.removeChild(this._childrenListNode); - - this._childrenListNode = this.treeOutline._childrenListNode.ownerDocument.createElement("ol"); - this._childrenListNode.parentTreeElement = this; - this._childrenListNode.classList.add("children"); - - if (this.hidden) - this._childrenListNode.classList.add("hidden"); - - this.onpopulate(); - - for (var i = 0; i < this.children.length; ++i) - this.children[i]._attach(); - - delete this._shouldRefreshChildren; - } - - if (this._listItemNode) { - this._listItemNode.classList.add("expanded"); - if (this._childrenListNode && this._childrenListNode.parentNode != this._listItemNode.parentNode) - this.parent._childrenListNode.insertBefore(this._childrenListNode, this._listItemNode.nextSibling); - } - - if (this._childrenListNode) - this._childrenListNode.classList.add("expanded"); - - if (this.onexpand) - this.onexpand(this); - - if (this.treeOutline && this.treeOutline.onexpand) - this.treeOutline.onexpand(this); -} - -TreeElement.prototype.expandRecursively = function(maxDepth) -{ - var item = this; - var info = {}; - var depth = 0; - - // The Inspector uses TreeOutlines to represents object properties, so recursive expansion - // in some case can be infinite, since JavaScript objects can hold circular references. - // So default to a recursion cap of 3 levels, since that gives fairly good results. - if (typeof maxDepth === "undefined" || typeof maxDepth === "null") - maxDepth = 3; - - while (item) { - if (depth < maxDepth) - item.expand(); - item = item.traverseNextTreeElement(false, this, (depth >= maxDepth), info); - depth += info.depthChange; - } -} - -TreeElement.prototype.hasAncestor = function(ancestor) { - if (!ancestor) - return false; - - var currentNode = this.parent; - while (currentNode) { - if (ancestor === currentNode) - return true; - currentNode = currentNode.parent; - } - - return false; -} - -TreeElement.prototype.reveal = function() -{ - var currentAncestor = this.parent; - while (currentAncestor && !currentAncestor.root) { - if (!currentAncestor.expanded) - currentAncestor.expand(); - currentAncestor = currentAncestor.parent; - } - - if (this.onreveal) - this.onreveal(this); -} - -TreeElement.prototype.revealed = function() -{ - var currentAncestor = this.parent; - while (currentAncestor && !currentAncestor.root) { - if (!currentAncestor.expanded) - return false; - currentAncestor = currentAncestor.parent; - } - - return true; -} - -TreeElement.prototype.selectOnMouseDown = function(event) -{ - this.select(false, true); -} - -/** - * @param {boolean=} omitFocus - * @param {boolean=} selectedByUser - */ -TreeElement.prototype.select = function(omitFocus, selectedByUser, suppressOnSelect, suppressOnDeselect) -{ - if (!this.treeOutline || !this.selectable) - return; - - if (this.selected && !this.treeOutline.allowsRepeatSelection) - return; - - if (!omitFocus) - this.treeOutline._childrenListNode.focus(); - - // Focusing on another node may detach "this" from tree. - if (!this.treeOutline) - return; - - this.treeOutline.processingSelectionChange = true; - - if (!this.selected) { - if (this.treeOutline.selectedTreeElement) - this.treeOutline.selectedTreeElement.deselect(suppressOnDeselect); - - this.selected = true; - this.treeOutline.selectedTreeElement = this; - - if (this._listItemNode) - this._listItemNode.classList.add("selected"); - } - - if (this.onselect && !suppressOnSelect) - this.onselect(this, selectedByUser); - - if (this.treeOutline.onselect && !suppressOnSelect) - this.treeOutline.onselect(this, selectedByUser); - - delete this.treeOutline.processingSelectionChange; -} - -/** - * @param {boolean=} omitFocus - */ -TreeElement.prototype.revealAndSelect = function(omitFocus, selectedByUser, suppressOnSelect, suppressOnDeselect) -{ - this.reveal(); - this.select(omitFocus, selectedByUser, suppressOnSelect, suppressOnDeselect); -} - -/** - * @param {boolean=} suppressOnDeselect - */ -TreeElement.prototype.deselect = function(suppressOnDeselect) -{ - if (!this.treeOutline || this.treeOutline.selectedTreeElement !== this || !this.selected) - return false; - - this.selected = false; - this.treeOutline.selectedTreeElement = null; - - if (this._listItemNode) - this._listItemNode.classList.remove("selected"); - - if (this.ondeselect && !suppressOnDeselect) - this.ondeselect(this); - - if (this.treeOutline.ondeselect && !suppressOnDeselect) - this.treeOutline.ondeselect(this); - - return true; -} - -TreeElement.prototype.onpopulate = function() -{ - // Overriden by subclasses. -} - -/** - * @param {boolean} skipUnrevealed - * @param {(TreeOutline|TreeElement)=} stayWithin - * @param {boolean=} dontPopulate - * @param {Object=} info - * @return {TreeElement} - */ -TreeElement.prototype.traverseNextTreeElement = function(skipUnrevealed, stayWithin, dontPopulate, info) -{ - if (!dontPopulate && this.hasChildren) - this.onpopulate.call(this); // FIXME: This shouldn't need to use call, but this is working around a JSC bug. https://webkit.org/b/74811 - - if (info) - info.depthChange = 0; - - var element = skipUnrevealed ? (this.revealed() ? this.children[0] : null) : this.children[0]; - if (element && (!skipUnrevealed || (skipUnrevealed && this.expanded))) { - if (info) - info.depthChange = 1; - return element; - } - - if (this === stayWithin) - return null; - - element = skipUnrevealed ? (this.revealed() ? this.nextSibling : null) : this.nextSibling; - if (element) - return element; - - element = this; - while (element && !element.root && !(skipUnrevealed ? (element.revealed() ? element.nextSibling : null) : element.nextSibling) && element.parent !== stayWithin) { - if (info) - info.depthChange -= 1; - element = element.parent; - } - - if (!element) - return null; - - return (skipUnrevealed ? (element.revealed() ? element.nextSibling : null) : element.nextSibling); -} - -/** - * @param {boolean} skipUnrevealed - * @param {boolean=} dontPopulate - * @return {TreeElement} - */ -TreeElement.prototype.traversePreviousTreeElement = function(skipUnrevealed, dontPopulate) -{ - var element = skipUnrevealed ? (this.revealed() ? this.previousSibling : null) : this.previousSibling; - if (!dontPopulate && element && element.hasChildren) - element.onpopulate(); - - while (element && (skipUnrevealed ? (element.revealed() && element.expanded ? element.children[element.children.length - 1] : null) : element.children[element.children.length - 1])) { - if (!dontPopulate && element.hasChildren) - element.onpopulate(); - element = (skipUnrevealed ? (element.revealed() && element.expanded ? element.children[element.children.length - 1] : null) : element.children[element.children.length - 1]); - } - - if (element) - return element; - - if (!this.parent || this.parent.root) - return null; - - return this.parent; -} - -TreeElement.prototype.isEventWithinDisclosureTriangle = function(event) -{ - // FIXME: We should not use getComputedStyle(). For that we need to get rid of using ::before for disclosure triangle. (http://webk.it/74446) - var computedLeftPadding = window.getComputedStyle(this._listItemNode).getPropertyCSSValue("padding-left").getFloatValue(CSSPrimitiveValue.CSS_PX); - var left = this._listItemNode.totalOffsetLeft + computedLeftPadding; - return event.pageX >= left && event.pageX <= left + this.arrowToggleWidth && this.hasChildren; -} - -TreeElement.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/TreeOutlineDataGridSynchronizer.js b/Source/WebInspectorUI/UserInterface/TreeOutlineDataGridSynchronizer.js deleted file mode 100644 index 041b2f938..000000000 --- a/Source/WebInspectorUI/UserInterface/TreeOutlineDataGridSynchronizer.js +++ /dev/null @@ -1,282 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -WebInspector.TreeOutlineDataGridSynchronizer = function(treeOutline, dataGrid) -{ - WebInspector.Object.call(this); - - this._treeOutline = treeOutline; - this._dataGrid = dataGrid; - this._enabled = true; - - this._treeOutline.element.parentNode.addEventListener("scroll", this._treeOutlineScrolled.bind(this)); - this._dataGrid.scrollContainer.addEventListener("scroll", this._dataGridScrolled.bind(this)); - - this._treeOutline.__dataGridNode = this._dataGrid; - - this._dataGrid.addEventListener(WebInspector.DataGrid.Event.ExpandedNode, this._dataGridNodeExpanded, this); - this._dataGrid.addEventListener(WebInspector.DataGrid.Event.CollapsedNode, this._dataGridNodeCollapsed, this); - this._dataGrid.addEventListener(WebInspector.DataGrid.Event.SelectedNodeChanged, this._dataGridNodeSelected, this); - - // FIXME: This is a hack. TreeOutline should just dispatch events via WebInspector.Object. - var existingOnAdd = treeOutline.onadd; - var existingOnRemove = treeOutline.onremove; - var existingOnExpand = treeOutline.onexpand; - var existingOnCollapse = treeOutline.oncollapse; - var existingOnHidden = treeOutline.onhidden; - var existingOnSelect = treeOutline.onselect; - - treeOutline.onadd = function(element) { - this._treeElementAdded(element); - if (existingOnAdd) - existingOnAdd.call(treeOutline, element); - }.bind(this); - - treeOutline.onremove = function(element) { - this._treeElementRemoved(element); - if (existingOnRemove) - existingOnRemove.call(treeOutline, element); - }.bind(this); - - treeOutline.onexpand = function(element) { - this._treeElementExpanded(element); - if (existingOnExpand) - existingOnExpand.call(treeOutline, element); - }.bind(this); - - treeOutline.oncollapse = function(element) { - this._treeElementCollapsed(element); - if (existingOnCollapse) - existingOnCollapse.call(treeOutline, element); - }.bind(this); - - treeOutline.onhidden = function(element, hidden) { - this._treeElementHiddenChanged(element, hidden); - if (existingOnHidden) - existingOnHidden.call(treeOutline, element, hidden); - }.bind(this); - - treeOutline.onselect = function(element, selectedByUser) { - this._treeElementSelected(element, selectedByUser); - if (existingOnSelect) - existingOnSelect.call(treeOutline, element, selectedByUser); - }.bind(this); -} - -WebInspector.TreeOutlineDataGridSynchronizer.prototype = { - constructor: WebInspector.TreeOutlineDataGridSynchronizer, - __proto__: WebInspector.Object, - - // Public - - get treeOutline() - { - return this._treeOutline; - }, - - get dataGrid() - { - return this._dataGrid; - }, - - get enabled() - { - return this._enabled; - }, - - set enabled(x) - { - this._enabled = x || false; - }, - - associate: function(treeElement, dataGridNode) - { - console.assert(treeElement); - console.assert(dataGridNode); - - treeElement.__dataGridNode = dataGridNode; - dataGridNode.__treeElement = treeElement; - }, - - synchronize: function() - { - this._dataGrid.scrollContainer.scrollTop = this._treeOutline.element.parentNode.scrollTop; - if (this._treeOutline.selectedTreeElement) - this._treeOutline.selectedTreeElement.__dataGridNode.select(true); - else if (this._dataGrid.selectedNode) - this._dataGrid.selectedNode.deselect(true); - }, - - treeElementForDataGridNode: function(dataGridNode) - { - return dataGridNode.__treeElement || null; - }, - - dataGridNodeForTreeElement: function(treeElement) - { - return treeElement.__dataGridNode || null; - }, - - // Private - - _treeOutlineScrolled: function(event) - { - if (!this._enabled) - return; - - if (this._ignoreNextTreeOutlineScrollEvent) { - delete this._ignoreNextTreeOutlineScrollEvent; - return; - } - - this._ignoreNextDataGridScrollEvent = true; - this._dataGrid.scrollContainer.scrollTop = this._treeOutline.element.parentNode.scrollTop; - }, - - _dataGridScrolled: function(event) - { - if (!this._enabled) - return; - - if (this._ignoreNextDataGridScrollEvent) { - delete this._ignoreNextDataGridScrollEvent; - return; - } - - this._ignoreNextTreeOutlineScrollEvent = true; - this._treeOutline.element.parentNode.scrollTop = this._dataGrid.scrollContainer.scrollTop; - }, - - _dataGridNodeSelected: function(event) - { - if (!this._enabled) - return; - - var dataGridNode = this._dataGrid.selectedNode; - if (dataGridNode) - dataGridNode.__treeElement.select(true, true, true, true); - }, - - _dataGridNodeExpanded: function(event) - { - if (!this._enabled) - return; - - var dataGridNode = event.data.dataGridNode; - console.assert(dataGridNode); - - if (!dataGridNode.__treeElement.expanded) - dataGridNode.__treeElement.expand(); - }, - - _dataGridNodeCollapsed: function(event) - { - if (!this._enabled) - return; - - var dataGridNode = event.data.dataGridNode; - console.assert(dataGridNode); - - if (dataGridNode.__treeElement.expanded) - dataGridNode.__treeElement.collapse(); - }, - - _treeElementSelected: function(treeElement, selectedByUser) - { - if (!this._enabled) - return; - - var dataGridNode = treeElement.__dataGridNode; - console.assert(dataGridNode); - - dataGridNode.select(true); - }, - - _treeElementAdded: function(treeElement) - { - if (!this._enabled) - return; - - var dataGridNode = treeElement.__dataGridNode; - console.assert(dataGridNode); - - var parentDataGridNode = treeElement.parent.__dataGridNode; - console.assert(dataGridNode); - - var childIndex = treeElement.parent.children.indexOf(treeElement); - console.assert(childIndex !== -1); - - parentDataGridNode.insertChild(dataGridNode, childIndex); - }, - - _treeElementRemoved: function(treeElement) - { - if (!this._enabled) - return; - - var dataGridNode = treeElement.__dataGridNode; - console.assert(dataGridNode); - - if (dataGridNode.parent) - dataGridNode.parent.removeChild(dataGridNode); - }, - - _treeElementExpanded: function(treeElement) - { - if (!this._enabled) - return; - - var dataGridNode = treeElement.__dataGridNode; - console.assert(dataGridNode); - - if (!dataGridNode.expanded) - dataGridNode.expand(); - }, - - _treeElementCollapsed: function(treeElement) - { - if (!this._enabled) - return; - - var dataGridNode = treeElement.__dataGridNode; - console.assert(dataGridNode); - - if (dataGridNode.expanded) - dataGridNode.collapse(); - }, - - _treeElementHiddenChanged: function(treeElement, hidden) - { - if (!this._enabled) - return; - - var dataGridNode = treeElement.__dataGridNode; - console.assert(dataGridNode); - - dataGridNode.element.classList.toggle("hidden", hidden); - } -} - -WebInspector.TreeOutlineDataGridSynchronizer.prototype.__proto__ = WebInspector.Object.prototype; diff --git a/Source/WebInspectorUI/UserInterface/URLUtilities.js b/Source/WebInspectorUI/UserInterface/URLUtilities.js deleted file mode 100644 index 9d5acb873..000000000 --- a/Source/WebInspectorUI/UserInterface/URLUtilities.js +++ /dev/null @@ -1,196 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -function removeURLFragment(url) -{ - var hashIndex = url.indexOf("#"); - if (hashIndex >= 0) - return url.substring(0, hashIndex); - return url; -} - -function relativePath(path, basePath) -{ - console.assert(path.charAt(0) === "/"); - console.assert(basePath.charAt(0) === "/"); - - var pathComponents = path.split("/"); - var baseComponents = basePath.replace(/\/$/, "").split("/"); - var finalComponents = []; - - var index = 1; - for (; index < pathComponents.length && index < baseComponents.length; ++index) { - if (pathComponents[index] !== baseComponents[index]) - break; - } - - for (var i = index; i < baseComponents.length; ++i) - finalComponents.push(".."); - - for (var i = index; i < pathComponents.length; ++i) - finalComponents.push(pathComponents[i]); - - return finalComponents.join("/"); -} - -function parseURL(url) -{ - url = url ? url.trim() : ""; - - var match = url.match(/^([^:]+):\/\/([^\/:]*)(?::([\d]+))?(?:(\/[^#]*)(?:#(.*))?)?$/i); - if (!match) - return {scheme: null, host: null, port: null, path: null, queryString: null, fragment: null, lastPathComponent: null}; - - var scheme = match[1].toLowerCase(); - var host = match[2].toLowerCase(); - var port = Number(match[3]) || null; - var wholePath = match[4] || null; - var fragment = match[5] || null; - var path = wholePath; - var queryString = null; - - // Split the path and the query string. - if (wholePath) { - var indexOfQuery = wholePath.indexOf("?"); - if (indexOfQuery !== -1) { - path = wholePath.substring(0, indexOfQuery); - queryString = wholePath.substring(indexOfQuery + 1); - } - path = resolveDotsInPath(path); - } - - // Find last path component. - var lastPathComponent = null; - if (path && path !== "/") { - // Skip the trailing slash if there is one. - var endOffset = path[path.length - 1] === "/" ? 1 : 0; - var lastSlashIndex = path.lastIndexOf("/", path.length - 1 - endOffset); - if (lastSlashIndex !== -1) - lastPathComponent = path.substring(lastSlashIndex + 1, path.length - endOffset); - } - - return {scheme: scheme, host: host, port: port, path: path, queryString: queryString, fragment: fragment, lastPathComponent: lastPathComponent}; -} - -function absoluteURL(partialURL, baseURL) -{ - partialURL = partialURL ? partialURL.trim() : ""; - - // Return data and javascript URLs as-is. - if (partialURL.startsWith("data:") || partialURL.startsWith("javascript:") || partialURL.startsWith("mailto:")) - return partialURL; - - // If the URL has a scheme it is already a full URL, so return it. - if (parseURL(partialURL).scheme) - return partialURL; - - // If there is no partial URL, just return the base URL. - if (!partialURL) - return baseURL || null; - - var baseURLComponents = parseURL(baseURL); - - // The base URL needs to be an absolute URL. Return null if it isn't. - if (!baseURLComponents.scheme) - return null; - - // A URL that starts with "//" is a full URL without the scheme. Use the base URL scheme. - if (partialURL[0] === "/" && partialURL[1] === "/") - return baseURLComponents.scheme + ":" + partialURL; - - // The path can be null for URLs that have just a scheme and host (like "http://apple.com"). So make the path be "/". - if (!baseURLComponents.path) - baseURLComponents.path = "/"; - - // Generate the base URL prefix that is used in the rest of the cases. - var baseURLPrefix = baseURLComponents.scheme + "://" + baseURLComponents.host + (baseURLComponents.port ? (":" + baseURLComponents.port) : ""); - - // A URL that starts with "?" is just a query string that gets applied to the base URL (replacing the base URL query string and fragment). - if (partialURL[0] === "?") - return baseURLPrefix + baseURLComponents.path + partialURL; - - // A URL that starts with "/" is an absolute path that gets applied to the base URL (replacing the base URL path, query string and fragment). - if (partialURL[0] === "/") - return baseURLPrefix + resolveDotsInPath(partialURL); - - // Generate the base path that is used in the final case by removing everything after the last "/" from the base URL's path. - var basePath = baseURLComponents.path.substring(0, baseURLComponents.path.lastIndexOf("/")) + "/"; - return baseURLPrefix + resolveDotsInPath(basePath + partialURL); -} - -function parseLocationQueryParameters(arrayResult) -{ - // The first character is always the "?". - return parseQueryString(window.location.search.substring(1), arrayResult); -} - -function parseQueryString(queryString, arrayResult) -{ - if (!queryString) - return arrayResult ? [] : {}; - - function decode(string) - { - try { - // Replace "+" with " " then decode precent encoded values. - return decodeURIComponent(string.replace(/\+/g, " ")); - } catch (e) { - return string; - } - } - - var parameters = arrayResult ? [] : {}; - var parameterStrings = queryString.split("&"); - for (var i = 0; i < parameterStrings.length; ++i) { - var pair = parameterStrings[i].split("=").map(decode); - if (arrayResult) - parameters.push({name: pair[0], value: pair[1]}); - else - parameters[pair[0]] = pair[1]; - } - - return parameters; -} - -WebInspector.displayNameForURL = function(url, urlComponents) -{ - if (!urlComponents) - urlComponents = parseURL(url); - - var displayName; - try { - displayName = decodeURIComponent(urlComponents.lastPathComponent || ""); - } catch (e) { - displayName = urlComponents.lastPathComponent; - } - - return displayName || WebInspector.displayNameForHost(urlComponents.host) || url; -} - -WebInspector.displayNameForHost = function(host) -{ - // FIXME : This should decode punycode hostnames. - return host; -} diff --git a/Source/WebInspectorUI/UserInterface/Utilities.js b/Source/WebInspectorUI/UserInterface/Utilities.js deleted file mode 100644 index 2a9f48ca6..000000000 --- a/Source/WebInspectorUI/UserInterface/Utilities.js +++ /dev/null @@ -1,951 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -Object.defineProperty(Object, "shallowCopy", -{ - value: function(object) - { - // Make a new object and copy all the key/values. The values are not copied. - var copy = {}; - var keys = Object.keys(object); - for (var i = 0; i < keys.length; ++i) - copy[keys[i]] = object[keys[i]]; - return copy; - } -}); - -Object.defineProperty(Object, "shallowEqual", -{ - value: function(a, b) - { - // Checks if two objects have the same top-level properties. - - // Check for strict equality in case they are the same object. - if (a === b) - return true; - - // Only objects can proceed. null is an object, but Object.keys throws for null. - if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) - return false; - - var aKeys = Object.keys(a); - var bKeys = Object.keys(b); - - // Check that each object has the same number of keys. - if (aKeys.length !== bKeys.length) - return false; - - // Check if all the keys and their values are equal. - for (var i = 0; i < aKeys.length; ++i) { - // Check that b has the same key as a. - if (!(aKeys[i] in b)) - return false; - - // Check that the values are strict equal since this is only - // a shallow check, not a recursive one. - if (a[aKeys[i]] !== b[aKeys[i]]) - return false; - } - - return true; - } -}); - -Object.defineProperty(Object.prototype, "valueForCaseInsensitiveKey", -{ - value: function(key) - { - if (this.hasOwnProperty(key)) - return this[key]; - - var lowerCaseKey = key.toLowerCase(); - for (var currentKey in this) { - if (currentKey.toLowerCase() === lowerCaseKey) - return this[currentKey]; - } - - return undefined; - } -}); - -Object.defineProperty(Node.prototype, "enclosingNodeOrSelfWithClass", -{ - value: function(className) - { - for (var node = this; node && node !== this.ownerDocument; node = node.parentNode) - if (node.nodeType === Node.ELEMENT_NODE && node.classList.contains(className)) - return node; - return null; - } -}); - -Object.defineProperty(Node.prototype, "enclosingNodeOrSelfWithNodeNameInArray", -{ - value: function(nameArray) - { - var lowerCaseNameArray = nameArray.map(function(name) { return name.toLowerCase() }); - for (var node = this; node && node !== this.ownerDocument; node = node.parentNode) { - for (var i = 0; i < nameArray.length; ++i) { - if (node.nodeName.toLowerCase() === lowerCaseNameArray[i]) - return node; - } - } - - return null; - } -}); - -Object.defineProperty(Node.prototype, "enclosingNodeOrSelfWithNodeName", -{ - value: function(nodeName) - { - return this.enclosingNodeOrSelfWithNodeNameInArray([nodeName]); - } -}); - -Object.defineProperty(Node.prototype, "isAncestor", -{ - value: function(node) - { - if (!node) - return false; - - var currentNode = node.parentNode; - while (currentNode) { - if (this === currentNode) - return true; - currentNode = currentNode.parentNode; - } - - return false; - } -}); - -Object.defineProperty(Node.prototype, "isDescendant", -{ - value: function(descendant) - { - return !!descendant && descendant.isAncestor(this); - } -}); - - -Object.defineProperty(Node.prototype, "isSelfOrAncestor", -{ - value: function(node) - { - return !!node && (node === this || this.isAncestor(node)); - } -}); - - -Object.defineProperty(Node.prototype, "isSelfOrDescendant", -{ - value: function(node) - { - return !!node && (node === this || this.isDescendant(node)); - } -}); - -Object.defineProperty(Node.prototype, "traverseNextNode", -{ - value: function(stayWithin) - { - var node = this.firstChild; - if (node) - return node; - - if (stayWithin && this === stayWithin) - return null; - - node = this.nextSibling; - if (node) - return node; - - node = this; - while (node && !node.nextSibling && (!stayWithin || !node.parentNode || node.parentNode !== stayWithin)) - node = node.parentNode; - if (!node) - return null; - - return node.nextSibling; - } -}); - -Object.defineProperty(Node.prototype, "traversePreviousNode", -{ - value: function(stayWithin) - { - if (stayWithin && this === stayWithin) - return null; - var node = this.previousSibling; - while (node && node.lastChild) - node = node.lastChild; - if (node) - return node; - return this.parentNode; - } -}); - - -Object.defineProperty(Node.prototype, "rangeOfWord", -{ - value: 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; - - } -}); - -Object.defineProperty(Element.prototype, "totalOffsetLeft", -{ - get: function() - { - return this.getBoundingClientRect().left; - } -}); - -Object.defineProperty(Element.prototype, "totalOffsetTop", -{ - get: function() - { - return this.getBoundingClientRect().top; - } -}); - -Object.defineProperty(Element.prototype, "removeChildren", -{ - value: function() - { - // This has been tested to be the fastest removal method. - if (this.firstChild) - this.textContent = ""; - } -}); - -Object.defineProperty(Element.prototype, "isInsertionCaretInside", -{ - value: function() - { - var selection = window.getSelection(); - if (!selection.rangeCount || !selection.isCollapsed) - return false; - var selectionRange = selection.getRangeAt(0); - return selectionRange.startContainer === this || selectionRange.startContainer.isDescendant(this); - } -}); - -Object.defineProperty(Element.prototype, "removeMatchingStyleClasses", -{ - value: function(classNameRegex) - { - var regex = new RegExp("(^|\\s+)" + classNameRegex + "($|\\s+)"); - if (regex.test(this.className)) - this.className = this.className.replace(regex, " "); - } -}); - -Object.defineProperty(Element.prototype, "createChild", -{ - value: function(elementName, className) - { - var element = this.ownerDocument.createElement(elementName); - if (className) - element.className = className; - this.appendChild(element); - return element; - } -}); - -Object.defineProperty(Element.prototype, "isScrolledToBottom", -{ - value: function() - { - // This code works only for 0-width border - return this.scrollTop + this.clientHeight === this.scrollHeight; - } -}); - -Object.defineProperty(Element.prototype, "recalculateStyles", -{ - value: function() - { - this.ownerDocument.defaultView.getComputedStyle(this); - } -}); - -Object.defineProperty(DocumentFragment.prototype, "createChild", -{ - value: Element.prototype.createChild -}); - -Object.defineProperty(Array.prototype, "contains", -{ - value: function(value) - { - return this.indexOf(value) !== -1; - } -}); - -Object.defineProperty(Array.prototype, "lastValue", -{ - get: function() - { - if (!this.length) - return undefined; - return this[this.length - 1]; - } -}); - -Object.defineProperty(Array.prototype, "remove", -{ - value: function(value, onlyFirst) - { - for (var i = this.length - 1; i >= 0; --i) { - if (this[i] === value) { - this.splice(i, 1); - if (onlyFirst) - return; - } - } - } -}); - -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, "upperBound", -{ - value: function(value) - { - var first = 0; - var count = this.length; - while (count > 0) { - var step = count >> 1; - var middle = first + step; - if (value >= this[middle]) { - first = middle + 1; - count -= step + 1; - } else - count = step; - } - return first; - } -}); - -Object.defineProperty(String.prototype, "trimMiddle", -{ - value: function(maxLength) - { - if (this.length <= maxLength) - return this; - var leftHalf = maxLength >> 1; - var rightHalf = maxLength - leftHalf - 1; - return this.substr(0, leftHalf) + "\u2026" + this.substr(this.length - rightHalf, rightHalf); - } -}); - -Object.defineProperty(String.prototype, "trimEnd", -{ - value: function(maxLength) - { - if (this.length <= maxLength) - return this; - return this.substr(0, maxLength - 1) + "\u2026"; - } -}); - -Object.defineProperty(String.prototype, "collapseWhitespace", -{ - value: function() - { - return this.replace(/[\s\xA0]+/g, " "); - } -}); - -Object.defineProperty(String.prototype, "escapeCharacters", -{ - value: 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 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; - } -}); - -Object.defineProperty(String.prototype, "escapeForRegExp", -{ - value: function() - { - return this.escapeCharacters("^[]{}()\\.$*+?|"); - } -}); - -Object.defineProperty(String.prototype, "capitalize", -{ - value: function() - { - return this.charAt(0).toUpperCase() + this.slice(1); - } -}); - -Object.defineProperty(String, "tokenizeFormatString", -{ - value: function(format) - { - var tokens = []; - var substitutionIndex = 0; - - function addStringToken(str) - { - tokens.push({ type: "string", value: str }); - } - - function addSpecifierToken(specifier, precision, substitutionIndex) - { - tokens.push({ type: "specifier", specifier: specifier, precision: precision, substitutionIndex: substitutionIndex }); - } - - var index = 0; - for (var precentIndex = format.indexOf("%", index); precentIndex !== -1; precentIndex = format.indexOf("%", index)) { - addStringToken(format.substring(index, precentIndex)); - index = precentIndex + 1; - - if (format[index] === "%") { - addStringToken("%"); - ++index; - continue; - } - - if (!isNaN(format[index])) { - // The first character is a number, it might be a substitution index. - var number = parseInt(format.substring(index), 10); - while (!isNaN(format[index])) - ++index; - - // If the number is greater than zero and ends with a "$", - // then this is a substitution index. - if (number > 0 && format[index] === "$") { - substitutionIndex = (number - 1); - ++index; - } - } - - var precision = -1; - if (format[index] === ".") { - // This is a precision specifier. If no digit follows the ".", - // then the precision should be zero. - ++index; - - precision = parseInt(format.substring(index), 10); - if (isNaN(precision)) - precision = 0; - - while (!isNaN(format[index])) - ++index; - } - - addSpecifierToken(format[index], precision, substitutionIndex); - - ++substitutionIndex; - ++index; - } - - addStringToken(format.substring(index)); - - return tokens; - } -}); - -Object.defineProperty(String.prototype, "startsWith", -{ - value: function(string) - { - return this.lastIndexOf(string, 0) === 0; - } -}); - -Object.defineProperty(String.prototype, "hash", -{ - get: function() - { - // Matches the wtf/StringHasher.h (SuperFastHash) algorithm. - - // Arbitrary start value to avoid mapping all 0's to all 0's. - const stringHashingStartValue = 0x9e3779b9; - - var result = stringHashingStartValue; - var pendingCharacter = null; - for (var i = 0; i < this.length; ++i) { - var currentCharacter = this[i].charCodeAt(0); - if (pendingCharacter === null) { - pendingCharacter = currentCharacter; - continue; - } - - result += pendingCharacter; - result = (result << 16) ^ ((currentCharacter << 11) ^ result); - result += result >> 11; - - pendingCharacter = null; - } - - // Handle the last character in odd length strings. - if (pendingCharacter !== null) { - result += pendingCharacter; - result ^= result << 11; - result += result >> 17; - } - - // Force "avalanching" of final 31 bits. - result ^= result << 3; - result += result >> 5; - result ^= result << 2; - result += result >> 15; - result ^= result << 10; - - // Prevent 0 and negative results. - return (0xffffffff + result + 1).toString(36); - } -}); - -Object.defineProperty(String, "standardFormatters", -{ - value: { - 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; - } - } -}); - -Object.defineProperty(String, "format", -{ - value: function(format, substitutions, formatters, initialValue, append) - { - if (!format || !substitutions || !substitutions.length) - return { formattedResult: append(initialValue, format), unusedSubstitutions: substitutions }; - - function prettyFunctionName() - { - return "String.format(\"" + format + "\", \"" + substitutions.join("\", \"") + "\")"; - } - - function warn(msg) - { - console.warn(prettyFunctionName() + ": " + msg); - } - - function error(msg) - { - console.error(prettyFunctionName() + ": " + msg); - } - - var result = initialValue; - var tokens = String.tokenizeFormatString(format); - 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) { - // If there are not enough substitutions for the current substitutionIndex - // just output the format specifier literally and move on. - 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)) { - // Encountered an unsupported format character, treat as a string. - 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}; - } -}); - -Object.defineProperty(String.prototype, "format", -{ - value: function() - { - return String.format(this, arguments, String.standardFormatters, "", function(a, b) { return a + b; }).formattedResult; - } -}); - -Object.defineProperty(String.prototype, "insertWordBreakCharacters", -{ - value: function() - { - // Add zero width spaces after characters that are good to break after. - // Otherwise a string with no spaces will not break and overflow its container. - // This is mainly used on URL strings, so the characters are tailored for URLs. - return this.replace(/([\/;:\)\]\}&?])/g, "$1\u200b"); - } -}); - -Object.defineProperty(String.prototype, "removeWordBreakCharacters", -{ - value: function() - { - // Undoes what insertWordBreakCharacters did. - return this.replace(/\u200b/g, ""); - } -}); - -Object.defineProperty(Number, "constrain", -{ - value: function(num, min, max) - { - if (num < min) - num = min; - else if (num > max) - num = max; - return num; - } -}); - -Object.defineProperty(Number, "secondsToString", -{ - value: function(seconds, higherResolution) - { - var ms = seconds * 1000; - - if (higherResolution && Math.abs(ms) < 100) - return WebInspector.UIString("%.2fms").format(ms); - else if (Math.abs(ms) < 100) - return WebInspector.UIString("%.1fms").format(ms); - - if (higherResolution && Math.abs(ms) < 1000) - return WebInspector.UIString("%.1fms").format(ms); - else if (Math.abs(ms) < 1000) - return WebInspector.UIString("%.0fms").format(ms); - - if (Math.abs(seconds) < 60) - return WebInspector.UIString("%.2fs").format(seconds); - - var minutes = seconds / 60; - if (Math.abs(minutes) < 60) - return WebInspector.UIString("%.1fmin").format(minutes); - - var hours = minutes / 60; - if (Math.abs(hours) < 24) - return WebInspector.UIString("%.1fhrs").format(hours); - - var days = hours / 24; - return WebInspector.UIString("%.1f days").format(days); - } -}); - -Object.defineProperty(Number, "bytesToString", -{ - value: function(bytes, higherResolution) - { - if (higherResolution === undefined) - higherResolution = true; - - if (Math.abs(bytes) < 1024) - return WebInspector.UIString("%.0f B").format(bytes); - - var kilobytes = bytes / 1024; - if (Math.abs(kilobytes) < 10 || (higherResolution && Math.abs(kilobytes) < 1024)) - return WebInspector.UIString("%.2f KB").format(kilobytes); - else if (Math.abs(kilobytes) < 1024) - return WebInspector.UIString("%.1f KB").format(kilobytes); - - var megabytes = kilobytes / 1024; - if (higherResolution || Math.abs(megabytes) < 10) - return WebInspector.UIString("%.2f MB").format(megabytes); - else - return WebInspector.UIString("%.1f MB").format(megabytes); - } -}); - -Object.defineProperty(Uint32Array, "isLittleEndian", -{ - value: function() - { - if ("_isLittleEndian" in this) - return this._isLittleEndian; - - var buffer = new ArrayBuffer(4); - var longData = new Uint32Array(buffer); - var data = new Uint8Array(buffer); - - longData[0] = 0x0a0b0c0d; - - this._isLittleEndian = data[0] === 0x0d && data[1] === 0x0c && data[2] === 0x0b && data[3] === 0x0a; - - return this._isLittleEndian; - } -}); - -function isEmptyObject(object) -{ - for (var property in object) - return false; - return true; -} - -function isEnterKey(event) -{ - // Check if this is an IME event. - return event.keyCode !== 229 && event.keyIdentifier === "Enter"; -} - -function resolveDotsInPath(path) -{ - if (!path) - return path; - - if (path.indexOf("./") === -1) - return path; - - console.assert(path.charAt(0) === "/"); - - var result = []; - - var components = path.split("/"); - for (var i = 0; i < components.length; ++i) { - var component = components[i]; - - // Skip over "./". - if (component === ".") - continue; - - // Rewind one component for "../". - if (component === "..") { - if (result.length === 1) - continue; - result.pop(); - continue; - } - - result.push(component); - } - - return result.join("/"); -} - -function parseMIMEType(fullMimeType) -{ - if (!fullMimeType) - return {type: fullMimeType, boundary: null, encoding: null}; - - var typeParts = fullMimeType.split(/\s*;\s*/); - console.assert(typeParts.length >= 1); - - var type = typeParts[0]; - var boundary = null; - var encoding = null; - - for (var i = 1; i < typeParts.length; ++i) { - var subparts = typeParts[i].split(/\s*=\s*/); - if (subparts.length !== 2) - continue; - - if (subparts[0].toLowerCase() === "boundary") - boundary = subparts[1]; - else if (subparts[0].toLowerCase() === "charset") - encoding = subparts[1].replace("^\"|\"$", ""); // Trim quotes. - } - - return {type: type, boundary: boundary || null, encoding: encoding || null}; -} - -function simpleGlobStringToRegExp(globString, regExpFlags) -{ - // Only supports "*" globs. - - if (!globString) - return null; - - // Escape everything from String.prototype.escapeForRegExp except "*". - var regexString = globString.escapeCharacters("^[]{}()\\.$+?|"); - - // Unescape all doubly escaped backslashes in front of escaped asterisks. - // So "\\*" will become "\*" again, undoing escapeCharacters escaping of "\". - // This makes "\*" match a literal "*" instead of using the "*" for globbing. - regexString = regexString.replace(/\\\\\*/g, "\\*"); - - // The following regex doesn't match an asterisk that has a backslash in front. - // It also catches consecutive asterisks so they collapse down when replaced. - var unescapedAsteriskRegex = /(^|[^\\])\*+/g; - if (unescapedAsteriskRegex.test(globString)) { - // Replace all unescaped asterisks with ".*". - regexString = regexString.replace(unescapedAsteriskRegex, "$1.*"); - - // Match edge boundaries when there is an asterisk to better meet the expectations - // of the user. When someone types "*.js" they don't expect "foo.json" to match. They - // would only expect that if they type "*.js*". We use \b (instead of ^ and $) to allow - // matches inside paths or URLs, so "ba*.js" will match "foo/bar.js" but not "boo/bbar.js". - // When there isn't an asterisk the regexString is just a substring search. - regexString = "\\b" + regexString + "\\b"; - } - - return new RegExp(regexString, regExpFlags); -} diff --git a/Source/WebInspectorUI/UserInterface/Views/ActivateButtonNavigationItem.js b/Source/WebInspectorUI/UserInterface/Views/ActivateButtonNavigationItem.js new file mode 100644 index 000000000..731c3594a --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Views/ActivateButtonNavigationItem.js @@ -0,0 +1,77 @@ +/* + * Copyright (C) 2013, 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.ActivateButtonNavigationItem = class ActivateButtonNavigationItem extends WebInspector.ButtonNavigationItem +{ + constructor(identifier, defaultToolTip, activatedToolTip, image, imageWidth, imageHeight, role) + { + super(identifier, defaultToolTip, image, imageWidth, imageHeight, role); + + this._defaultToolTip = defaultToolTip; + this._activatedToolTip = activatedToolTip || defaultToolTip; + this._role = role; + } + + // Public + + get defaultToolTip() + { + return this._defaultToolTip; + } + + get activatedToolTip() + { + return this._activatedToolTip; + } + + get activated() + { + return this.element.classList.contains(WebInspector.ActivateButtonNavigationItem.ActivatedStyleClassName); + } + + set activated(flag) + { + this.element.classList.toggle(WebInspector.ActivateButtonNavigationItem.ActivatedStyleClassName, flag); + + if (flag) { + this.toolTip = this._activatedToolTip; + if (this._role === "tab") + this.element.setAttribute("aria-selected", "true"); + } else { + this.toolTip = this._defaultToolTip; + if (this._role === "tab") + this.element.removeAttribute("aria-selected"); + } + } + + // Protected + + get additionalClassNames() + { + return ["activate", "button"]; + } +}; + +WebInspector.ActivateButtonNavigationItem.ActivatedStyleClassName = "activated"; diff --git a/Source/WebInspectorUI/UserInterface/Views/ActivateButtonToolbarItem.js b/Source/WebInspectorUI/UserInterface/Views/ActivateButtonToolbarItem.js new file mode 100644 index 000000000..2d8a747fd --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Views/ActivateButtonToolbarItem.js @@ -0,0 +1,56 @@ +/* + * Copyright (C) 2013, 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.ActivateButtonToolbarItem = class ActivateButtonToolbarItem extends WebInspector.ActivateButtonNavigationItem +{ + constructor(identifier, defaultToolTip, activatedToolTip, label, image, role) + { + super(identifier, defaultToolTip, activatedToolTip, image, 16, 16, role); + + if (typeof label === "string") { + this._labelElement = document.createElement("div"); + this._labelElement.className = WebInspector.ButtonToolbarItem.LabelStyleClassName; + this._element.appendChild(this._labelElement); + + this.label = label; + } + } + + // Public + + get label() + { + return this._labelElement.textContent; + } + + set label(newLabel) + { + console.assert(newLabel); + if (!newLabel || !this._labelElement) + return; + + this._labelElement.textContent = newLabel; + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Views/ApplicationCacheDetailsSidebarPanel.js b/Source/WebInspectorUI/UserInterface/Views/ApplicationCacheDetailsSidebarPanel.js new file mode 100644 index 000000000..4509f8d84 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Views/ApplicationCacheDetailsSidebarPanel.js @@ -0,0 +1,150 @@ +/* + * Copyright (C) 2013, 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.ApplicationCacheDetailsSidebarPanel = class ApplicationCacheDetailsSidebarPanel extends WebInspector.DetailsSidebarPanel +{ + constructor() + { + super("application-cache-details", WebInspector.UIString("Storage"), WebInspector.UIString("Storage")); + + this.element.classList.add("application-cache"); + + this._applicationCacheFrame = null; + + this._locationManifestURLRow = new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("Manifest URL")); + this._locationFrameURLRow = new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("Frame URL")); + + this._locationGroup = new WebInspector.DetailsSectionGroup([this._locationManifestURLRow, this._locationFrameURLRow]); + + this._locationSection = new WebInspector.DetailsSection("application-cache-location", WebInspector.UIString("Location"), [this._locationGroup]); + + this._onlineRow = new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("Online")); + this._statusRow = new WebInspector.DetailsSectionSimpleRow(WebInspector.UIString("Status")); + + this._statusGroup = new WebInspector.DetailsSectionGroup([this._onlineRow, this._statusRow]); + + this._statusSection = new WebInspector.DetailsSection("application-cache-status", WebInspector.UIString("Status"), [this._statusGroup]); + + this.contentView.element.appendChild(this._locationSection.element); + this.contentView.element.appendChild(this._statusSection.element); + + WebInspector.applicationCacheManager.addEventListener(WebInspector.ApplicationCacheManager.Event.NetworkStateUpdated, this._networkStateUpdated, this); + WebInspector.applicationCacheManager.addEventListener(WebInspector.ApplicationCacheManager.Event.FrameManifestStatusChanged, this._frameManifestStatusChanged, this); + } + + // Public + + inspect(objects) + { + // Convert to a single item array if needed. + if (!(objects instanceof Array)) + objects = [objects]; + + var applicationCacheFrameToInspect = null; + + // Iterate over the objects to find a WebInspector.ApplicationCacheFrame to inspect. + for (var i = 0; i < objects.length; ++i) { + if (objects[i] instanceof WebInspector.ApplicationCacheFrame) { + applicationCacheFrameToInspect = objects[i]; + break; + } + } + + this.applicationCacheFrame = applicationCacheFrameToInspect; + + return !!this.applicationCacheFrame; + } + + get applicationCacheFrame() + { + return this._applicationCacheFrame; + } + + set applicationCacheFrame(applicationCacheFrame) + { + if (this._applicationCacheFrame === applicationCacheFrame) + return; + + this._applicationCacheFrame = applicationCacheFrame; + + this.needsLayout(); + } + + // Protected + + layout() + { + if (!this.applicationCacheFrame) + return; + + this._locationFrameURLRow.value = this.applicationCacheFrame.frame.url; + this._locationManifestURLRow.value = this.applicationCacheFrame.manifest.manifestURL; + + this._refreshOnlineRow(); + this._refreshStatusRow(); + } + + // Private + + _networkStateUpdated(event) + { + if (!this.applicationCacheFrame) + return; + + this._refreshOnlineRow(); + } + + _frameManifestStatusChanged(event) + { + if (!this.applicationCacheFrame) + return; + + console.assert(event.data.frameManifest instanceof WebInspector.ApplicationCacheFrame); + if (event.data.frameManifest !== this.applicationCacheFrame) + return; + + this._refreshStatusRow(); + } + + _refreshOnlineRow() + { + this._onlineRow.value = WebInspector.applicationCacheManager.online ? WebInspector.UIString("Yes") : WebInspector.UIString("No"); + } + + _refreshStatusRow() + { + this._statusRow.value = WebInspector.ApplicationCacheDetailsSidebarPanel.Status[this.applicationCacheFrame.status]; + } +}; + +// This needs to be kept in sync with ApplicationCacheManager.js. +WebInspector.ApplicationCacheDetailsSidebarPanel.Status = { + 0: "Uncached", + 1: "Idle", + 2: "Checking", + 3: "Downloading", + 4: "UpdateReady", + 5: "Obsolete" +}; diff --git a/Source/WebInspectorUI/UserInterface/Views/ApplicationCacheFrameContentView.css b/Source/WebInspectorUI/UserInterface/Views/ApplicationCacheFrameContentView.css new file mode 100644 index 000000000..d231c1d1a --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Views/ApplicationCacheFrameContentView.css @@ -0,0 +1,32 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +.content-view.application-cache-frame > .data-grid { + position: absolute; + top: 0; + left: 0; + right: 0; + bottom: 0; +} diff --git a/Source/WebInspectorUI/UserInterface/Views/ApplicationCacheFrameContentView.js b/Source/WebInspectorUI/UserInterface/Views/ApplicationCacheFrameContentView.js new file mode 100644 index 000000000..c73fc1481 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Views/ApplicationCacheFrameContentView.js @@ -0,0 +1,229 @@ +/* + * Copyright (C) 2010, 2013-2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.ApplicationCacheFrameContentView = class ApplicationCacheFrameContentView extends WebInspector.ContentView +{ + constructor(representedObject) + { + console.assert(representedObject instanceof WebInspector.ApplicationCacheFrame); + + super(representedObject); + + this.element.classList.add("application-cache-frame"); + + this._frame = representedObject.frame; + + this._emptyView = WebInspector.createMessageTextView(WebInspector.UIString("No Application Cache information available"), false); + this._emptyView.classList.add("hidden"); + this.element.appendChild(this._emptyView); + + this._markDirty(); + + var status = representedObject.status; + this.updateStatus(status); + + WebInspector.applicationCacheManager.addEventListener(WebInspector.ApplicationCacheManager.Event.FrameManifestStatusChanged, this._updateStatus, this); + } + + shown() + { + super.shown(); + + this._maybeUpdate(); + } + + closed() + { + WebInspector.applicationCacheManager.removeEventListener(null, null, this); + + super.closed(); + } + + saveToCookie(cookie) + { + cookie.type = WebInspector.ContentViewCookieType.ApplicationCache; + cookie.frame = this.representedObject.frame.url; + cookie.manifest = this.representedObject.manifest.manifestURL; + } + + get scrollableElements() + { + if (!this._dataGrid) + return []; + return [this._dataGrid.scrollContainer]; + } + + _maybeUpdate() + { + if (!this.visible || !this._viewDirty) + return; + + this._update(); + this._viewDirty = false; + } + + _markDirty() + { + this._viewDirty = true; + } + + _updateStatus(event) + { + var frameManifest = event.data.frameManifest; + if (frameManifest !== this.representedObject) + return; + + console.assert(frameManifest instanceof WebInspector.ApplicationCacheFrame); + + this.updateStatus(frameManifest.status); + } + + updateStatus(status) + { + var oldStatus = this._status; + this._status = status; + + if (this.visible && this._status === WebInspector.ApplicationCacheManager.Status.Idle && (oldStatus === WebInspector.ApplicationCacheManager.Status.UpdateReady || !this._resources)) + this._markDirty(); + + this._maybeUpdate(); + } + + _update() + { + WebInspector.applicationCacheManager.requestApplicationCache(this._frame, this._updateCallback.bind(this)); + } + + _updateCallback(applicationCache) + { + if (!applicationCache || !applicationCache.manifestURL) { + delete this._manifest; + delete this._creationTime; + delete this._updateTime; + delete this._size; + delete this._resources; + + this._emptyView.classList.remove("hidden"); + + if (this._dataGrid) + this._dataGrid.element.classList.add("hidden"); + return; + } + + // FIXME: are these variables needed anywhere else? + this._manifest = applicationCache.manifestURL; + this._creationTime = applicationCache.creationTime; + this._updateTime = applicationCache.updateTime; + this._size = applicationCache.size; + this._resources = applicationCache.resources; + + if (!this._dataGrid) + this._createDataGrid(); + + this._populateDataGrid(); + this._dataGrid.autoSizeColumns(20, 80); + this._dataGrid.element.classList.remove("hidden"); + + this._emptyView.classList.add("hidden"); + } + + _createDataGrid() + { + var columns = {url: {}, type: {}, size: {}}; + + columns.url.title = WebInspector.UIString("Resource"); + columns.url.sortable = true; + + columns.type.title = WebInspector.UIString("Type"); + columns.type.sortable = true; + + columns.size.title = WebInspector.UIString("Size"); + columns.size.aligned = "right"; + columns.size.sortable = true; + + this._dataGrid = new WebInspector.DataGrid(columns); + this._dataGrid.addEventListener(WebInspector.DataGrid.Event.SortChanged, this._sortDataGrid, this); + + this._dataGrid.sortColumnIdentifier = "url"; + this._dataGrid.sortOrder = WebInspector.DataGrid.SortOrder.Ascending; + this._dataGrid.createSettings("application-cache-frame-content-view"); + + this.addSubview(this._dataGrid); + this._dataGrid.updateLayout(); + } + + _sortDataGrid() + { + function numberCompare(columnIdentifier, nodeA, nodeB) + { + return nodeA.data[columnIdentifier] - nodeB.data[columnIdentifier]; + } + function localeCompare(columnIdentifier, nodeA, nodeB) + { + return (nodeA.data[columnIdentifier] + "").localeCompare(nodeB.data[columnIdentifier] + ""); + } + + var comparator; + switch (this._dataGrid.sortColumnIdentifier) { + case "type": comparator = localeCompare.bind(this, "type"); break; + case "size": comparator = numberCompare.bind(this, "size"); break; + case "url": + default: comparator = localeCompare.bind(this, "url"); break; + } + + this._dataGrid.sortNodes(comparator); + } + + _populateDataGrid() + { + this._dataGrid.removeChildren(); + + for (var resource of this._resources) { + var data = { + url: resource.url, + type: resource.type, + size: Number.bytesToString(resource.size) + }; + var node = new WebInspector.DataGridNode(data); + this._dataGrid.appendChild(node); + } + } + + _deleteButtonClicked(event) + { + if (!this._dataGrid || !this._dataGrid.selectedNode) + return; + + // FIXME: Delete Button semantics are not yet defined. (Delete a single, or all?) + this._deleteCallback(this._dataGrid.selectedNode); + } + + _deleteCallback(node) + { + // FIXME: Should we delete a single (selected) resource or all resources? + // InspectorBackend.deleteCachedResource(...) + // this._update(); + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Views/ApplicationCacheFrameTreeElement.js b/Source/WebInspectorUI/UserInterface/Views/ApplicationCacheFrameTreeElement.js new file mode 100644 index 000000000..9b346cb37 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Views/ApplicationCacheFrameTreeElement.js @@ -0,0 +1,62 @@ +/* + * Copyright (C) 2013, 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.ApplicationCacheFrameTreeElement = class ApplicationCacheFrameTreeElement extends WebInspector.GeneralTreeElement +{ + constructor(representedObject) + { + console.assert(representedObject instanceof WebInspector.ApplicationCacheFrame); + + super("application-cache-frame", "", "", representedObject, false); + + this.updateTitles(); + } + + updateTitles() + { + var url = this.representedObject.frame.url; + var parsedURL = parseURL(url); + + this.mainTitle = WebInspector.displayNameForURL(url, parsedURL); + + // Show the host as the subtitle only if it doesn't match the subtitle of the manifest tree element, + // and it doesn't match the mainTitle. + var subtitle = WebInspector.displayNameForHost(parsedURL.host); + + var manifestTreeElement = null; + var currentAncestor = this.parent; + while (currentAncestor && !currentAncestor.root) { + if (currentAncestor instanceof WebInspector.ApplicationCacheManifestTreeElement) { + manifestTreeElement = currentAncestor; + break; + } + + currentAncestor = currentAncestor.parent; + } + + var subtitleIsDuplicate = subtitle === this._mainTitle || (manifestTreeElement && manifestTreeElement.subtitle === subtitle); + this.subtitle = subtitleIsDuplicate ? null : subtitle; + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Views/ApplicationCacheIcons.css b/Source/WebInspectorUI/UserInterface/Views/ApplicationCacheIcons.css new file mode 100644 index 000000000..5df7fcda3 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Views/ApplicationCacheIcons.css @@ -0,0 +1,32 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +.application-cache-manifest .icon { + content: image-set(url(../Images/ApplicationCacheManifest.png) 1x, url(../Images/ApplicationCacheManifest@2x.png) 2x); +} + +.application-cache-frame .icon { + content: image-set(url(../Images/ApplicationCache.png) 1x, url(../Images/ApplicationCache@2x.png) 2x); +} diff --git a/Source/WebInspectorUI/UserInterface/Views/ApplicationCacheManifestTreeElement.js b/Source/WebInspectorUI/UserInterface/Views/ApplicationCacheManifestTreeElement.js new file mode 100644 index 000000000..27a95c830 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Views/ApplicationCacheManifestTreeElement.js @@ -0,0 +1,72 @@ +/* + * Copyright (C) 2013, 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.ApplicationCacheManifestTreeElement = class ApplicationCacheManifestTreeElement extends WebInspector.StorageTreeElement +{ + constructor(representedObject) + { + console.assert(representedObject instanceof WebInspector.ApplicationCacheManifest); + + super("application-cache-manifest", "", representedObject); + + this.hasChildren = true; + this.expanded = true; + } + + // Public + + get name() + { + if (!this._name) + this._generateTitles(); + + return this._name; + } + + get secondaryName() + { + if (!this._secondaryName) + this._generateTitles(); + + return this._secondaryName; + } + + get categoryName() + { + return WebInspector.UIString("Application Cache"); + } + + _generateTitles() + { + var parsedURL = parseURL(this.representedObject.manifestURL); + + // Prefer the last path component, with a fallback for the host as the main title. + this._name = WebInspector.displayNameForURL(this.representedObject.manifestURL, parsedURL); + + // Show the host as the subtitle. + var secondaryName = WebInspector.displayNameForHost(parsedURL.host); + this._secondaryName = this._name !== secondaryName ? secondaryName : null; + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Views/BezierEditor.css b/Source/WebInspectorUI/UserInterface/Views/BezierEditor.css new file mode 100644 index 000000000..e95fbc1ab --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Views/BezierEditor.css @@ -0,0 +1,119 @@ +/* + * Copyright (C) 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +.bezier-editor { + width: 200px; + height: 258px; +} + +.bezier-editor > .bezier-preview { + width: calc(100% - 10px); + height: 25px; + margin: 5px 5px 0; + border-bottom: 1px solid lightgrey; +} + +.bezier-editor > .bezier-preview > div { + width: 20px; + height: 20px; + background-color: var(--selected-background-color); + border-radius: 50%; +} + +.bezier-editor > .bezier-preview-timing { + position: absolute; + top: 34px; + margin-left: 11px; + border-left: 4px solid transparent; + border-right: 4px solid transparent; + border-top: 4px solid black; +} + +.bezier-editor > .bezier-preview.animate > div, +.bezier-editor > .bezier-preview-timing.animate { + animation: bezierPreview 2.5s linear 250ms infinite; +} + +@keyframes bezierPreview { + from { transform: translate(0, 0); } + 10% { transform: translate(0, 0); } + 90% { transform: translate(170px, 0); } + to { transform: translate(170px, 0); } +} + +.bezier-editor > .bezier-container { + margin: 0 8px; +} + +.bezier-editor > .bezier-container .linear-curve { + fill: none; + stroke:lightgrey; + stroke-width: 2; + stroke-linecap: round; +} + +.bezier-editor > .bezier-container .bezier-curve { + fill: none; + stroke: black; + stroke-width: 2; + stroke-linecap: round; +} + +.bezier-editor > .bezier-container .control-line { + fill: none; + stroke: hsl(210, 100%, 49%); + stroke-width: 2; + stroke-linecap: round; +} + +.bezier-editor > .bezier-container .control-handle { + r: 5px; + fill: hsl(210, 100%, 49%); +} + +.bezier-editor > .bezier-container .control-handle.selected { + r: 7px; +} + +.bezier-editor > .number-input-container { + display: flex; + width: calc(100% - 10px); + margin: 0 5px; + padding-top: 7px; + border-top: 1px solid lightgrey; +} + +.bezier-editor > .number-input-container > input { + width: 100%; + margin: 0 2px; + padding: 1px 0 1px 1px; + text-align: right; + font-size: 12px; + background-color: white; + border: 1px solid hsl(0, 0%, 60%); + border-radius: 4px; + box-shadow: inset 0 0 1px 1px hsl(0, 0%, 89%); + outline: none; +} diff --git a/Source/WebInspectorUI/UserInterface/Views/BezierEditor.js b/Source/WebInspectorUI/UserInterface/Views/BezierEditor.js new file mode 100644 index 000000000..a07c19d6f --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Views/BezierEditor.js @@ -0,0 +1,390 @@ +/* + * Copyright (C) 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.BezierEditor = class BezierEditor extends WebInspector.Object +{ + constructor() + { + super(); + + this._element = document.createElement("div"); + this._element.classList.add("bezier-editor"); + + var editorWidth = 184; + var editorHeight = 200; + this._padding = 25; + this._controlHandleRadius = 7; + this._bezierWidth = editorWidth - (this._controlHandleRadius * 2); + this._bezierHeight = editorHeight - (this._controlHandleRadius * 2) - (this._padding * 2); + + this._bezierPreviewContainer = this._element.createChild("div", "bezier-preview"); + this._bezierPreviewContainer.title = WebInspector.UIString("Restart animation"); + this._bezierPreviewContainer.addEventListener("mousedown", this._resetPreviewAnimation.bind(this)); + + this._bezierPreview = this._bezierPreviewContainer.createChild("div"); + + this._bezierPreviewTiming = this._element.createChild("div", "bezier-preview-timing"); + + this._bezierContainer = this._element.appendChild(createSVGElement("svg")); + this._bezierContainer.setAttribute("width", editorWidth); + this._bezierContainer.setAttribute("height", editorHeight); + this._bezierContainer.classList.add("bezier-container"); + + let svgGroup = this._bezierContainer.appendChild(createSVGElement("g")); + svgGroup.setAttribute("transform", "translate(0, " + this._padding + ")"); + + let linearCurve = svgGroup.appendChild(createSVGElement("line")); + linearCurve.classList.add("linear-curve"); + linearCurve.setAttribute("x1", this._controlHandleRadius); + linearCurve.setAttribute("y1", this._bezierHeight + this._controlHandleRadius); + linearCurve.setAttribute("x2", this._bezierWidth + this._controlHandleRadius); + linearCurve.setAttribute("y2", this._controlHandleRadius); + + this._bezierCurve = svgGroup.appendChild(createSVGElement("path")); + this._bezierCurve.classList.add("bezier-curve"); + + function createControl(x1, y1) + { + x1 += this._controlHandleRadius; + y1 += this._controlHandleRadius; + + let line = svgGroup.appendChild(createSVGElement("line")); + line.classList.add("control-line"); + line.setAttribute("x1", x1); + line.setAttribute("y1", y1); + line.setAttribute("x2", x1); + line.setAttribute("y2", y1); + + let handle = svgGroup.appendChild(createSVGElement("circle")); + handle.classList.add("control-handle"); + + return {point: null, line, handle}; + } + + this._inControl = createControl.call(this, 0, this._bezierHeight); + this._outControl = createControl.call(this, this._bezierWidth, 0); + + this._numberInputContainer = this._element.createChild("div", "number-input-container"); + + function createBezierInput(id, {min, max} = {}) + { + let key = "_bezier" + id + "Input"; + this[key] = this._numberInputContainer.createChild("input"); + this[key].type = "number"; + this[key].step = 0.01; + + if (!isNaN(min)) + this[key].min = min; + + if (!isNaN(max)) + this[key].max = max; + + this[key].addEventListener("input", this.debounce(250)._handleNumberInputInput); + this[key].addEventListener("keydown", this._handleNumberInputKeydown.bind(this)); + } + + createBezierInput.call(this, "InX", {min: 0, max: 1}); + createBezierInput.call(this, "InY"); + createBezierInput.call(this, "OutX", {min: 0, max: 1}); + createBezierInput.call(this, "OutY"); + + this._selectedControl = null; + this._mouseDownPosition = null; + this._bezierContainer.addEventListener("mousedown", this); + + WebInspector.addWindowKeydownListener(this); + } + + // Public + + get element() + { + return this._element; + } + + set bezier(bezier) + { + if (!bezier) + return; + + var isCubicBezier = bezier instanceof WebInspector.CubicBezier; + console.assert(isCubicBezier); + if (!isCubicBezier) + return; + + this._bezier = bezier; + this._updateBezierPreview(); + } + + get bezier() + { + return this._bezier; + } + + removeListeners() + { + WebInspector.removeWindowKeydownListener(this); + } + + // Protected + + handleEvent(event) + { + switch (event.type) { + case "mousedown": + this._handleMousedown(event); + break; + case "mousemove": + this._handleMousemove(event); + break; + case "mouseup": + this._handleMouseup(event); + break; + } + } + + handleKeydownEvent(event) + { + if (!this._selectedControl || !this._element.parentNode) + return false; + + let horizontal = 0; + let vertical = 0; + switch (event.keyCode) { + case WebInspector.KeyboardShortcut.Key.Up.keyCode: + vertical = -1; + break; + case WebInspector.KeyboardShortcut.Key.Right.keyCode: + horizontal = 1; + break; + case WebInspector.KeyboardShortcut.Key.Down.keyCode: + vertical = 1; + break; + case WebInspector.KeyboardShortcut.Key.Left.keyCode: + horizontal = -1; + break; + default: + return false; + } + + if (event.shiftKey) { + horizontal *= 10; + vertical *= 10; + } + + vertical *= this._bezierWidth / 100; + horizontal *= this._bezierHeight / 100; + + this._selectedControl.point.x = Number.constrain(this._selectedControl.point.x + horizontal, 0, this._bezierWidth); + this._selectedControl.point.y += vertical; + this._updateControl(this._selectedControl); + this._updateValue(); + + return true; + } + + // Private + + _handleMousedown(event) + { + if (event.button !== 0) + return; + + window.addEventListener("mousemove", this, true); + window.addEventListener("mouseup", this, true); + + this._bezierPreviewContainer.classList.remove("animate"); + this._bezierPreviewTiming.classList.remove("animate"); + + this._updateControlPointsForMouseEvent(event, true); + } + + _handleMousemove(event) + { + this._updateControlPointsForMouseEvent(event); + } + + _handleMouseup(event) + { + this._selectedControl.handle.classList.remove("selected"); + this._mouseDownPosition = null; + this._triggerPreviewAnimation(); + + window.removeEventListener("mousemove", this, true); + window.removeEventListener("mouseup", this, true); + } + + _updateControlPointsForMouseEvent(event, calculateSelectedControlPoint) + { + var point = WebInspector.Point.fromEventInElement(event, this._bezierContainer); + point.x = Number.constrain(point.x - this._controlHandleRadius, 0, this._bezierWidth); + point.y -= this._controlHandleRadius + this._padding; + + if (calculateSelectedControlPoint) { + this._mouseDownPosition = point; + + if (this._inControl.point.distance(point) < this._outControl.point.distance(point)) + this._selectedControl = this._inControl; + else + this._selectedControl = this._outControl; + } + + if (event.shiftKey && this._mouseDownPosition) { + if (Math.abs(this._mouseDownPosition.x - point.x) > Math.abs(this._mouseDownPosition.y - point.y)) + point.y = this._mouseDownPosition.y; + else + point.x = this._mouseDownPosition.x; + } + + this._selectedControl.point = point; + this._selectedControl.handle.classList.add("selected"); + this._updateValue(); + } + + _updateValue() + { + function round(num) + { + return Math.round(num * 100) / 100; + } + + var inValueX = round(this._inControl.point.x / this._bezierWidth); + var inValueY = round(1 - (this._inControl.point.y / this._bezierHeight)); + + var outValueX = round(this._outControl.point.x / this._bezierWidth); + var outValueY = round(1 - (this._outControl.point.y / this._bezierHeight)); + + this._bezier = new WebInspector.CubicBezier(inValueX, inValueY, outValueX, outValueY); + this._updateBezier(); + + this.dispatchEventToListeners(WebInspector.BezierEditor.Event.BezierChanged, {bezier: this._bezier}); + } + + _updateBezier() + { + var r = this._controlHandleRadius; + var inControlX = this._inControl.point.x + r; + var inControlY = this._inControl.point.y + r; + var outControlX = this._outControl.point.x + r; + var outControlY = this._outControl.point.y + r; + var path = `M ${r} ${this._bezierHeight + r} C ${inControlX} ${inControlY} ${outControlX} ${outControlY} ${this._bezierWidth + r} ${r}`; + this._bezierCurve.setAttribute("d", path); + this._updateControl(this._inControl); + this._updateControl(this._outControl); + + this._bezierInXInput.value = this._bezier.inPoint.x; + this._bezierInYInput.value = this._bezier.inPoint.y; + this._bezierOutXInput.value = this._bezier.outPoint.x; + this._bezierOutYInput.value = this._bezier.outPoint.y; + } + + _updateControl(control) + { + control.handle.setAttribute("cx", control.point.x + this._controlHandleRadius); + control.handle.setAttribute("cy", control.point.y + this._controlHandleRadius); + + control.line.setAttribute("x2", control.point.x + this._controlHandleRadius); + control.line.setAttribute("y2", control.point.y + this._controlHandleRadius); + } + + _updateBezierPreview() + { + this._inControl.point = new WebInspector.Point(this._bezier.inPoint.x * this._bezierWidth, (1 - this._bezier.inPoint.y) * this._bezierHeight); + this._outControl.point = new WebInspector.Point(this._bezier.outPoint.x * this._bezierWidth, (1 - this._bezier.outPoint.y) * this._bezierHeight); + + this._updateBezier(); + this._triggerPreviewAnimation(); + } + + _triggerPreviewAnimation() + { + this._bezierPreview.style.animationTimingFunction = this._bezier.toString(); + this._bezierPreviewContainer.classList.add("animate"); + this._bezierPreviewTiming.classList.add("animate"); + } + + _resetPreviewAnimation() + { + var parent = this._bezierPreview.parentNode; + parent.removeChild(this._bezierPreview); + parent.appendChild(this._bezierPreview); + + this._element.removeChild(this._bezierPreviewTiming); + this._element.appendChild(this._bezierPreviewTiming); + } + + _handleNumberInputInput(event) + { + this._changeBezierForInput(event.target, event.target.value); + } + + _handleNumberInputKeydown(event) + { + let shift = 0; + if (event.keyIdentifier === "Up") + shift = 0.01; + else if (event.keyIdentifier === "Down") + shift = -0.01; + + if (!shift) + return; + + if (event.shiftKey) + shift *= 10; + + event.preventDefault(); + this._changeBezierForInput(event.target, parseFloat(event.target.value) + shift); + } + + _changeBezierForInput(target, value) + { + value = Math.round(value * 100) / 100; + + switch (target) { + case this._bezierInXInput: + this._bezier.inPoint.x = Number.constrain(value, 0, 1); + break; + case this._bezierInYInput: + this._bezier.inPoint.y = value; + break; + case this._bezierOutXInput: + this._bezier.outPoint.x = Number.constrain(value, 0, 1); + break; + case this._bezierOutYInput: + this._bezier.outPoint.y = value; + break; + default: + return; + } + + this._updateBezierPreview(); + + this.dispatchEventToListeners(WebInspector.BezierEditor.Event.BezierChanged, {bezier: this._bezier}); + } +}; + +WebInspector.BezierEditor.Event = { + BezierChanged: "bezier-editor-bezier-changed" +}; diff --git a/Source/WebInspectorUI/UserInterface/Views/BoxModelDetailsSectionRow.css b/Source/WebInspectorUI/UserInterface/Views/BoxModelDetailsSectionRow.css new file mode 100644 index 000000000..44ca9580f --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Views/BoxModelDetailsSectionRow.css @@ -0,0 +1,104 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +.details-section .row.box-model { + padding: 6px; + text-align: center; + white-space: nowrap; +} + +.details-section .row.box-model .label { + position: absolute; + color: black; + margin-left: 3px; + padding-left: 2px; + padding-right: 2px; +} + +.details-section .row.box-model :matches(.position, .margin, .border, .padding, .content) { + border: 1px solid grey; + background-color: white; + display: inline-block; + text-align: center; + vertical-align: middle; + padding: 3px; + margin: 3px; +} + +.details-section .row.box-model .position { + border-style: dotted; +} + +.details-section .row.box-model .margin { + border-style: dashed; + border-color: black; +} + +.details-section .row.box-model:not(.hovered) .margin, +.details-section .row.box-model .margin.active { + background-color: hsla(30, 88%, 69%, 0.66); +} + +.details-section .row.box-model .border { + border-color: black; +} + +.details-section .row.box-model:not(.hovered) .border, +.details-section .row.box-model .border.active { + background-color: hsla(44, 100%, 80%, 0.66); +} + +.details-section .row.box-model .padding { + border-style: dashed; +} + +.details-section .row.box-model:not(.hovered) .padding, +.details-section .row.box-model .padding.active { + background-color: hsla(101, 37%, 62%, 0.55); +} + +.details-section .row.box-model .content { + position: static; + min-width: 80px; + overflow: visible; +} + +.details-section .row.box-model:not(.hovered) .content, +.details-section .row.box-model .content.active { + background-color: hsla(208, 60%, 64%, 0.66); +} + +.details-section .row.box-model .editing { + position: relative; + z-index: 2; +} + +.details-section .row.box-model :matches(.content span, .top, .right, .bottom, .left) { + display: inline-block; +} + +.details-section .row.box-model :matches(.right, .left) { + vertical-align: middle; +} diff --git a/Source/WebInspectorUI/UserInterface/Views/BoxModelDetailsSectionRow.js b/Source/WebInspectorUI/UserInterface/Views/BoxModelDetailsSectionRow.js new file mode 100644 index 000000000..eae123d97 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Views/BoxModelDetailsSectionRow.js @@ -0,0 +1,434 @@ +/* + * Copyright (C) 2013, 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.BoxModelDetailsSectionRow = class BoxModelDetailsSectionRow extends WebInspector.DetailsSectionRow +{ + constructor() + { + super(WebInspector.UIString("No Box Model Information")); + + this.element.classList.add("box-model"); + + this._nodeStyles = null; + } + + // Public + + get nodeStyles() + { + return this._nodeStyles; + } + + set nodeStyles(nodeStyles) + { + if (this._nodeStyles && this._nodeStyles.computedStyle) + this._nodeStyles.computedStyle.removeEventListener(WebInspector.CSSStyleDeclaration.Event.PropertiesChanged, this._refresh, this); + + this._nodeStyles = nodeStyles; + if (this._nodeStyles && this._nodeStyles.computedStyle) + this._nodeStyles.computedStyle.addEventListener(WebInspector.CSSStyleDeclaration.Event.PropertiesChanged, this._refresh, this); + + this._refresh(); + } + + // Private + + _refresh() + { + if (this._ignoreNextRefresh) { + this._ignoreNextRefresh = false; + return; + } + + this._updateMetrics(); + } + + _getPropertyValueAsPx(style, propertyName) + { + return Number(style.propertyForName(propertyName).value.replace(/px$/, "") || 0); + } + + _getBox(computedStyle, componentName) + { + var suffix = this._getComponentSuffix(componentName); + var left = this._getPropertyValueAsPx(computedStyle, componentName + "-left" + suffix); + var top = this._getPropertyValueAsPx(computedStyle, componentName + "-top" + suffix); + var right = this._getPropertyValueAsPx(computedStyle, componentName + "-right" + suffix); + var bottom = this._getPropertyValueAsPx(computedStyle, componentName + "-bottom" + suffix); + return {left, top, right, bottom}; + } + + _getComponentSuffix(componentName) + { + return componentName === "border" ? "-width" : ""; + } + + _highlightDOMNode(showHighlight, mode, event) + { + event.stopPropagation(); + + var nodeId = showHighlight ? this.nodeStyles.node.id : 0; + if (nodeId) { + if (this._highlightMode === mode) + return; + this._highlightMode = mode; + WebInspector.domTreeManager.highlightDOMNode(nodeId, mode); + } else { + this._highlightMode = null; + WebInspector.domTreeManager.hideDOMNodeHighlight(); + } + + for (var i = 0; this._boxElements && i < this._boxElements.length; ++i) { + var element = this._boxElements[i]; + if (nodeId && (mode === "all" || element._name === mode)) + element.classList.add("active"); + else + element.classList.remove("active"); + } + + this.element.classList.toggle("hovered", showHighlight); + } + + _updateMetrics() + { + var metricsElement = document.createElement("div"); + var style = this._nodeStyles.computedStyle; + + function createValueElement(type, value, name, propertyName) + { + // Check if the value is a float and whether it should be rounded. + let floatValue = parseFloat(value); + let shouldRoundValue = !isNaN(floatValue) && (floatValue % 1 !== 0); + + if (isNaN(floatValue)) + value = figureDash; + + let element = document.createElement(type); + element.textContent = shouldRoundValue ? ("~" + Math.round(floatValue * 100) / 100) : value; + if (shouldRoundValue) + element.title = value; + element.addEventListener("dblclick", this._startEditing.bind(this, element, name, propertyName, style), false); + return element; + } + + function createBoxPartElement(name, side) + { + let suffix = this._getComponentSuffix(name); + let propertyName = (name !== "position" ? name + "-" : "") + side + suffix; + let value = style.propertyForName(propertyName).value; + if (value === "" || (name !== "position" && value === "0px") || (name === "position" && value === "auto")) + value = ""; + else + value = value.replace(/px$/, ""); + + let element = createValueElement.call(this, "div", value, name, propertyName); + element.className = side; + return element; + } + + function createContentAreaElement(name) + { + console.assert(name === "width" || name === "height"); + + let size = style.propertyForName(name).value.replace(/px$/, ""); + if (style.propertyForName("box-sizing").value === "border-box") { + let borderBox = this._getBox(style, "border"); + let paddingBox = this._getBox(style, "padding"); + + let [side, oppositeSide] = name === "width" ? ["left", "right"] : ["top", "bottom"]; + size = size - borderBox[side] - borderBox[oppositeSide] - paddingBox[side] - paddingBox[oppositeSide]; + } + + return createValueElement.call(this, "span", size, name, name); + } + + // Display types for which margin is ignored. + var noMarginDisplayType = { + "table-cell": true, + "table-column": true, + "table-column-group": true, + "table-footer-group": true, + "table-header-group": true, + "table-row": true, + "table-row-group": true + }; + + // Display types for which padding is ignored. + var noPaddingDisplayType = { + "table-column": true, + "table-column-group": true, + "table-footer-group": true, + "table-header-group": true, + "table-row": true, + "table-row-group": true + }; + + // Position types for which top, left, bottom and right are ignored. + var noPositionType = { + "static": true + }; + + this._boxElements = []; + + if (!style.hasProperties()) { + this.showEmptyMessage(); + return; + } + + var previousBox = null; + for (let name of ["content", "padding", "border", "margin", "position"]) { + if (name === "margin" && noMarginDisplayType[style.propertyForName("display").value]) + continue; + if (name === "padding" && noPaddingDisplayType[style.propertyForName("display").value]) + continue; + if (name === "position" && noPositionType[style.propertyForName("position").value]) + continue; + + var boxElement = document.createElement("div"); + boxElement.className = name; + boxElement._name = name; + boxElement.addEventListener("mouseover", this._highlightDOMNode.bind(this, true, name === "position" ? "all" : name), false); + this._boxElements.push(boxElement); + + if (name === "content") { + let widthElement = createContentAreaElement.call(this, "width"); + let heightElement = createContentAreaElement.call(this, "height"); + boxElement.append(widthElement, " \u00D7 ", heightElement); + } else { + var labelElement = document.createElement("div"); + labelElement.className = "label"; + labelElement.textContent = name; + boxElement.appendChild(labelElement); + + boxElement.appendChild(createBoxPartElement.call(this, name, "top")); + boxElement.appendChild(document.createElement("br")); + boxElement.appendChild(createBoxPartElement.call(this, name, "left")); + + if (previousBox) + boxElement.appendChild(previousBox); + + boxElement.appendChild(createBoxPartElement.call(this, name, "right")); + boxElement.appendChild(document.createElement("br")); + boxElement.appendChild(createBoxPartElement.call(this, name, "bottom")); + } + + previousBox = boxElement; + } + + metricsElement.appendChild(previousBox); + metricsElement.addEventListener("mouseover", this._highlightDOMNode.bind(this, false, ""), false); + + this.hideEmptyMessage(); + this.element.appendChild(metricsElement); + } + + _startEditing(targetElement, box, styleProperty, computedStyle) + { + if (WebInspector.isBeingEdited(targetElement)) + return; + + // If the target element has a title use it as the editing value + // since the current text is likely truncated/rounded. + if (targetElement.title) + targetElement.textContent = targetElement.title; + + var context = {box, styleProperty}; + var boundKeyDown = this._handleKeyDown.bind(this, context, styleProperty); + context.keyDownHandler = boundKeyDown; + targetElement.addEventListener("keydown", boundKeyDown, false); + + this._isEditingMetrics = true; + + var config = new WebInspector.EditingConfig(this._editingCommitted.bind(this), this._editingCancelled.bind(this), context); + WebInspector.startEditing(targetElement, config); + + window.getSelection().setBaseAndExtent(targetElement, 0, targetElement, 1); + } + + _alteredFloatNumber(number, event) + { + var arrowKeyPressed = event.keyIdentifier === "Up" || event.keyIdentifier === "Down"; + + // Jump by 10 when shift is down or jump by 0.1 when Alt/Option is down. + // Also jump by 10 for page up and down, or by 100 if shift is held with a page key. + var changeAmount = 1; + if (event.shiftKey && !arrowKeyPressed) + changeAmount = 100; + else if (event.shiftKey || !arrowKeyPressed) + changeAmount = 10; + else if (event.altKey) + changeAmount = 0.1; + + if (event.keyIdentifier === "Down" || event.keyIdentifier === "PageDown") + changeAmount *= -1; + + // Make the new number and constrain it to a precision of 6, this matches numbers the engine returns. + // Use the Number constructor to forget the fixed precision, so 1.100000 will print as 1.1. + var result = Number((number + changeAmount).toFixed(6)); + if (!String(result).match(WebInspector.EditingSupport.NumberRegex)) + return null; + + return result; + } + + _handleKeyDown(context, styleProperty, event) + { + if (!/^(?:Page)?(?:Up|Down)$/.test(event.keyIdentifier)) + return; + + var element = event.currentTarget; + + var selection = window.getSelection(); + if (!selection.rangeCount) + return; + + var selectionRange = selection.getRangeAt(0); + if (!selectionRange.commonAncestorContainer.isSelfOrDescendant(element)) + return; + + var originalValue = element.textContent; + var wordRange = selectionRange.startContainer.rangeOfWord(selectionRange.startOffset, WebInspector.EditingSupport.StyleValueDelimiters, element); + var wordString = wordRange.toString(); + + var matches = WebInspector.EditingSupport.NumberRegex.exec(wordString); + var replacementString; + if (matches && matches.length) { + var prefix = matches[1]; + var suffix = matches[3]; + var number = this._alteredFloatNumber(parseFloat(matches[2]), event); + if (number === null) { + // Need to check for null explicitly. + return; + } + + if (styleProperty !== "margin" && number < 0) + number = 0; + + replacementString = prefix + number + suffix; + } + + if (!replacementString) + return; + + var replacementTextNode = document.createTextNode(replacementString); + + wordRange.deleteContents(); + wordRange.insertNode(replacementTextNode); + + var finalSelectionRange = document.createRange(); + finalSelectionRange.setStart(replacementTextNode, 0); + finalSelectionRange.setEnd(replacementTextNode, replacementString.length); + + selection.removeAllRanges(); + selection.addRange(finalSelectionRange); + + event.handled = true; + event.preventDefault(); + + this._ignoreNextRefresh = true; + + this._applyUserInput(element, replacementString, originalValue, context, false); + } + + _editingEnded(element, context) + { + element.removeEventListener("keydown", context.keyDownHandler, false); + this._isEditingMetrics = false; + } + + _editingCancelled(element, context) + { + this._editingEnded(element, context); + this._refresh(); + } + + _applyUserInput(element, userInput, previousContent, context, commitEditor) + { + if (commitEditor && userInput === previousContent) { + // Nothing changed, so cancel. + this._editingCancelled(element, context); + return; + } + + if (context.box !== "position" && (!userInput || userInput === figureDash)) + userInput = "0px"; + else if (context.box === "position" && (!userInput || userInput === figureDash)) + userInput = "auto"; + + userInput = userInput.toLowerCase(); + // Append a "px" unit if the user input was just a number. + if (/^-?(?:\d+(?:\.\d+)?|\.\d+)$/.test(userInput)) + userInput += "px"; + + var styleProperty = context.styleProperty; + var computedStyle = this._nodeStyles.computedStyle; + + if (computedStyle.propertyForName("box-sizing").value === "border-box" && (styleProperty === "width" || styleProperty === "height")) { + if (!userInput.match(/px$/)) { + console.error("For elements with box-sizing: border-box, only absolute content area dimensions can be applied"); + return; + } + + var borderBox = this._getBox(computedStyle, "border"); + var paddingBox = this._getBox(computedStyle, "padding"); + var userValuePx = Number(userInput.replace(/px$/, "")); + if (isNaN(userValuePx)) + return; + if (styleProperty === "width") + userValuePx += borderBox.left + borderBox.right + paddingBox.left + paddingBox.right; + else + userValuePx += borderBox.top + borderBox.bottom + paddingBox.top + paddingBox.bottom; + + userInput = userValuePx + "px"; + } + + function resolvedNode(object) + { + if (!object) + return; + + function toggleInlineStyleProperty(property, value) + { + this.style.setProperty(property, value, "important"); + } + + function didToggle() + { + this._nodeStyles.refresh(); + } + + object.callFunction(toggleInlineStyleProperty, [styleProperty, userInput], false, didToggle.bind(this)); + object.release(); + } + + WebInspector.RemoteObject.resolveNode(this._nodeStyles.node, "", resolvedNode.bind(this)); + } + + _editingCommitted(element, userInput, previousContent, context) + { + this._editingEnded(element, context); + this._applyUserInput(element, userInput, previousContent, context, true); + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Views/BreakpointActionView.css b/Source/WebInspectorUI/UserInterface/Views/BreakpointActionView.css new file mode 100644 index 000000000..cf55d69a3 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Views/BreakpointActionView.css @@ -0,0 +1,91 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +.breakpoint-action-block-header { + margin-bottom: 3px; +} + +.breakpoint-action-button-container { + float: right; +} + +.breakpoint-action-append-button, +.breakpoint-action-remove-button { + background-origin: border-box; + width: 13px; + height: 13px; + margin-left: 5px; + margin-top: 2px; + background-color: transparent; + border: none; + opacity: 0.6; +} + +.breakpoint-action-append-button { + background-image: url(../Images/Plus13.svg); +} + +.breakpoint-action-remove-button { + background-image: url(../Images/Minus.svg); +} + +.breakpoint-action-block-body { + margin: 1px 2px 6px 2px; + padding: 8px; + width: 100%; + border-radius: 4px; + border: 1px solid hsl(0, 0%, 74%); + background-color: hsla(0, 0%, 87%, 0.95); + box-shadow: inset 0 0 2px hsl(0, 0%, 78%); +} + +.breakpoint-action-block-body > .description { + color: var(--text-color-gray-medium); + text-align: right; + margin-top: 6px; + margin-right: 2px; +} + +.breakpoint-action-block-body > input { + width: 100%; +} + +.breakpoint-action-eval-editor { + margin: 2px 0; + padding: 2px 0 1px 0; + -webkit-appearance: textfield; + border: 1px solid hsl(0, 0%, 78%); + background: white; +} + +.breakpoint-action-eval-editor > .CodeMirror { + width: 336px; /* NOTE: Fixed value, manually tuned to .edit-breakpoint-popover-content.wide width */ + height: auto; +} + +.breakpoint-action-eval-editor > .CodeMirror-scroll { + width: 336px; /* NOTE: Fixed value, manually tuned to .edit-breakpoint-popover-content.wide width */ + overflow: hidden; +} diff --git a/Source/WebInspectorUI/UserInterface/Views/BreakpointActionView.js b/Source/WebInspectorUI/UserInterface/Views/BreakpointActionView.js new file mode 100644 index 000000000..2159a40a8 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Views/BreakpointActionView.js @@ -0,0 +1,215 @@ +/* + * Copyright (C) 2013, 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.BreakpointActionView = class BreakpointActionView extends WebInspector.Object +{ + constructor(action, delegate, omitFocus) + { + super(); + + console.assert(action); + console.assert(delegate); + console.assert(DebuggerAgent.BreakpointActionType); + + this._action = action; + this._delegate = delegate; + + this._element = document.createElement("div"); + this._element.className = "breakpoint-action-block"; + + var header = this._element.appendChild(document.createElement("div")); + header.className = "breakpoint-action-block-header"; + + var picker = header.appendChild(document.createElement("select")); + picker.addEventListener("change", this._pickerChanged.bind(this)); + + for (var key in WebInspector.BreakpointAction.Type) { + var type = WebInspector.BreakpointAction.Type[key]; + var option = document.createElement("option"); + option.textContent = WebInspector.BreakpointActionView.displayStringForType(type); + option.selected = this._action.type === type; + option.value = type; + picker.add(option); + } + + let buttonContainerElement = header.appendChild(document.createElement("div")); + buttonContainerElement.classList.add("breakpoint-action-button-container"); + + let appendActionButton = buttonContainerElement.appendChild(document.createElement("button")); + appendActionButton.className = "breakpoint-action-append-button"; + appendActionButton.addEventListener("click", this._appendActionButtonClicked.bind(this)); + appendActionButton.title = WebInspector.UIString("Add new breakpoint action after this action"); + + let removeActionButton = buttonContainerElement.appendChild(document.createElement("button")); + removeActionButton.className = "breakpoint-action-remove-button"; + removeActionButton.addEventListener("click", this._removeAction.bind(this)); + removeActionButton.title = WebInspector.UIString("Remove this breakpoint action"); + + this._bodyElement = this._element.appendChild(document.createElement("div")); + this._bodyElement.className = "breakpoint-action-block-body"; + + this._updateBody(omitFocus); + } + + // Static + + static displayStringForType(type) + { + switch (type) { + case WebInspector.BreakpointAction.Type.Log: + return WebInspector.UIString("Log Message"); + case WebInspector.BreakpointAction.Type.Evaluate: + return WebInspector.UIString("Evaluate JavaScript"); + case WebInspector.BreakpointAction.Type.Sound: + return WebInspector.UIString("Play Sound"); + case WebInspector.BreakpointAction.Type.Probe: + return WebInspector.UIString("Probe Expression"); + default: + console.assert(false); + return ""; + } + } + + // Public + + get action() + { + return this._action; + } + + get element() + { + return this._element; + } + + // Private + + _pickerChanged(event) + { + var newType = event.target.value; + this._action = this._action.breakpoint.recreateAction(newType, this._action); + this._updateBody(); + this._delegate.breakpointActionViewResized(this); + } + + _appendActionButtonClicked(event) + { + var newAction = this._action.breakpoint.createAction(this._action.type, this._action); + this._delegate.breakpointActionViewAppendActionView(this, newAction); + } + + _removeAction() + { + this._action.breakpoint.removeAction(this._action); + this._delegate.breakpointActionViewRemoveActionView(this); + } + + _updateBody(omitFocus) + { + this._bodyElement.removeChildren(); + + switch (this._action.type) { + case WebInspector.BreakpointAction.Type.Log: + this._bodyElement.hidden = false; + + var input = this._bodyElement.appendChild(document.createElement("input")); + input.placeholder = WebInspector.UIString("Message"); + input.addEventListener("change", this._logInputChanged.bind(this)); + input.value = this._action.data || ""; + input.spellcheck = false; + if (!omitFocus) + setTimeout(function() { input.focus(); }, 0); + + let descriptionElement = this._bodyElement.appendChild(document.createElement("div")); + descriptionElement.classList.add("description"); + descriptionElement.textContent = WebInspector.UIString("${expr} = expression"); + break; + + case WebInspector.BreakpointAction.Type.Evaluate: + case WebInspector.BreakpointAction.Type.Probe: + this._bodyElement.hidden = false; + + var editorElement = this._bodyElement.appendChild(document.createElement("div")); + editorElement.classList.add("breakpoint-action-eval-editor"); + editorElement.classList.add(WebInspector.SyntaxHighlightedStyleClassName); + + this._codeMirror = WebInspector.CodeMirrorEditor.create(editorElement, { + lineWrapping: true, + mode: "text/javascript", + indentWithTabs: true, + indentUnit: 4, + matchBrackets: true, + value: this._action.data || "", + }); + + this._codeMirror.on("viewportChange", this._codeMirrorViewportChanged.bind(this)); + this._codeMirror.on("blur", this._codeMirrorBlurred.bind(this)); + + this._codeMirrorViewport = {from: null, to: null}; + + var completionController = new WebInspector.CodeMirrorCompletionController(this._codeMirror); + completionController.addExtendedCompletionProvider("javascript", WebInspector.javaScriptRuntimeCompletionProvider); + + // CodeMirror needs a refresh after the popover displays, to layout, otherwise it doesn't appear. + setTimeout(() => { + this._codeMirror.refresh(); + if (!omitFocus) + this._codeMirror.focus(); + }, 0); + + break; + + case WebInspector.BreakpointAction.Type.Sound: + this._bodyElement.hidden = true; + break; + + default: + console.assert(false); + this._bodyElement.hidden = true; + break; + } + } + + _logInputChanged(event) + { + this._action.data = event.target.value; + } + + _codeMirrorBlurred(event) + { + // Throw away the expression if it's just whitespace. + this._action.data = (this._codeMirror.getValue() || "").trim(); + } + + _codeMirrorViewportChanged(event, from, to) + { + if (this._codeMirrorViewport.from === from && this._codeMirrorViewport.to === to) + return; + + this._codeMirrorViewport.from = from; + this._codeMirrorViewport.to = to; + this._delegate.breakpointActionViewResized(this); + } +}; diff --git a/Source/WebInspectorUI/UserInterface/Views/BreakpointPopoverController.css b/Source/WebInspectorUI/UserInterface/Views/BreakpointPopoverController.css new file mode 100644 index 000000000..25df67a54 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Views/BreakpointPopoverController.css @@ -0,0 +1,85 @@ +/* + * Copyright (C) 2013-2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +.popover .edit-breakpoint-popover-content { + width: 420px; + padding: 5px 15px; +} + +.popover .edit-breakpoint-popover-content.wide { + width: 460px; +} + +.popover .edit-breakpoint-popover-content > label.toggle { + color: black; + font-weight: bold; + text-overflow: ellipsis; + white-space: nowrap; +} + +.popover .edit-breakpoint-popover-content > table { + width: 100%; +} + +.popover .edit-breakpoint-popover-content > table > tr > th { + color: hsl(0, 0%, 34%); + font-weight: bold; + text-align: right; + width: 1px; /* Shrink to fit. */ + vertical-align: top; + line-height: 23px; + white-space: nowrap; +} + +.popover .edit-breakpoint-popover-content > table > tr > td { + padding-left: 5px; +} + +.edit-breakpoint-popover-condition { + width: 100%; + padding: 4px 0 2px 0; + -webkit-appearance: textfield; + border: 1px solid hsl(0, 0%, 78%); + background: white; +} + +.edit-breakpoint-popover-condition > .CodeMirror { + width: 320px; /* NOTE: Fixed value, manually tuned to .edit-breakpoint-popover-content width. */ + height: auto; +} + +.wide .edit-breakpoint-popover-condition > .CodeMirror { + width: 360px; /* NOTE: Fixed value, manually tuned to .edit-breakpoint-popover-content width. */ +} + +#edit-breakpoint-popover-ignore { + width: 40px; + margin-right: 4px; +} + +#edit-breakpoint-popoover-auto-continue { + margin-left: 0; + margin-right: 4px; +} diff --git a/Source/WebInspectorUI/UserInterface/Views/BreakpointTreeElement.css b/Source/WebInspectorUI/UserInterface/Views/BreakpointTreeElement.css new file mode 100644 index 000000000..fe26a9820 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Views/BreakpointTreeElement.css @@ -0,0 +1,86 @@ +/* + * Copyright (C) 2013, 2014 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +.item.breakpoint .status > .status-image { + width: 21px; + height: 12px; + content: url(../Images/BreakpointInactiveButton.svg); + margin-top: 3px; +} + +.item.breakpoint .status > .status-image.resolved { + content: url(../Images/BreakpointButton.svg); +} + +.item.breakpoint .status > .status-image.auto-continue { + opacity: 0.6; +} + +.item.breakpoint .status > .status-image.disabled { + opacity: 0.35; +} + +.item.breakpoint .subtitle.formatted-location { + font-style: italic; +} + +.breakpoint-exception-icon .icon { + content: url(../Images/Exception.svg); +} + +.breakpoint-assertion-icon .icon { + content: url(../Images/Assertion.svg); +} + +.breakpoint-paused-icon .icon { + content: url(../Images/PausedBreakpoint.svg); +} + +/* When animating a layer on top of a tree element's icon, move the main +icon to the icon element's background so animations are layered on top. */ +.breakpoint-generic-line-icon .icon { + background-image: url(../Images/ResultLine.svg); + content: ''; +} + +.breakpoint-generic-line-icon .icon > span { + position: absolute; + top: 0; + right: 0; + bottom: 0; + left: 0; + + border-radius: 50%; + transform: scale(0); + transition: none; + background-color: hsl(216, 30%, 42%); +} + +.data-updated.breakpoint-generic-line-icon .icon > span { + border-radius: 0; + transform: scale(0.85); + transition: all .4s ease-out; + background-color: hsla(216, 30%, 42%, 0.1); +} diff --git a/Source/WebInspectorUI/UserInterface/Views/BreakpointTreeElement.js b/Source/WebInspectorUI/UserInterface/Views/BreakpointTreeElement.js new file mode 100644 index 000000000..b73ddd3ff --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Views/BreakpointTreeElement.js @@ -0,0 +1,274 @@ +/* + * Copyright (C) 2013-2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.BreakpointTreeElement = class BreakpointTreeElement extends WebInspector.DebuggerTreeElement +{ + constructor(breakpoint, className, title) + { + console.assert(breakpoint instanceof WebInspector.Breakpoint); + + if (!className) + className = WebInspector.BreakpointTreeElement.GenericLineIconStyleClassName; + + super(["breakpoint", className], title, null, breakpoint, false); + + this._breakpoint = breakpoint; + this._probeSet = null; + + this._listenerSet = new WebInspector.EventListenerSet(this, "BreakpointTreeElement listeners"); + if (!title) + this._listenerSet.register(breakpoint, WebInspector.Breakpoint.Event.LocationDidChange, this._breakpointLocationDidChange); + this._listenerSet.register(breakpoint, WebInspector.Breakpoint.Event.DisabledStateDidChange, this._updateStatus); + this._listenerSet.register(breakpoint, WebInspector.Breakpoint.Event.AutoContinueDidChange, this._updateStatus); + this._listenerSet.register(breakpoint, WebInspector.Breakpoint.Event.ResolvedStateDidChange, this._updateStatus); + this._listenerSet.register(WebInspector.debuggerManager, WebInspector.DebuggerManager.Event.BreakpointsEnabledDidChange, this._updateStatus); + + this._listenerSet.register(WebInspector.probeManager, WebInspector.ProbeManager.Event.ProbeSetAdded, this._probeSetAdded); + this._listenerSet.register(WebInspector.probeManager, WebInspector.ProbeManager.Event.ProbeSetRemoved, this._probeSetRemoved); + + this._statusImageElement = document.createElement("img"); + this._statusImageElement.className = WebInspector.BreakpointTreeElement.StatusImageElementStyleClassName; + this._listenerSet.register(this._statusImageElement, "mousedown", this._statusImageElementMouseDown); + this._listenerSet.register(this._statusImageElement, "click", this._statusImageElementClicked); + + if (!title) + this._updateTitles(); + this._updateStatus(); + + this.status = this._statusImageElement; + + this._iconAnimationLayerElement = document.createElement("span"); + this.iconElement.appendChild(this._iconAnimationLayerElement); + } + + // Public + + get breakpoint() + { + return this._breakpoint; + } + + get filterableData() + { + return {text: [this.breakpoint.contentIdentifier]}; + } + + ondelete() + { + if (!WebInspector.debuggerManager.isBreakpointRemovable(this._breakpoint)) + return false; + + // We set this flag so that TreeOutlines that will remove this + // BreakpointTreeElement will know whether it was deleted from + // within the TreeOutline or from outside it (e.g. TextEditor). + this.__deletedViaDeleteKeyboardShortcut = true; + + WebInspector.debuggerManager.removeBreakpoint(this._breakpoint); + return true; + } + + onenter() + { + this._breakpoint.cycleToNextMode(); + return true; + } + + onspace() + { + this._breakpoint.cycleToNextMode(); + return true; + } + + onattach() + { + super.onattach(); + + this._listenerSet.install(); + + for (var probeSet of WebInspector.probeManager.probeSets) + if (probeSet.breakpoint === this._breakpoint) + this._addProbeSet(probeSet); + } + + ondetach() + { + this._listenerSet.uninstall(); + + if (this._probeSet) + this._removeProbeSet(this._probeSet); + } + + populateContextMenu(contextMenu, event) + { + WebInspector.breakpointPopoverController.appendContextMenuItems(contextMenu, this._breakpoint, this._statusImageElement); + + super.populateContextMenu(contextMenu, event); + } + + removeStatusImage() + { + this._statusImageElement.remove(); + this._statusImageElement = null; + } + + // Private + + _updateTitles() + { + var sourceCodeLocation = this._breakpoint.sourceCodeLocation; + + var displayLineNumber = sourceCodeLocation.displayLineNumber; + var displayColumnNumber = sourceCodeLocation.displayColumnNumber; + if (displayColumnNumber > 0) + this.mainTitle = WebInspector.UIString("Line %d:%d").format(displayLineNumber + 1, displayColumnNumber + 1); // The user visible line and column numbers are 1-based. + else + this.mainTitle = WebInspector.UIString("Line %d").format(displayLineNumber + 1); // The user visible line number is 1-based. + + if (sourceCodeLocation.hasMappedLocation()) { + this.subtitle = sourceCodeLocation.formattedLocationString(); + + if (sourceCodeLocation.hasFormattedLocation()) + this.subtitleElement.classList.add(WebInspector.BreakpointTreeElement.FormattedLocationStyleClassName); + else + this.subtitleElement.classList.remove(WebInspector.BreakpointTreeElement.FormattedLocationStyleClassName); + + this.tooltip = this.mainTitle + " \u2014 " + WebInspector.UIString("originally %s").format(sourceCodeLocation.originalLocationString()); + } + } + + _updateStatus() + { + if (!this._statusImageElement) + return; + + if (this._breakpoint.disabled) + this._statusImageElement.classList.add(WebInspector.BreakpointTreeElement.StatusImageDisabledStyleClassName); + else + this._statusImageElement.classList.remove(WebInspector.BreakpointTreeElement.StatusImageDisabledStyleClassName); + + if (this._breakpoint.autoContinue) + this._statusImageElement.classList.add(WebInspector.BreakpointTreeElement.StatusImageAutoContinueStyleClassName); + else + this._statusImageElement.classList.remove(WebInspector.BreakpointTreeElement.StatusImageAutoContinueStyleClassName); + + if (this._breakpoint.resolved && WebInspector.debuggerManager.breakpointsEnabled) + this._statusImageElement.classList.add(WebInspector.BreakpointTreeElement.StatusImageResolvedStyleClassName); + else + this._statusImageElement.classList.remove(WebInspector.BreakpointTreeElement.StatusImageResolvedStyleClassName); + } + + _addProbeSet(probeSet) + { + console.assert(probeSet instanceof WebInspector.ProbeSet); + console.assert(probeSet.breakpoint === this._breakpoint); + console.assert(probeSet !== this._probeSet); + + this._probeSet = probeSet; + probeSet.addEventListener(WebInspector.ProbeSet.Event.SamplesCleared, this._samplesCleared, this); + probeSet.dataTable.addEventListener(WebInspector.ProbeSetDataTable.Event.FrameInserted, this._dataUpdated, this); + } + + _removeProbeSet(probeSet) + { + console.assert(probeSet instanceof WebInspector.ProbeSet); + console.assert(probeSet === this._probeSet); + + probeSet.removeEventListener(WebInspector.ProbeSet.Event.SamplesCleared, this._samplesCleared, this); + probeSet.dataTable.removeEventListener(WebInspector.ProbeSetDataTable.Event.FrameInserted, this._dataUpdated, this); + this._probeSet = null; + } + + _probeSetAdded(event) + { + var probeSet = event.data.probeSet; + if (probeSet.breakpoint === this._breakpoint) + this._addProbeSet(probeSet); + } + + _probeSetRemoved(event) + { + var probeSet = event.data.probeSet; + if (probeSet.breakpoint === this._breakpoint) + this._removeProbeSet(probeSet); + } + + _samplesCleared(event) + { + console.assert(this._probeSet); + + var oldTable = event.data.oldTable; + oldTable.removeEventListener(WebInspector.ProbeSetDataTable.Event.FrameInserted, this._dataUpdated, this); + this._probeSet.dataTable.addEventListener(WebInspector.ProbeSetDataTable.Event.FrameInserted, this._dataUpdated, this); + } + + _dataUpdated() + { + if (this.element.classList.contains(WebInspector.BreakpointTreeElement.ProbeDataUpdatedStyleClassName)) { + clearTimeout(this._removeIconAnimationTimeoutIdentifier); + this.element.classList.remove(WebInspector.BreakpointTreeElement.ProbeDataUpdatedStyleClassName); + // We want to restart the animation, which can only be done by removing the class, + // performing layout, and re-adding the class. Try adding class back on next run loop. + window.requestAnimationFrame(this._dataUpdated.bind(this)); + return; + } + + this.element.classList.add(WebInspector.BreakpointTreeElement.ProbeDataUpdatedStyleClassName); + this._removeIconAnimationTimeoutIdentifier = setTimeout(() => { + this.element.classList.remove(WebInspector.BreakpointTreeElement.ProbeDataUpdatedStyleClassName); + }, WebInspector.BreakpointTreeElement.ProbeDataUpdatedAnimationDuration); + } + + _breakpointLocationDidChange(event) + { + console.assert(event.target === this._breakpoint); + + // The Breakpoint has a new display SourceCode. The sidebar will remove us, and ondetach() will clear listeners. + if (event.data.oldDisplaySourceCode === this._breakpoint.displaySourceCode) + return; + + this._updateTitles(); + } + + _statusImageElementMouseDown(event) + { + // To prevent the tree element from selecting. + event.stopPropagation(); + } + + _statusImageElementClicked(event) + { + this._breakpoint.cycleToNextMode(); + } +}; + +WebInspector.BreakpointTreeElement.GenericLineIconStyleClassName = "breakpoint-generic-line-icon"; +WebInspector.BreakpointTreeElement.StatusImageElementStyleClassName = "status-image"; +WebInspector.BreakpointTreeElement.StatusImageResolvedStyleClassName = "resolved"; +WebInspector.BreakpointTreeElement.StatusImageAutoContinueStyleClassName = "auto-continue"; +WebInspector.BreakpointTreeElement.StatusImageDisabledStyleClassName = "disabled"; +WebInspector.BreakpointTreeElement.FormattedLocationStyleClassName = "formatted-location"; +WebInspector.BreakpointTreeElement.ProbeDataUpdatedStyleClassName = "data-updated"; + +WebInspector.BreakpointTreeElement.ProbeDataUpdatedAnimationDuration = 400; // milliseconds diff --git a/Source/WebInspectorUI/UserInterface/Views/ButtonNavigationItem.css b/Source/WebInspectorUI/UserInterface/Views/ButtonNavigationItem.css new file mode 100644 index 000000000..bd94d40b3 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Views/ButtonNavigationItem.css @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +.navigation-bar .item.button { + width: 26px; + justify-content: center; +} + +.navigation-bar .item.button.text-only { + width: auto; + padding: 1px 8px 3px; + margin: 0 2px; + + line-height: 11px; + color: hsl(0, 0%, 18%); + border: 1px solid transparent; + border-radius: 3px; + text-align: center; +} + +.navigation-bar .item.button > .glyph { + color: var(--glyph-color); +} + +.navigation-bar .item.button:not(.disabled):active > .glyph { + color: var(--glyph-color-pressed); +} + +.navigation-bar .item.button:not(.disabled):matches(:focus, .activate.activated, .radio.selected) > .glyph { + color: var(--glyph-color-active); +} + +.navigation-bar .item.button:not(.disabled):active:matches(:focus, .activate.activated, .radio.selected) > .glyph { + color: var(--glyph-color-active-pressed); +} + +.navigation-bar .item.button.disabled > .glyph { + color: var(--glyph-color-disabled); +} diff --git a/Source/WebInspectorUI/UserInterface/Views/ButtonNavigationItem.js b/Source/WebInspectorUI/UserInterface/Views/ButtonNavigationItem.js new file mode 100644 index 000000000..8848f9d52 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Views/ButtonNavigationItem.js @@ -0,0 +1,140 @@ +/* + * Copyright (C) 2013, 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.ButtonNavigationItem = class ButtonNavigationItem extends WebInspector.NavigationItem +{ + constructor(identifier, toolTipOrLabel, image, imageWidth, imageHeight, role, label) + { + super(identifier); + + console.assert(identifier); + console.assert(toolTipOrLabel); + + this.toolTip = toolTipOrLabel; + + this._element.addEventListener("click", this._mouseClicked.bind(this)); + + this._element.setAttribute("role", role || "button"); + + if (label) + this._element.setAttribute("aria-label", label); + + this._imageWidth = imageWidth || 16; + this._imageHeight = imageHeight || 16; + + if (image) + this.image = image; + else + this.label = toolTipOrLabel; + } + + // Public + + get toolTip() + { + return this._element.title; + } + + set toolTip(newToolTip) + { + console.assert(newToolTip); + if (!newToolTip) + return; + + this._element.title = newToolTip; + } + + get label() + { + return this._element.textContent; + } + + set label(newLabel) + { + this._element.classList.add(WebInspector.ButtonNavigationItem.TextOnlyClassName); + this._element.textContent = newLabel || ""; + if (this.parentNavigationBar) + this.parentNavigationBar.needsLayout(); + } + + get image() + { + return this._image; + } + + set image(newImage) + { + if (!newImage) { + this._element.removeChildren(); + return; + } + + this._element.removeChildren(); + this._element.classList.remove(WebInspector.ButtonNavigationItem.TextOnlyClassName); + + this._image = newImage; + + this._glyphElement = useSVGSymbol(this._image, "glyph"); + this._glyphElement.style.width = this._imageWidth + "px"; + this._glyphElement.style.height = this._imageHeight + "px"; + this._element.appendChild(this._glyphElement); + } + + get enabled() + { + return !this._element.classList.contains(WebInspector.ButtonNavigationItem.DisabledStyleClassName); + } + + set enabled(flag) + { + if (flag) + this._element.classList.remove(WebInspector.ButtonNavigationItem.DisabledStyleClassName); + else + this._element.classList.add(WebInspector.ButtonNavigationItem.DisabledStyleClassName); + } + + // Protected + + get additionalClassNames() + { + return ["button"]; + } + + // Private + + _mouseClicked(event) + { + if (!this.enabled) + return; + this.dispatchEventToListeners(WebInspector.ButtonNavigationItem.Event.Clicked); + } +}; + +WebInspector.ButtonNavigationItem.DisabledStyleClassName = "disabled"; +WebInspector.ButtonNavigationItem.TextOnlyClassName = "text-only"; + +WebInspector.ButtonNavigationItem.Event = { + Clicked: "button-navigation-item-clicked" +}; diff --git a/Source/WebInspectorUI/UserInterface/Views/ButtonToolbarItem.css b/Source/WebInspectorUI/UserInterface/Views/ButtonToolbarItem.css new file mode 100644 index 000000000..88835ef16 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Views/ButtonToolbarItem.css @@ -0,0 +1,97 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +.toolbar .item.button { + align-items: center; + justify-content: center; + + margin: 4px; + padding: 0 10px; +} + +.toolbar.icon-and-label-vertical .item.button { + flex-direction: column; +} + +.toolbar.icon-and-label-horizontal .item.button { + flex-direction: row; +} + +.toolbar .item.button > .glyph { + width: 32px; + height: 32px; + + color: hsl(0, 0%, 45%); +} + +.toolbar .item.button:not(.disabled):active > .glyph { + color: hsl(0, 0%, 30%); +} + +.toolbar .item.button:not(.disabled):matches(:focus, .activate.activated) > .glyph { + color: var(--selected-background-color); +} + +.toolbar .item.button:not(.disabled):active:matches(:focus, .activate.activated) > .glyph { + color: var(--selected-background-color-active); +} + +.toolbar.small-size .item.button > .glyph { + width: 16px; + height: 16px; +} + +.toolbar.label-only .item.button > .glyph { + display: none; +} + +.toolbar .item.button > .label { + text-align: center; + color: hsl(0, 0%, 31%); +} + +.toolbar.label-only .item.activate.button.activated > .label { + color: hsl(206, 69%, 45%); +} + +.toolbar.icon-and-label-horizontal .item.button > .label { + margin-left: 4px; +} + +.toolbar.icon-only .item.button > .label { + display: none; +} + +body.window-inactive .toolbar .item.button { + opacity: 0.65; +} + +.toolbar .item.button.disabled { + opacity: 0.55 !important; +} + +body.window-inactive .toolbar .item.button.disabled { + opacity: 0.35 !important; +} diff --git a/Source/WebInspectorUI/UserInterface/Views/ButtonToolbarItem.js b/Source/WebInspectorUI/UserInterface/Views/ButtonToolbarItem.js new file mode 100644 index 000000000..b2c7a2b7c --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Views/ButtonToolbarItem.js @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2013, 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.ButtonToolbarItem = class ButtonToolbarItem extends WebInspector.ButtonNavigationItem +{ + constructor(identifier, toolTip, label, image, role) + { + super(identifier, toolTip, image, 16, 16, role); + + if (typeof label === "string") { + this._labelElement = document.createElement("div"); + this._labelElement.className = WebInspector.ButtonToolbarItem.LabelStyleClassName; + this._element.appendChild(this._labelElement); + + this.label = label; + } + } + + // Public + + get label() + { + return this._labelElement.textContent; + } + + set label(newLabel) + { + console.assert(newLabel); + if (!newLabel || !this._labelElement) + return; + + this._labelElement.textContent = newLabel; + } +}; + +WebInspector.ButtonToolbarItem.LabelStyleClassName = "label"; diff --git a/Source/WebInspectorUI/UserInterface/Views/CSSStyleDeclarationSection.css b/Source/WebInspectorUI/UserInterface/Views/CSSStyleDeclarationSection.css new file mode 100644 index 000000000..4060588f4 --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Views/CSSStyleDeclarationSection.css @@ -0,0 +1,168 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +.style-declaration-section { + display: flex; + flex-direction: column; + + padding: 3px; +} + +.style-declaration-section.locked { + background-color: hsl(0, 0%, 97%); +} + +.style-declaration-section:not(.locked) { + background-color: white; + border-top-color: hsla(0, 0%, 0%, 0.2); +} + +.style-declaration-section.last-in-group { + margin-bottom: 10px; + + border-bottom: 1px solid hsla(0, 0%, 0%, 0.3); +} + +.style-declaration-section + .style-declaration-section { + border-top: 1px solid hsla(0, 0%, 0%, 0.15); +} + +.style-declaration-section:last-child { + margin-bottom: 0 !important; +} + +.style-declaration-section > .header { + position: relative; + padding: var(--style-declaration-section-header-padding); + font-size: 11px; + line-height: 12px; +} + +.style-declaration-section.locked > .header > .locked-icon { + float: right; + width: 8px; + height: 10px; + margin-left: 5px; + content: url(../Images/Locked.svg); +} + +.style-declaration-section > .header > .icon { + position: absolute; + + top: 2px; + left: 4px; + + width: 16px; + height: 16px; +} + +.style-declaration-section > .header > .icon.toggle-able:hover { + filter: brightness(0.9); +} + +.style-declaration-section > .header > .icon.toggle-able:active { + filter: brightness(0.8); +} + +.style-declaration-section:not(.invalid-selector).rule-disabled > .header > .icon { + opacity: 0.5; +} + +.style-declaration-section > .header > textarea { + display: block; + position: absolute; + top: 0; + right: 0; + bottom: 0; + left: 0; + margin: var(--style-declaration-section-header-padding); + padding: 0; + font-family: Menlo, monospace; + color: black; + background: transparent; + border: none; + outline: none; + opacity: 0; + resize: none; + -webkit-appearance: none; +} + +.style-declaration-section > .header > textarea:focus { + opacity: 1; +} + +.style-declaration-section > .header > textarea:focus + .selector { + opacity: 0; +} + +.style-declaration-section > .header > .selector { + font-family: Menlo, monospace; + color: hsl(0, 0%, 50%); + word-wrap: break-word; +} + +.style-declaration-section > .header > .selector > .matched { + color: black; +} + +.style-declaration-section > .header > .origin { + position: relative; + z-index: 1; + + line-height: 10px; + + color: hsl(0, 0%, 50%); + + word-wrap: break-word; + white-space: nowrap; +} + +.style-declaration-section > .header > .origin a { + white-space: normal; +} + +.style-declaration-section > .header > .origin > .go-to-link { + color: inherit !important; +} + +.style-declaration-section.invalid-selector > .header > .icon { + top: 4px; + left: 6px; + width: 12px; + height: 12px; + content: url(../Images/Error.svg); +} + +.style-declaration-section.invalid-selector > .header > .selector, +.style-declaration-section.invalid-selector > .header > .selector > * { + color: red; +} + +@media (-webkit-min-device-pixel-ratio: 2) { + .style-declaration-section, + .sidebar > .panel.details.css-style > .content > .pseudo-classes { + border-width: 0.5px !important; + } +} diff --git a/Source/WebInspectorUI/UserInterface/Views/CSSStyleDeclarationSection.js b/Source/WebInspectorUI/UserInterface/Views/CSSStyleDeclarationSection.js new file mode 100644 index 000000000..fb26f033c --- /dev/null +++ b/Source/WebInspectorUI/UserInterface/Views/CSSStyleDeclarationSection.js @@ -0,0 +1,740 @@ +/* + * Copyright (C) 2013, 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +WebInspector.CSSStyleDeclarationSection = class CSSStyleDeclarationSection extends WebInspector.Object +{ + constructor(delegate, style) + { + console.assert(style instanceof WebInspector.CSSStyleDeclaration, style); + + super(); + + this._delegate = delegate || null; + + this._style = style || null; + this._selectorElements = []; + this._ruleDisabled = false; + this._hasInvalidSelector = false; + + this._element = document.createElement("div"); + this._element.classList.add("style-declaration-section"); + + new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, "S", this._save.bind(this), this._element); + new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl | WebInspector.KeyboardShortcut.Modifier.Shift, "S", this._save.bind(this), this._element); + + this._headerElement = document.createElement("div"); + this._headerElement.classList.add("header"); + + if (!style.editable) { + let lockedIconElement = this._headerElement.createChild("img", "locked-icon"); + + let styleLabel; + if (style.ownerRule && style.ownerRule.type === WebInspector.CSSStyleSheet.Type.UserAgent) + styleLabel = WebInspector.UIString("User Agent Stylesheet"); + else + styleLabel = WebInspector.UIString("Style rule"); + + lockedIconElement.title = WebInspector.UIString("%s cannot be modified").format(styleLabel); + } + + this._iconElement = this._headerElement.createChild("img", "icon"); + + if (this.selectorEditable) { + this._selectorInput = this._headerElement.createChild("textarea"); + this._selectorInput.spellcheck = false; + this._selectorInput.tabIndex = -1; + this._selectorInput.addEventListener("mouseover", this._handleMouseOver.bind(this)); + this._selectorInput.addEventListener("mousemove", this._handleMouseMove.bind(this)); + this._selectorInput.addEventListener("mouseout", this._handleMouseOut.bind(this)); + this._selectorInput.addEventListener("keydown", this._handleKeyDown.bind(this)); + this._selectorInput.addEventListener("keypress", this._handleKeyPress.bind(this)); + this._selectorInput.addEventListener("input", this._handleInput.bind(this)); + this._selectorInput.addEventListener("paste", this._handleSelectorPaste.bind(this)); + this._selectorInput.addEventListener("blur", this._handleBlur.bind(this)); + } + + this._selectorElement = this._headerElement.createChild("span", "selector"); + if (!this.selectorEditable) { + this._selectorElement.addEventListener("mouseover", this._handleMouseOver.bind(this)); + this._selectorElement.addEventListener("mouseout", this._handleMouseOut.bind(this)); + } + + this._originElement = this._headerElement.createChild("span", "origin"); + + this._propertiesElement = document.createElement("div"); + this._propertiesElement.classList.add("properties"); + + this._editorActive = false; + this._propertiesTextEditor = new WebInspector.CSSStyleDeclarationTextEditor(this, style); + this._propertiesTextEditor.addEventListener(WebInspector.CSSStyleDeclarationTextEditor.Event.ContentChanged, this._editorContentChanged.bind(this)); + this._propertiesTextEditor.addEventListener(WebInspector.CSSStyleDeclarationTextEditor.Event.Blurred, this._editorBlurred.bind(this)); + this._propertiesElement.appendChild(this._propertiesTextEditor.element); + + this._element.appendChild(this._headerElement); + this._element.appendChild(this._propertiesElement); + + let iconClassName = null; + switch (style.type) { + case WebInspector.CSSStyleDeclaration.Type.Rule: + console.assert(style.ownerRule); + + if (style.inherited) + iconClassName = WebInspector.CSSStyleDeclarationSection.InheritedStyleRuleIconStyleClassName; + else if (style.ownerRule.type === WebInspector.CSSStyleSheet.Type.Author) + iconClassName = WebInspector.CSSStyleDeclarationSection.AuthorStyleRuleIconStyleClassName; + else if (style.ownerRule.type === WebInspector.CSSStyleSheet.Type.User) + iconClassName = WebInspector.CSSStyleDeclarationSection.UserStyleRuleIconStyleClassName; + else if (style.ownerRule.type === WebInspector.CSSStyleSheet.Type.UserAgent) + iconClassName = WebInspector.CSSStyleDeclarationSection.UserAgentStyleRuleIconStyleClassName; + else if (style.ownerRule.type === WebInspector.CSSStyleSheet.Type.Inspector) + iconClassName = WebInspector.CSSStyleDeclarationSection.InspectorStyleRuleIconStyleClassName; + break; + + case WebInspector.CSSStyleDeclaration.Type.Inline: + case WebInspector.CSSStyleDeclaration.Type.Attribute: + if (style.inherited) + iconClassName = WebInspector.CSSStyleDeclarationSection.InheritedElementStyleRuleIconStyleClassName; + else + iconClassName = WebInspector.DOMTreeElementPathComponent.DOMElementIconStyleClassName; + break; + } + + if (style.editable) { + this._iconElement.classList.add("toggle-able"); + this._iconElement.title = WebInspector.UIString("Comment All Properties"); + this._iconElement.addEventListener("click", this._handleIconElementClicked.bind(this)); + } + + console.assert(iconClassName); + this._element.classList.add(iconClassName); + + if (!style.editable) + this._element.classList.add(WebInspector.CSSStyleDeclarationSection.LockedStyleClassName); + else if (style.ownerRule) + this._style.ownerRule.addEventListener(WebInspector.CSSRule.Event.SelectorChanged, this._updateSelectorIcon.bind(this)); + else + this._element.classList.add(WebInspector.CSSStyleDeclarationSection.SelectorLockedStyleClassName); + + this.refresh(); + + this._headerElement.addEventListener("contextmenu", this._handleContextMenuEvent.bind(this)); + } + + // Public + + get element() + { + return this._element; + } + + get style() + { + return this._style; + } + + get lastInGroup() + { + return this._element.classList.contains(WebInspector.CSSStyleDeclarationSection.LastInGroupStyleClassName); + } + + set lastInGroup(last) + { + if (last) + this._element.classList.add(WebInspector.CSSStyleDeclarationSection.LastInGroupStyleClassName); + else + this._element.classList.remove(WebInspector.CSSStyleDeclarationSection.LastInGroupStyleClassName); + } + + get focused() + { + return this._propertiesTextEditor.focused; + } + + focus() + { + this._propertiesTextEditor.focus(); + } + + refresh() + { + this._selectorElement.removeChildren(); + this._originElement.removeChildren(); + this._selectorElements = []; + + this._originElement.append(` ${emDash} `); + + function appendSelector(selector, matched) + { + console.assert(selector instanceof WebInspector.CSSSelector); + + let selectorElement = document.createElement("span"); + selectorElement.textContent = selector.text; + + if (matched) + selectorElement.classList.add(WebInspector.CSSStyleDeclarationSection.MatchedSelectorElementStyleClassName); + + let specificity = selector.specificity; + if (specificity) { + let tooltip = WebInspector.UIString("Specificity: (%d, %d, %d)").format(specificity[0], specificity[1], specificity[2]); + if (selector.dynamic) { + tooltip += "\n"; + if (this._style.inherited) + tooltip += WebInspector.UIString("Dynamically calculated for the parent element"); + else + tooltip += WebInspector.UIString("Dynamically calculated for the selected element"); + } + selectorElement.title = tooltip; + } else if (selector.dynamic) { + let tooltip = WebInspector.UIString("Specificity: No value for selected element"); + tooltip += "\n"; + tooltip += WebInspector.UIString("Dynamically calculated for the selected element and did not match"); + selectorElement.title = tooltip; + } + + this._selectorElement.appendChild(selectorElement); + this._selectorElements.push(selectorElement); + } + + function appendSelectorTextKnownToMatch(selectorText) + { + let selectorElement = document.createElement("span"); + selectorElement.textContent = selectorText; + selectorElement.classList.add(WebInspector.CSSStyleDeclarationSection.MatchedSelectorElementStyleClassName); + this._selectorElement.appendChild(selectorElement); + } + + switch (this._style.type) { + case WebInspector.CSSStyleDeclaration.Type.Rule: + console.assert(this._style.ownerRule); + + let selectors = this._style.ownerRule.selectors; + let matchedSelectorIndices = this._style.ownerRule.matchedSelectorIndices; + let alwaysMatch = !matchedSelectorIndices.length; + if (selectors.length) { + let hasMatchingPseudoElementSelector = false; + for (let i = 0; i < selectors.length; ++i) { + appendSelector.call(this, selectors[i], alwaysMatch || matchedSelectorIndices.includes(i)); + if (i < selectors.length - 1) + this._selectorElement.append(", "); + + if (matchedSelectorIndices.includes(i) && selectors[i].isPseudoElementSelector()) + hasMatchingPseudoElementSelector = true; + } + this._element.classList.toggle(WebInspector.CSSStyleDeclarationSection.PseudoElementSelectorStyleClassName, hasMatchingPseudoElementSelector); + } else + appendSelectorTextKnownToMatch.call(this, this._style.ownerRule.selectorText); + + if (this._style.ownerRule.sourceCodeLocation) { + let sourceCodeLink = WebInspector.createSourceCodeLocationLink(this._style.ownerRule.sourceCodeLocation, true); + this._originElement.appendChild(sourceCodeLink); + } else { + let originString; + switch (this._style.ownerRule.type) { + case WebInspector.CSSStyleSheet.Type.Author: + originString = WebInspector.UIString("Author Stylesheet"); + break; + + case WebInspector.CSSStyleSheet.Type.User: + originString = WebInspector.UIString("User Stylesheet"); + break; + + case WebInspector.CSSStyleSheet.Type.UserAgent: + originString = WebInspector.UIString("User Agent Stylesheet"); + break; + + case WebInspector.CSSStyleSheet.Type.Inspector: + originString = WebInspector.UIString("Web Inspector"); + break; + } + + console.assert(originString); + if (originString) + this._originElement.append(originString); + } + + break; + + case WebInspector.CSSStyleDeclaration.Type.Inline: + appendSelectorTextKnownToMatch.call(this, this._style.node.displayName); + this._originElement.append(WebInspector.UIString("Style Attribute")); + break; + + case WebInspector.CSSStyleDeclaration.Type.Attribute: + appendSelectorTextKnownToMatch.call(this, this._style.node.displayName); + this._originElement.append(WebInspector.UIString("HTML Attributes")); + break; + } + + this._updateSelectorIcon(); + if (this._selectorInput) + this._selectorInput.value = this._selectorElement.textContent; + } + + highlightProperty(property) + { + if (this._propertiesTextEditor.highlightProperty(property)) { + this._element.scrollIntoView(); + return true; + } + + return false; + } + + findMatchingPropertiesAndSelectors(needle) + { + this._element.classList.remove(WebInspector.CSSStyleDetailsSidebarPanel.NoFilterMatchInSectionClassName, WebInspector.CSSStyleDetailsSidebarPanel.FilterMatchingSectionHasLabelClassName); + + var hasMatchingSelector = false; + + for (var selectorElement of this._selectorElements) { + selectorElement.classList.remove(WebInspector.CSSStyleDetailsSidebarPanel.FilterMatchSectionClassName); + + if (needle && selectorElement.textContent.includes(needle)) { + selectorElement.classList.add(WebInspector.CSSStyleDetailsSidebarPanel.FilterMatchSectionClassName); + hasMatchingSelector = true; + } + } + + if (!needle) { + this._propertiesTextEditor.resetFilteredProperties(); + return false; + } + + var hasMatchingProperty = this._propertiesTextEditor.findMatchingProperties(needle); + + if (!hasMatchingProperty && !hasMatchingSelector) { + this._element.classList.add(WebInspector.CSSStyleDetailsSidebarPanel.NoFilterMatchInSectionClassName); + return false; + } + + return true; + } + + updateLayout() + { + this._propertiesTextEditor.updateLayout(); + } + + clearSelection() + { + this._propertiesTextEditor.clearSelection(); + } + + cssStyleDeclarationTextEditorFocused() + { + if (typeof this._delegate.cssStyleDeclarationSectionEditorFocused === "function") + this._delegate.cssStyleDeclarationSectionEditorFocused(this); + } + + cssStyleDeclarationTextEditorSwitchRule(reverse) + { + if (!this._delegate) + return; + + if (reverse && typeof this._delegate.cssStyleDeclarationSectionEditorPreviousRule === "function") + this._delegate.cssStyleDeclarationSectionEditorPreviousRule(this); + else if (!reverse && typeof this._delegate.cssStyleDeclarationSectionEditorNextRule === "function") + this._delegate.cssStyleDeclarationSectionEditorNextRule(this); + } + + focusRuleSelector(reverse) + { + if (!this.selectorEditable && !this.locked) { + this.focus(); + return; + } + + if (this.locked) { + this.cssStyleDeclarationTextEditorSwitchRule(reverse); + return; + } + + let selection = window.getSelection(); + selection.removeAllRanges(); + + this._element.scrollIntoViewIfNeeded(); + + if (this._selectorInput) { + this._selectorInput.focus(); + this._selectorInput.selectionStart = 0; + this._selectorInput.selectionEnd = this._selectorInput.value.length; + } else { + let range = document.createRange(); + range.selectNodeContents(this._selectorElement); + selection.addRange(range); + } + } + + selectLastProperty() + { + this._propertiesTextEditor.selectLastProperty(); + } + + get selectorEditable() + { + return !this.locked && this._style.ownerRule; + } + + get locked() + { + return !this._style.editable; + } + + get editorActive() + { + return this._editorActive; + } + + // Private + + get _currentSelectorText() + { + let selectorText = this.selectorEditable ? this._selectorInput.value : this._selectorElement.textContent; + if (!selectorText || !selectorText.length) { + if (!this._style.ownerRule) + return ""; + + selectorText = this._style.ownerRule.selectorText; + } + + return selectorText.trim(); + } + + _handleSelectorPaste(event) + { + if (this._style.type === WebInspector.CSSStyleDeclaration.Type.Inline || !this._style.ownerRule) + return; + + if (!event || !event.clipboardData) + return; + + let data = event.clipboardData.getData("text/plain"); + if (!data) + return; + + function parseTextForRule(text) + { + let containsBraces = /[\{\}]/; + if (!containsBraces.test(text)) + return []; + + let match = text.match(/([^{]+){([\s\S]*)}/); + if (!match) + return []; + + // If the match "body" contains braces, parse that body as if it were a rule. + // This will usually happen if the user includes a media query in the copied text. + return containsBraces.test(match[2]) ? parseTextForRule(match[2]) : match; + } + + let [selector, value] = parseTextForRule(data); + if (!selector || !value) + return; + + this._style.nodeStyles.changeRule(this._style.ownerRule, selector.trim(), value); + event.preventDefault(); + } + + _handleContextMenuEvent(event) + { + if (window.getSelection().toString().length) + return; + + let contextMenu = WebInspector.ContextMenu.createFromEvent(event); + + contextMenu.appendItem(WebInspector.UIString("Copy Rule"), () => { + InspectorFrontendHost.copyText(this._style.generateCSSRuleString()); + }); + + if (this._style.inherited) + return; + + contextMenu.appendItem(WebInspector.UIString("Duplicate Selector"), () => { + if (this._delegate && typeof this._delegate.focusEmptySectionWithStyle === "function") { + let existingRules = this._style.nodeStyles.rulesForSelector(this._currentSelectorText); + for (let rule of existingRules) { + if (this._delegate.focusEmptySectionWithStyle(rule.style)) + return; + } + } + + this._style.nodeStyles.addRule(this._currentSelectorText); + }); + + // Only used one colon temporarily since single-colon pseudo elements are valid CSS. + if (WebInspector.CSSStyleManager.PseudoElementNames.some((className) => this._style.selectorText.includes(":" + className))) + return; + + if (WebInspector.CSSStyleManager.ForceablePseudoClasses.every((className) => !this._style.selectorText.includes(":" + className))) { + contextMenu.appendSeparator(); + + for (let pseudoClass of WebInspector.CSSStyleManager.ForceablePseudoClasses) { + if (pseudoClass === "visited" && this._style.node.nodeName() !== "A") + continue; + + let pseudoClassSelector = ":" + pseudoClass; + + contextMenu.appendItem(WebInspector.UIString("Add %s Rule").format(pseudoClassSelector), () => { + this._style.node.setPseudoClassEnabled(pseudoClass, true); + + let selector; + if (this._style.ownerRule) + selector = this._style.ownerRule.selectors.map((selector) => selector.text + pseudoClassSelector).join(", "); + else + selector = this._currentSelectorText + pseudoClassSelector; + + this._style.nodeStyles.addRule(selector); + }); + } + } + + contextMenu.appendSeparator(); + + for (let pseudoElement of WebInspector.CSSStyleManager.PseudoElementNames) { + let pseudoElementSelector = "::" + pseudoElement; + const styleText = "content: \"\";"; + + let existingSection = null; + if (this._delegate && typeof this._delegate.sectionForStyle === "function") { + let existingRules = this._style.nodeStyles.rulesForSelector(this._currentSelectorText + pseudoElementSelector); + if (existingRules.length) { + // There shouldn't really ever be more than one pseudo-element rule + // that is not in a media query. As such, just focus the first rule + // on the assumption that it is the only one necessary. + existingSection = this._delegate.sectionForStyle(existingRules[0].style); + } + } + + let title = existingSection ? WebInspector.UIString("Focus %s Rule") : WebInspector.UIString("Create %s Rule"); + contextMenu.appendItem(title.format(pseudoElementSelector), () => { + if (existingSection) { + existingSection.focus(); + return; + } + + let selector; + if (this._style.ownerRule) + selector = this._style.ownerRule.selectors.map((selector) => selector.text + pseudoElementSelector).join(", "); + else + selector = this._currentSelectorText + pseudoElementSelector; + + this._style.nodeStyles.addRule(selector, styleText); + }); + } + } + + _handleIconElementClicked() + { + if (this._hasInvalidSelector) { + // This will revert the selector text to the original valid value. + this.refresh(); + return; + } + + this._ruleDisabled = this._ruleDisabled ? !this._propertiesTextEditor.uncommentAllProperties() : this._propertiesTextEditor.commentAllProperties(); + this._iconElement.title = this._ruleDisabled ? WebInspector.UIString("Uncomment All Properties") : WebInspector.UIString("Comment All Properties"); + this._element.classList.toggle("rule-disabled", this._ruleDisabled); + } + + _highlightNodesWithSelector() + { + if (!this._style.ownerRule) { + WebInspector.domTreeManager.highlightDOMNode(this._style.node.id); + return; + } + + WebInspector.domTreeManager.highlightSelector(this._currentSelectorText, this._style.node.ownerDocument.frameIdentifier); + } + + _hideDOMNodeHighlight() + { + WebInspector.domTreeManager.hideDOMNodeHighlight(); + } + + _handleMouseOver(event) + { + this._highlightNodesWithSelector(); + } + + _handleMouseMove(event) + { + if (this._hasInvalidSelector) + return; + + // Attempts to find a selector element under the mouse so that the title (which contains the + // specificity information) can be applied to _selectorInput, which will then display the + // title if the user hovers long enough. + for (let element of this._selectorElements) { + let {top, right, bottom, left} = element.getBoundingClientRect(); + if (event.clientX >= left && event.clientX <= right && event.clientY >= top && event.clientY <= bottom) { + this._selectorInput.title = element.title; + return; + } + } + + this._selectorInput.title = ""; + } + + _handleMouseOut(event) + { + this._hideDOMNodeHighlight(); + } + + _save(event) + { + event.preventDefault(); + event.stopPropagation(); + + if (this._style.type !== WebInspector.CSSStyleDeclaration.Type.Rule) { + // FIXME: Can't save CSS inside + InspectorFrontendHost.beep(); + return; + } + + console.assert(this._style.ownerRule instanceof WebInspector.CSSRule); + console.assert(this._style.ownerRule.sourceCodeLocation instanceof WebInspector.SourceCodeLocation); + + let sourceCode = this._style.ownerRule.sourceCodeLocation.sourceCode; + if (sourceCode.type !== WebInspector.Resource.Type.Stylesheet) { + // FIXME: Can't save CSS inside style="" + InspectorFrontendHost.beep(); + return; + } + + var url; + if (sourceCode.urlComponents.scheme === "data") { + let mainResource = WebInspector.frameResourceManager.mainFrame.mainResource; + let pathDirectory = mainResource.url.slice(0, -mainResource.urlComponents.lastPathComponent.length); + url = pathDirectory + "base64.css"; + } else + url = sourceCode.url; + + const saveAs = event.shiftKey; + WebInspector.saveDataToFile({url: url, content: sourceCode.content}, saveAs); + } + + _handleKeyDown(event) + { + if (event.keyCode === WebInspector.KeyboardShortcut.Key.Enter.keyCode) { + this._selectorInput.blur(); + return; + } + + if (event.keyCode !== WebInspector.KeyboardShortcut.Key.Tab.keyCode) { + this._highlightNodesWithSelector(); + return; + } + + if (event.shiftKey && this._delegate && typeof this._delegate.cssStyleDeclarationSectionEditorPreviousRule === "function") { + event.preventDefault(); + this._delegate.cssStyleDeclarationSectionEditorPreviousRule(this, true); + return; + } + + if (!event.metaKey) { + event.preventDefault(); + this.focus(); + this._propertiesTextEditor.selectFirstProperty(); + return; + } + } + + _handleKeyPress(event) + { + if (!event.altGraphKey && !event.altKey && !event.ctrlKey && !event.metaKey) { + // Ensures that