Change createObjectURL and revokeObjectURL to put under webkitURL.
[WebKit-https.git] / Source / WebCore / inspector / front-end / NetworkPanel.js
1 /*
2  * Copyright (C) 2007, 2008 Apple Inc.  All rights reserved.
3  * Copyright (C) 2008, 2009 Anthony Ricaud <rik@webkit.org>
4  * Copyright (C) 2010 Google Inc. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1.  Redistributions of source code must retain the above copyright
11  *     notice, this list of conditions and the following disclaimer.
12  * 2.  Redistributions in binary form must reproduce the above copyright
13  *     notice, this list of conditions and the following disclaimer in the
14  *     documentation and/or other materials provided with the distribution.
15  * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
16  *     its contributors may be used to endorse or promote products derived
17  *     from this software without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
20  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
23  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 WebInspector.NetworkPanel = function()
32 {
33     WebInspector.Panel.call(this, "network");
34
35     this.createSidebar();
36     this.sidebarElement.className = "network-sidebar";
37
38     this._resources = [];
39     this._resourcesById = {};
40     this._resourcesByURL = {};
41     this._lastIdentifier = 0;
42     this._staleResources = [];
43     this._resourceGridNodes = {};
44     this._mainResourceLoadTime = -1;
45     this._mainResourceDOMContentTime = -1;
46     this._hiddenCategories = {};
47
48     this._categories = WebInspector.resourceCategories;
49
50     this.containerElement = document.createElement("div");
51     this.containerElement.id = "network-container";
52     this.sidebarElement.appendChild(this.containerElement);
53
54     this._viewsContainerElement = document.createElement("div");
55     this._viewsContainerElement.id = "network-views";
56     this._viewsContainerElement.className = "hidden";
57     this.element.appendChild(this._viewsContainerElement);
58
59     this._closeButtonElement = document.createElement("button");
60     this._closeButtonElement.id = "network-close-button";
61     this._closeButtonElement.addEventListener("click", this._toggleGridMode.bind(this), false);
62     this._viewsContainerElement.appendChild(this._closeButtonElement);
63
64     this._createSortingFunctions();
65     this._createTable();
66     this._createTimelineGrid();
67     this._createStatusbarButtons();
68     this._createFilterStatusBarItems();
69     this._createSummaryBar();
70
71     if (!WebInspector.settings.resourcesLargeRows)
72         this._setLargerResources(WebInspector.settings.resourcesLargeRows);
73
74     this._popoverHelper = new WebInspector.PopoverHelper(this.element, this._getPopoverAnchor.bind(this), this._showPopover.bind(this), true);
75     // Enable faster hint.
76     this._popoverHelper.setTimeout(100);
77
78     this.calculator = new WebInspector.NetworkTransferTimeCalculator();
79     this._filter(this._filterAllElement, false);
80
81     this._toggleGridMode();
82 }
83
84 WebInspector.NetworkPanel.prototype = {
85     get toolbarItemLabel()
86     {
87         return WebInspector.UIString("Network");
88     },
89
90     get statusBarItems()
91     {
92         return [this._largerResourcesButton.element, this._preserveLogToggle.element, this._clearButton.element, this._filterBarElement];
93     },
94
95     isCategoryVisible: function(categoryName)
96     {
97         return true;
98     },
99
100     elementsToRestoreScrollPositionsFor: function()
101     {
102         return [this.containerElement];
103     },
104
105     resize: function()
106     {
107         WebInspector.Panel.prototype.resize.call(this);
108         this._dataGrid.updateWidths();
109         this._positionSummaryBar();
110     },
111
112     updateSidebarWidth: function(width)
113     {
114         if (!this._viewingResourceMode)
115             return;
116         WebInspector.Panel.prototype.updateSidebarWidth.call(this, width);
117         if (this._summaryBarElement.parentElement === this.element)
118             this._summaryBarElement.style.width = width + "px";
119     },
120
121     updateMainViewWidth: function(width)
122     {
123         this._viewsContainerElement.style.left = width + "px";
124     },
125
126     handleShortcut: function(event)
127     {
128         if (this._viewingResourceMode && event.keyCode === WebInspector.KeyboardShortcut.Keys.Esc.code) {
129             this._toggleGridMode();
130             event.handled = true;
131         }
132     },
133
134     _positionSummaryBar: function()
135     {
136         // Position the total bar.
137
138         var fillerRow = this._dataGrid.dataTableBody.lastChild;
139         if (this._summaryBarElement.parentElement !== this.element && fillerRow.offsetHeight > 0) {
140             // Glue status to bottom.
141             if (this._summaryBarRowNode) {
142                 this._dataGrid.removeChild(this._summaryBarRowNode);
143                 delete this._summaryBarRowNode;
144             }
145             this._summaryBarElement.addStyleClass("network-summary-bar-bottom");
146             this._summaryBarElement.style.setProperty("width", this.sidebarElement.offsetWidth + "px");
147             this.element.appendChild(this._summaryBarElement);
148             this._dataGrid.element.style.bottom = "20px";
149             return;
150         }
151
152         if (!this._summaryBarRowNode && !fillerRow.offsetHeight) {
153             // Glue status to table.
154             this._summaryBarRowNode = new WebInspector.NetworkTotalGridNode(this._summaryBarElement);
155             this._summaryBarElement.removeStyleClass("network-summary-bar-bottom");
156             this._summaryBarElement.style.removeProperty("width");
157             this._dataGrid.appendChild(this._summaryBarRowNode);
158             this._dataGrid.element.style.bottom = 0;
159             this._sortItems();
160         }
161     },
162
163     _resetSummaryBar: function()
164     {
165         delete this._summaryBarRowNode;
166         this._summaryBarElement.parentElement.removeChild(this._summaryBarElement);
167         this._updateSummaryBar();
168     },
169
170     _createTimelineGrid: function()
171     {
172         this._timelineGrid = new WebInspector.TimelineGrid();
173         this._timelineGrid.element.addStyleClass("network-timeline-grid");
174         this._dataGrid.element.appendChild(this._timelineGrid.element);
175     },
176
177     _createTable: function()
178     {
179         var columns = {name: {}, method: {}, status: {}, type: {}, size: {}, time: {}, timeline: {}};
180         columns.name.titleDOMFragment = this._makeHeaderFragment(WebInspector.UIString("Name"), WebInspector.UIString("Path"));
181         columns.name.sortable = true;
182         columns.name.width = "20%";
183         columns.name.disclosure = true;
184
185         columns.method.title = WebInspector.UIString("Method");
186         columns.method.sortable = true;
187         columns.method.width = "7%";
188
189         columns.status.titleDOMFragment = this._makeHeaderFragment(WebInspector.UIString("Status"), WebInspector.UIString("Text"));
190         columns.status.sortable = true;
191         columns.status.width = "8%";
192
193         columns.type.title = WebInspector.UIString("Type");
194         columns.type.sortable = true;
195         columns.type.width = "10%";
196
197         columns.size.titleDOMFragment = this._makeHeaderFragment(WebInspector.UIString("Size"), WebInspector.UIString("Transfer"));
198         columns.size.sortable = true;
199         columns.size.width = "10%";
200         columns.size.aligned = "right";
201
202         columns.time.titleDOMFragment = this._makeHeaderFragment(WebInspector.UIString("Time"), WebInspector.UIString("Latency"));
203         columns.time.sortable = true;
204         columns.time.width = "10%";
205         columns.time.aligned = "right";
206
207         columns.timeline.title = "";
208         columns.timeline.sortable = false;
209         columns.timeline.width = "37%";
210         columns.timeline.sort = "ascending";
211
212         this._dataGrid = new WebInspector.DataGrid(columns);
213         this._dataGrid.element.addEventListener("contextmenu", this._contextMenu.bind(this), true);
214         this.containerElement.appendChild(this._dataGrid.element);
215         this._dataGrid.addEventListener("sorting changed", this._sortItems, this);
216         this._dataGrid.addEventListener("width changed", this._updateDividersIfNeeded, this);
217
218         this._patchTimelineHeader();
219     },
220
221     _makeHeaderFragment: function(title, subtitle)
222     {
223         var fragment = document.createDocumentFragment();
224         fragment.appendChild(document.createTextNode(title));
225         var subtitleDiv = document.createElement("div");
226         subtitleDiv.className = "network-header-subtitle";
227         subtitleDiv.textContent = subtitle;
228         fragment.appendChild(subtitleDiv);
229         return fragment;
230     },
231
232     _patchTimelineHeader: function()
233     {
234         var timelineSorting = document.createElement("select");
235
236         var option = document.createElement("option");
237         option.value = "startTime";
238         option.label = WebInspector.UIString("Timeline");
239         timelineSorting.appendChild(option);
240
241         option = document.createElement("option");
242         option.value = "startTime";
243         option.label = WebInspector.UIString("Start Time");
244         timelineSorting.appendChild(option);
245
246         option = document.createElement("option");
247         option.value = "responseTime";
248         option.label = WebInspector.UIString("Response Time");
249         timelineSorting.appendChild(option);
250
251         option = document.createElement("option");
252         option.value = "endTime";
253         option.label = WebInspector.UIString("End Time");
254         timelineSorting.appendChild(option);
255
256         option = document.createElement("option");
257         option.value = "duration";
258         option.label = WebInspector.UIString("Duration");
259         timelineSorting.appendChild(option);
260
261         option = document.createElement("option");
262         option.value = "latency";
263         option.label = WebInspector.UIString("Latency");
264         timelineSorting.appendChild(option);
265
266         var header = this._dataGrid.headerTableHeader("timeline");
267         header.replaceChild(timelineSorting, header.firstChild);
268
269         timelineSorting.addEventListener("click", function(event) { event.stopPropagation() }, false);
270         timelineSorting.addEventListener("change", this._sortByTimeline.bind(this), false);
271         this._timelineSortSelector = timelineSorting;
272     },
273
274     _createSortingFunctions: function()
275     {
276         this._sortingFunctions = {};
277         this._sortingFunctions.name = WebInspector.NetworkDataGridNode.NameComparator;
278         this._sortingFunctions.method = WebInspector.NetworkDataGridNode.ResourcePropertyComparator.bind(null, "method", false);
279         this._sortingFunctions.status = WebInspector.NetworkDataGridNode.ResourcePropertyComparator.bind(null, "statusCode", false);
280         this._sortingFunctions.type = WebInspector.NetworkDataGridNode.ResourcePropertyComparator.bind(null, "mimeType", false);
281         this._sortingFunctions.size = WebInspector.NetworkDataGridNode.SizeComparator;
282         this._sortingFunctions.time = WebInspector.NetworkDataGridNode.ResourcePropertyComparator.bind(null, "duration", false);
283         this._sortingFunctions.timeline = WebInspector.NetworkDataGridNode.ResourcePropertyComparator.bind(null, "startTime", false);
284         this._sortingFunctions.startTime = WebInspector.NetworkDataGridNode.ResourcePropertyComparator.bind(null, "startTime", false);
285         this._sortingFunctions.endTime = WebInspector.NetworkDataGridNode.ResourcePropertyComparator.bind(null, "endTime", false);
286         this._sortingFunctions.responseTime = WebInspector.NetworkDataGridNode.ResourcePropertyComparator.bind(null, "responseReceivedTime", false);
287         this._sortingFunctions.duration = WebInspector.NetworkDataGridNode.ResourcePropertyComparator.bind(null, "duration", true);
288         this._sortingFunctions.latency = WebInspector.NetworkDataGridNode.ResourcePropertyComparator.bind(null, "latency", true);
289
290         var timeCalculator = new WebInspector.NetworkTransferTimeCalculator();
291         var durationCalculator = new WebInspector.NetworkTransferDurationCalculator();
292
293         this._calculators = {};
294         this._calculators.timeline = timeCalculator;
295         this._calculators.startTime = timeCalculator;
296         this._calculators.endTime = timeCalculator;
297         this._calculators.responseTime = timeCalculator;
298         this._calculators.duration = durationCalculator;
299         this._calculators.latency = durationCalculator;
300     },
301
302     _sortItems: function()
303     {
304         var columnIdentifier = this._dataGrid.sortColumnIdentifier;
305         if (columnIdentifier === "timeline") {
306             this._sortByTimeline();
307             return;
308         }
309         var sortingFunction = this._sortingFunctions[columnIdentifier];
310         if (!sortingFunction)
311             return;
312
313         this._dataGrid.sortNodes(sortingFunction, this._dataGrid.sortOrder === "descending");
314         this._timelineSortSelector.selectedIndex = 0;
315     },
316
317     _sortByTimeline: function()
318     {
319         var selectedIndex = this._timelineSortSelector.selectedIndex;
320         if (!selectedIndex)
321             selectedIndex = 1; // Sort by start time by default.
322         var selectedOption = this._timelineSortSelector[selectedIndex];
323         var value = selectedOption.value;
324
325         var sortingFunction = this._sortingFunctions[value];
326         this._dataGrid.sortNodes(sortingFunction);
327         this.calculator = this._calculators[value];
328         if (this.calculator.startAtZero)
329             this._timelineGrid.hideEventDividers();
330         else
331             this._timelineGrid.showEventDividers();
332         this._dataGrid.markColumnAsSortedBy("timeline", "ascending");
333     },
334
335     _createFilterStatusBarItems: function()
336     {
337         var filterBarElement = document.createElement("div");
338         filterBarElement.className = "scope-bar status-bar-item";
339         filterBarElement.id = "network-filter";
340
341         function createFilterElement(category, label)
342         {
343             var categoryElement = document.createElement("li");
344             categoryElement.category = category;
345             categoryElement.className = category;
346             categoryElement.appendChild(document.createTextNode(label));
347             categoryElement.addEventListener("click", this._updateFilter.bind(this), false);
348             filterBarElement.appendChild(categoryElement);
349
350             return categoryElement;
351         }
352
353         this._filterAllElement = createFilterElement.call(this, "all", WebInspector.UIString("All"));
354
355         // Add a divider
356         var dividerElement = document.createElement("div");
357         dividerElement.addStyleClass("scope-bar-divider");
358         filterBarElement.appendChild(dividerElement);
359
360         for (var category in this._categories)
361             createFilterElement.call(this, category, this._categories[category].title);
362         this._filterBarElement = filterBarElement;
363     },
364
365     _createSummaryBar: function()
366     {
367         this._summaryBarElement = document.createElement("div");
368         this._summaryBarElement.className = "network-summary-bar";
369         this.containerElement.appendChild(this._summaryBarElement);
370     },
371
372     _updateSummaryBar: function()
373     {
374         this._positionSummaryBar(); // Grid is growing.
375         var numRequests = this._resources.length;
376
377         if (!numRequests) {
378             if (this._summaryBarElement._isDisplayingWarning)
379                 return;
380             this._summaryBarElement._isDisplayingWarning = true;
381
382             var img = document.createElement("img");
383             img.src = "Images/warningIcon.png";
384             this._summaryBarElement.removeChildren();
385             this._summaryBarElement.appendChild(img);
386             this._summaryBarElement.appendChild(document.createTextNode(" "));
387             this._summaryBarElement.appendChild(document.createTextNode(
388                 WebInspector.UIString("No requests captured. Reload the page to see detailed information on the network activity.")));
389             return;
390         }
391         delete this._summaryBarElement._isDisplayingWarning;
392
393         var transferSize = 0;
394         var baseTime = -1;
395         var maxTime = -1;
396         for (var i = 0; i < this._resources.length; ++i) {
397             var resource = this._resources[i];
398             transferSize += (resource.cached || !resource.transferSize) ? 0 : resource.transferSize;
399             if (resource.isMainResource)
400                 baseTime = resource.startTime;
401             if (resource.endTime > maxTime)
402                 maxTime = resource.endTime;
403         }
404         var text = String.sprintf(WebInspector.UIString("%d requests"), numRequests);
405         text += "  \u2758  " + String.sprintf(WebInspector.UIString("%s transferred"), Number.bytesToString(transferSize));
406         if (baseTime !== -1 && this._mainResourceLoadTime !== -1 && this._mainResourceDOMContentTime !== -1 && this._mainResourceDOMContentTime > baseTime) {
407             text += "  \u2758  " + String.sprintf(WebInspector.UIString("%s (onload: %s, DOMContentLoaded: %s)"),
408                         Number.secondsToString(maxTime - baseTime),
409                         Number.secondsToString(this._mainResourceLoadTime - baseTime),
410                         Number.secondsToString(this._mainResourceDOMContentTime - baseTime));
411         }
412         this._summaryBarElement.textContent = text;
413     },
414
415     _showCategory: function(category)
416     {
417         this._dataGrid.element.addStyleClass("filter-" + category);
418         delete this._hiddenCategories[category];
419     },
420
421     _hideCategory: function(category)
422     {
423         this._dataGrid.element.removeStyleClass("filter-" + category);
424         this._hiddenCategories[category] = true;
425     },
426
427     _updateFilter: function(e)
428     {
429         var isMac = WebInspector.isMac();
430         var selectMultiple = false;
431         if (isMac && e.metaKey && !e.ctrlKey && !e.altKey && !e.shiftKey)
432             selectMultiple = true;
433         if (!isMac && e.ctrlKey && !e.metaKey && !e.altKey && !e.shiftKey)
434             selectMultiple = true;
435
436         this._filter(e.target, selectMultiple);
437         this._positionSummaryBar();
438     },
439
440     _filter: function(target, selectMultiple)
441     {
442         function unselectAll()
443         {
444             for (var i = 0; i < this._filterBarElement.childNodes.length; ++i) {
445                 var child = this._filterBarElement.childNodes[i];
446                 if (!child.category)
447                     continue;
448
449                 child.removeStyleClass("selected");
450                 this._hideCategory(child.category);
451             }
452         }
453
454         if (target.category === this._filterAllElement) {
455             if (target.hasStyleClass("selected")) {
456                 // We can't unselect All, so we break early here
457                 return;
458             }
459
460             // If All wasn't selected, and now is, unselect everything else.
461             unselectAll.call(this);
462         } else {
463             // Something other than All is being selected, so we want to unselect All.
464             if (this._filterAllElement.hasStyleClass("selected")) {
465                 this._filterAllElement.removeStyleClass("selected");
466                 this._hideCategory("all");
467             }
468         }
469
470         if (!selectMultiple) {
471             // If multiple selection is off, we want to unselect everything else
472             // and just select ourselves.
473             unselectAll.call(this);
474
475             target.addStyleClass("selected");
476             this._showCategory(target.category);
477             return;
478         }
479
480         if (target.hasStyleClass("selected")) {
481             // If selectMultiple is turned on, and we were selected, we just
482             // want to unselect ourselves.
483             target.removeStyleClass("selected");
484             this._hideCategory(target.category);
485         } else {
486             // If selectMultiple is turned on, and we weren't selected, we just
487             // want to select ourselves.
488             target.addStyleClass("selected");
489             this._showCategory(target.category);
490         }
491     },
492
493     _scheduleRefresh: function()
494     {
495         if (this._needsRefresh)
496             return;
497
498         this._needsRefresh = true;
499
500         if (this.visible && !("_refreshTimeout" in this))
501             this._refreshTimeout = setTimeout(this.refresh.bind(this), 500);
502     },
503
504     _updateDividersIfNeeded: function(force)
505     {
506         var timelineColumn = this._dataGrid.columns.timeline;
507         for (var i = 0; i < this._dataGrid.resizers.length; ++i) {
508             if (timelineColumn.ordinal === this._dataGrid.resizers[i].rightNeighboringColumnID) {
509                 // Position timline grid location.
510                 this._timelineGrid.element.style.left = this._dataGrid.resizers[i].style.left;
511                 this._timelineGrid.element.style.right = "18px";
512             }
513         }
514
515         var proceed = true;
516         if (!this.visible) {
517             this._scheduleRefresh();
518             proceed = false;
519         } else
520             proceed = this._timelineGrid.updateDividers(force, this.calculator);
521
522         if (!proceed)
523             return;
524
525         if (this.calculator.startAtZero || !this.calculator.computePercentageFromEventTime) {
526             // If our current sorting method starts at zero, that means it shows all
527             // resources starting at the same point, and so onLoad event and DOMContent
528             // event lines really wouldn't make much sense here, so don't render them.
529             // Additionally, if the calculator doesn't have the computePercentageFromEventTime
530             // function defined, we are probably sorting by size, and event times aren't relevant
531             // in this case.
532             return;
533         }
534
535         this._timelineGrid.removeEventDividers();
536         if (this._mainResourceLoadTime !== -1) {
537             var percent = this.calculator.computePercentageFromEventTime(this._mainResourceLoadTime);
538
539             var loadDivider = document.createElement("div");
540             loadDivider.className = "network-event-divider network-red-divider";
541
542             var loadDividerPadding = document.createElement("div");
543             loadDividerPadding.className = "network-event-divider-padding";
544             loadDividerPadding.title = WebInspector.UIString("Load event fired");
545             loadDividerPadding.appendChild(loadDivider);
546             loadDividerPadding.style.left = percent + "%";
547             this._timelineGrid.addEventDivider(loadDividerPadding);
548         }
549
550         if (this._mainResourceDOMContentTime !== -1) {
551             var percent = this.calculator.computePercentageFromEventTime(this._mainResourceDOMContentTime);
552
553             var domContentDivider = document.createElement("div");
554             domContentDivider.className = "network-event-divider network-blue-divider";
555
556             var domContentDividerPadding = document.createElement("div");
557             domContentDividerPadding.className = "network-event-divider-padding";
558             domContentDividerPadding.title = WebInspector.UIString("DOMContent event fired");
559             domContentDividerPadding.appendChild(domContentDivider);
560             domContentDividerPadding.style.left = percent + "%";
561             this._timelineGrid.addEventDivider(domContentDividerPadding);
562         }
563     },
564
565     _refreshIfNeeded: function()
566     {
567         if (this._needsRefresh)
568             this.refresh();
569     },
570
571     _invalidateAllItems: function()
572     {
573         this._staleResources = this._resources.slice();
574     },
575
576     get calculator()
577     {
578         return this._calculator;
579     },
580
581     set calculator(x)
582     {
583         if (!x || this._calculator === x)
584             return;
585
586         this._calculator = x;
587         this._calculator.reset();
588
589         this._invalidateAllItems();
590         this.refresh();
591     },
592
593     _resourceGridNode: function(resource)
594     {
595         return this._resourceGridNodes[resource.identifier];
596     },
597
598     revealAndSelectItem: function(resource)
599     {
600         var node = this._resourceGridNode(resource);
601         if (node) {
602             node.reveal();
603             node.select(true);
604         }
605     },
606
607     addEventDivider: function(divider)
608     {
609         this._timelineGrid.addEventDivider(divider);
610     },
611
612     _createStatusbarButtons: function()
613     {
614         this._preserveLogToggle = new WebInspector.StatusBarButton(WebInspector.UIString("Preserve Log upon Navigation"), "record-profile-status-bar-item");
615         this._preserveLogToggle.addEventListener("click", this._onPreserveLogClicked.bind(this), false);
616
617         this._clearButton = new WebInspector.StatusBarButton(WebInspector.UIString("Clear"), "clear-status-bar-item");
618         this._clearButton.addEventListener("click", this._reset.bind(this), false);
619
620         this._largerResourcesButton = new WebInspector.StatusBarButton(WebInspector.UIString("Use small resource rows."), "network-larger-resources-status-bar-item");
621         this._largerResourcesButton.toggled = WebInspector.settings.resourcesLargeRows;
622         this._largerResourcesButton.addEventListener("click", this._toggleLargerResources.bind(this), false);
623     },
624
625     set mainResourceLoadTime(x)
626     {
627         if (this._mainResourceLoadTime === x)
628             return;
629
630         this._mainResourceLoadTime = x || -1;
631         // Update the dividers to draw the new line
632         this._updateDividersIfNeeded(true);
633     },
634
635     set mainResourceDOMContentTime(x)
636     {
637         if (this._mainResourceDOMContentTime === x)
638             return;
639
640         this._mainResourceDOMContentTime = x || -1;
641         this._updateDividersIfNeeded(true);
642     },
643
644     show: function()
645     {
646         WebInspector.Panel.prototype.show.call(this);
647         this._refreshIfNeeded();
648
649         if (this.visibleView)
650             this.visibleView.show(this._viewsContainerElement);
651
652         this._dataGrid.updateWidths();
653         this._positionSummaryBar();
654     },
655
656     hide: function()
657     {
658         WebInspector.Panel.prototype.hide.call(this);
659         this._popoverHelper.hidePopup();
660     },
661
662     get searchableViews()
663     {
664         var views = [];
665         return views;
666     },
667
668     searchMatchFound: function(view, matches)
669     {
670         this._resourceGridNode(view.resource).searchMatches = matches;
671     },
672
673     searchCanceled: function(startingNewSearch)
674     {
675         WebInspector.Panel.prototype.searchCanceled.call(this, startingNewSearch);
676
677         if (startingNewSearch || !this._resources)
678             return;
679     },
680
681     performSearch: function(query)
682     {
683         WebInspector.Panel.prototype.performSearch.call(this, query);
684     },
685
686     refresh: function()
687     {
688         this._needsRefresh = false;
689         if ("_refreshTimeout" in this) {
690             clearTimeout(this._refreshTimeout);
691             delete this._refreshTimeout;
692         }
693
694         var wasScrolledToLastRow = this._dataGrid.isScrolledToLastRow();
695         var staleItemsLength = this._staleResources.length;
696         var boundariesChanged = false;
697
698         for (var i = 0; i < staleItemsLength; ++i) {
699             var resource = this._staleResources[i];
700             var node = this._resourceGridNode(resource);
701             if (!node) {
702                 // Create the timeline tree element and graph.
703                 node = new WebInspector.NetworkDataGridNode(this, resource);
704                 this._resourceGridNodes[resource.identifier] = node;
705                 this._dataGrid.appendChild(node);
706             }
707             node.refreshResource();
708
709             if (this.calculator.updateBoundaries(resource))
710                 boundariesChanged = true;
711         }
712
713         if (boundariesChanged) {
714             // The boundaries changed, so all item graphs are stale.
715             this._invalidateAllItems();
716             staleItemsLength = this._staleResources.length;
717         }
718
719         for (var i = 0; i < staleItemsLength; ++i)
720             this._resourceGridNode(this._staleResources[i]).refreshGraph(this.calculator);
721
722         this._staleResources = [];
723         this._sortItems();
724         this._updateSummaryBar();
725         this._dataGrid.updateWidths();
726
727         if (wasScrolledToLastRow)
728             this._dataGrid.scrollToLastRow();
729     },
730
731     _onPreserveLogClicked: function(e)
732     {
733         this._preserveLogToggle.toggled = !this._preserveLogToggle.toggled;
734     },
735
736     reset: function()
737     {
738         if (!this._preserveLogToggle.toggled)
739             this._reset();
740     },
741
742     _reset: function()
743     {
744         this._popoverHelper.hidePopup();
745         this._closeVisibleResource();
746
747         this._toggleGridMode();
748
749         // Begin reset timeline
750         if (this._calculator)
751             this._calculator.reset();
752
753         this._resources = [];
754         this._resourcesById = {};
755         this._resourcesByURL = {};
756         this._staleResources = [];
757         this._resourceGridNodes = {};
758
759         this._dataGrid.removeChildren();
760         delete this._summaryBarRowNode;
761         this._updateDividersIfNeeded(true);
762         // End reset timeline.
763
764         this._mainResourceLoadTime = -1;
765         this._mainResourceDOMContentTime = -1;
766
767         this._viewsContainerElement.removeChildren();
768         this._viewsContainerElement.appendChild(this._closeButtonElement);
769         this._resetSummaryBar();
770     },
771
772     get resources()
773     {
774         return this._resourcesById;
775     },
776
777     refreshResource: function(resource)
778     {
779         if (!resource.identifier)
780             resource.identifier = "network:" + this._lastIdentifier++;
781
782         if (!this._resourcesById[resource.identifier]) {
783             this._resources.push(resource);
784             this._resourcesById[resource.identifier] = resource;
785             this._resourcesByURL[resource.url] = resource;
786
787             // Pull all the redirects of the main resource upon commit load.
788             if (resource.redirects) {
789                 for (var i = 0; i < resource.redirects.length; ++i)
790                     this.refreshResource(resource.redirects[i]);
791             }
792         }
793
794         this._staleResources.push(resource);
795         this._scheduleRefresh();
796
797         if (!resource)
798             return;
799
800         var oldView = WebInspector.ResourceView.existingResourceViewForResource(resource);
801         if (!oldView)
802             return;
803
804         if (WebInspector.ResourceView.resourceViewTypeMatchesResource(resource))
805             return;
806
807         var newView = WebInspector.ResourceView.recreateResourceView(resource);
808         if (this.visibleView === oldView)
809             this.visibleView = newView;
810     },
811
812     canShowSourceLine: function(url, line)
813     {
814         return !!this._resourcesByURL[url];
815     },
816
817     showSourceLine: function(url, line)
818     {
819         this._showResource(this._resourcesByURL[url], line);
820     },
821
822     _showResource: function(resource, line)
823     {
824         if (!resource)
825             return;
826
827         this._popoverHelper.hidePopup();
828
829         this._toggleViewingResourceMode();
830
831         if (this.visibleView) {
832             this.visibleView.detach();
833             delete this.visibleView;
834         }
835
836         var view = new WebInspector.NetworkItemView(resource);
837         view.show(this._viewsContainerElement);
838         this.visibleView = view;
839
840         this.updateSidebarWidth();
841     },
842
843     _closeVisibleResource: function()
844     {
845         this.element.removeStyleClass("viewing-resource");
846
847         if (this.visibleView) {
848             this.visibleView.detach();
849             delete this.visibleView;
850         }
851
852         if (this._lastSelectedGraphTreeElement)
853             this._lastSelectedGraphTreeElement.select(true);
854
855         this.updateSidebarWidth();
856     },
857
858     _toggleLargerResources: function()
859     {
860         WebInspector.settings.resourcesLargeRows = !WebInspector.settings.resourcesLargeRows;
861         this._setLargerResources(WebInspector.settings.resourcesLargeRows);
862     },
863
864     _setLargerResources: function(enabled)
865     {
866         this._largerResourcesButton.toggled = enabled;
867         if (!enabled) {
868             this._largerResourcesButton.title = WebInspector.UIString("Use large resource rows.");
869             this._dataGrid.element.addStyleClass("small");
870             this._timelineGrid.element.addStyleClass("small");
871             this._viewsContainerElement.addStyleClass("small");
872         } else {
873             this._largerResourcesButton.title = WebInspector.UIString("Use small resource rows.");
874             this._dataGrid.element.removeStyleClass("small");
875             this._timelineGrid.element.removeStyleClass("small");
876             this._viewsContainerElement.removeStyleClass("small");
877         }
878         this._positionSummaryBar();
879     },
880
881     _getPopoverAnchor: function(element)
882     {
883         var anchor = element.enclosingNodeOrSelfWithClass("network-graph-bar") || element.enclosingNodeOrSelfWithClass("network-graph-label");
884         if (!anchor)
885             return null;
886         var resource = anchor.parentElement.resource;
887         return resource && resource.timing ? anchor : null;
888     },
889
890     _showPopover: function(anchor)
891     {
892         var resource = anchor.parentElement.resource;
893         var tableElement = WebInspector.ResourceTimingView.createTimingTable(resource);
894         var popover = new WebInspector.Popover(tableElement);
895         popover.show(anchor);
896         return popover;
897     },
898
899     _toggleGridMode: function()
900     {
901         if (this._viewingResourceMode) {
902             this._viewingResourceMode = false;
903             this.element.removeStyleClass("viewing-resource");
904             this._dataGrid.element.removeStyleClass("viewing-resource-mode");
905             this._viewsContainerElement.addStyleClass("hidden");
906             this.sidebarElement.style.right = 0;
907             this.sidebarElement.style.removeProperty("width");
908             this._summaryBarElement.style.removeProperty("width");
909             if (this._dataGrid.selectedNode)
910                 this._dataGrid.selectedNode.selected = false;
911         }
912
913         if (this._briefGrid) {
914             this._dataGrid.element.removeStyleClass("full-grid-mode");
915             this._dataGrid.element.addStyleClass("brief-grid-mode");
916
917             this._dataGrid.hideColumn("method");
918             this._dataGrid.hideColumn("status");
919             this._dataGrid.hideColumn("type");
920             this._dataGrid.hideColumn("size");
921             this._dataGrid.hideColumn("time");
922
923             var widths = {};
924             widths.name = 20;
925             widths.timeline = 80;
926         } else {
927             this._dataGrid.element.addStyleClass("full-grid-mode");
928             this._dataGrid.element.removeStyleClass("brief-grid-mode");
929
930             this._dataGrid.showColumn("method");
931             this._dataGrid.showColumn("status");
932             this._dataGrid.showColumn("type");
933             this._dataGrid.showColumn("size");
934             this._dataGrid.showColumn("time");
935
936             var widths = {};
937             widths.name = 20;
938             widths.method = 7;
939             widths.status = 8;
940             widths.type = 10;
941             widths.size = 10;
942             widths.time = 10;
943             widths.timeline = 37;
944         }
945
946         this._dataGrid.showColumn("timeline");
947         this._dataGrid.applyColumnWidthsMap(widths);
948
949     },
950
951     _toggleViewingResourceMode: function()
952     {
953         if (this._viewingResourceMode)
954             return;
955         this._viewingResourceMode = true;
956         this._preservedColumnWidths = this._dataGrid.columnWidthsMap();
957
958         this.element.addStyleClass("viewing-resource");
959         this._dataGrid.element.addStyleClass("viewing-resource-mode");
960         this._dataGrid.element.removeStyleClass("full-grid-mode");
961         this._dataGrid.element.removeStyleClass("brief-grid-mode");
962
963         this._dataGrid.hideColumn("method");
964         this._dataGrid.hideColumn("status");
965         this._dataGrid.hideColumn("type");
966         this._dataGrid.hideColumn("size");
967         this._dataGrid.hideColumn("time");
968         this._dataGrid.hideColumn("timeline");
969
970         this._viewsContainerElement.removeStyleClass("hidden");
971         this.updateSidebarWidth(200);
972
973         var widths = {};
974         widths.name = 100;
975         this._dataGrid.applyColumnWidthsMap(widths);
976     },
977
978     _contextMenu: function(event)
979     {
980         // createBlobURL is enabled conditionally, do not expose resource export if it's not available.
981         if (typeof window.webkitURL.createObjectURL !== "function" || !Preferences.resourceExportEnabled)
982             return;
983
984         var contextMenu = new WebInspector.ContextMenu();
985         var gridNode = this._dataGrid.dataGridNodeFromNode(event.target);
986         var resource = gridNode && gridNode._resource;
987         if (resource)
988             contextMenu.appendItem(WebInspector.UIString("Export to HAR"), this._exportResource.bind(this, resource));
989         contextMenu.appendItem(WebInspector.UIString("Export all to HAR"), this._exportAll.bind(this));
990         contextMenu.show(event);
991     },
992
993     _exportAll: function()
994     {
995         var harArchive = {
996             log: (new WebInspector.HARLog()).build()
997         }
998         offerFileForDownload(JSON.stringify(harArchive));
999     },
1000
1001     _exportResource: function(resource)
1002     {
1003         var har = (new WebInspector.HAREntry(resource)).build();
1004         offerFileForDownload(JSON.stringify(har));
1005     }
1006 }
1007
1008 WebInspector.NetworkPanel.prototype.__proto__ = WebInspector.Panel.prototype;
1009
1010 WebInspector.NetworkBaseCalculator = function()
1011 {
1012 }
1013
1014 WebInspector.NetworkBaseCalculator.prototype = {
1015     computeSummaryValues: function(items)
1016     {
1017         var total = 0;
1018         var categoryValues = {};
1019
1020         var itemsLength = items.length;
1021         for (var i = 0; i < itemsLength; ++i) {
1022             var item = items[i];
1023             var value = this._value(item);
1024             if (typeof value === "undefined")
1025                 continue;
1026             if (!(item.category.name in categoryValues))
1027                 categoryValues[item.category.name] = 0;
1028             categoryValues[item.category.name] += value;
1029             total += value;
1030         }
1031
1032         return {categoryValues: categoryValues, total: total};
1033     },
1034
1035     computeBarGraphPercentages: function(item)
1036     {
1037         return {start: 0, middle: 0, end: (this._value(item) / this.boundarySpan) * 100};
1038     },
1039
1040     computeBarGraphLabels: function(item)
1041     {
1042         const label = this.formatValue(this._value(item));
1043         return {left: label, right: label, tooltip: label};
1044     },
1045
1046     get boundarySpan()
1047     {
1048         return this.maximumBoundary - this.minimumBoundary;
1049     },
1050
1051     updateBoundaries: function(item)
1052     {
1053         this.minimumBoundary = 0;
1054
1055         var value = this._value(item);
1056         if (typeof this.maximumBoundary === "undefined" || value > this.maximumBoundary) {
1057             this.maximumBoundary = value;
1058             return true;
1059         }
1060         return false;
1061     },
1062
1063     reset: function()
1064     {
1065         delete this.minimumBoundary;
1066         delete this.maximumBoundary;
1067     },
1068
1069     _value: function(item)
1070     {
1071         return 0;
1072     },
1073
1074     formatValue: function(value)
1075     {
1076         return value.toString();
1077     }
1078 }
1079
1080 WebInspector.NetworkTimeCalculator = function(startAtZero)
1081 {
1082     WebInspector.NetworkBaseCalculator.call(this);
1083     this.startAtZero = startAtZero;
1084 }
1085
1086 WebInspector.NetworkTimeCalculator.prototype = {
1087     computeSummaryValues: function(resources)
1088     {
1089         var resourcesByCategory = {};
1090         var resourcesLength = resources.length;
1091         for (var i = 0; i < resourcesLength; ++i) {
1092             var resource = resources[i];
1093             if (!(resource.category.name in resourcesByCategory))
1094                 resourcesByCategory[resource.category.name] = [];
1095             resourcesByCategory[resource.category.name].push(resource);
1096         }
1097
1098         var earliestStart;
1099         var latestEnd;
1100         var categoryValues = {};
1101         for (var category in resourcesByCategory) {
1102             resourcesByCategory[category].sort(WebInspector.Resource.CompareByTime);
1103             categoryValues[category] = 0;
1104
1105             var segment = {start: -1, end: -1};
1106
1107             var categoryResources = resourcesByCategory[category];
1108             var resourcesLength = categoryResources.length;
1109             for (var i = 0; i < resourcesLength; ++i) {
1110                 var resource = categoryResources[i];
1111                 if (resource.startTime === -1 || resource.endTime === -1)
1112                     continue;
1113
1114                 if (typeof earliestStart === "undefined")
1115                     earliestStart = resource.startTime;
1116                 else
1117                     earliestStart = Math.min(earliestStart, resource.startTime);
1118
1119                 if (typeof latestEnd === "undefined")
1120                     latestEnd = resource.endTime;
1121                 else
1122                     latestEnd = Math.max(latestEnd, resource.endTime);
1123
1124                 if (resource.startTime <= segment.end) {
1125                     segment.end = Math.max(segment.end, resource.endTime);
1126                     continue;
1127                 }
1128
1129                 categoryValues[category] += segment.end - segment.start;
1130
1131                 segment.start = resource.startTime;
1132                 segment.end = resource.endTime;
1133             }
1134
1135             // Add the last segment
1136             categoryValues[category] += segment.end - segment.start;
1137         }
1138
1139         return {categoryValues: categoryValues, total: latestEnd - earliestStart};
1140     },
1141
1142     computeBarGraphPercentages: function(resource)
1143     {
1144         if (resource.startTime !== -1)
1145             var start = ((resource.startTime - this.minimumBoundary) / this.boundarySpan) * 100;
1146         else
1147             var start = 0;
1148
1149         if (resource.responseReceivedTime !== -1)
1150             var middle = ((resource.responseReceivedTime - this.minimumBoundary) / this.boundarySpan) * 100;
1151         else
1152             var middle = (this.startAtZero ? start : 100);
1153
1154         if (resource.endTime !== -1)
1155             var end = ((resource.endTime - this.minimumBoundary) / this.boundarySpan) * 100;
1156         else
1157             var end = (this.startAtZero ? middle : 100);
1158
1159         if (this.startAtZero) {
1160             end -= start;
1161             middle -= start;
1162             start = 0;
1163         }
1164
1165         return {start: start, middle: middle, end: end};
1166     },
1167
1168     computePercentageFromEventTime: function(eventTime)
1169     {
1170         // This function computes a percentage in terms of the total loading time
1171         // of a specific event. If startAtZero is set, then this is useless, and we
1172         // want to return 0.
1173         if (eventTime !== -1 && !this.startAtZero)
1174             return ((eventTime - this.minimumBoundary) / this.boundarySpan) * 100;
1175
1176         return 0;
1177     },
1178
1179     computeBarGraphLabels: function(resource)
1180     {
1181         var rightLabel = "";
1182         if (resource.responseReceivedTime !== -1 && resource.endTime !== -1)
1183             rightLabel = this.formatValue(resource.endTime - resource.responseReceivedTime);
1184
1185         var hasLatency = resource.latency > 0;
1186         if (hasLatency)
1187             var leftLabel = this.formatValue(resource.latency);
1188         else
1189             var leftLabel = rightLabel;
1190
1191         if (resource.timing)
1192             return {left: leftLabel, right: rightLabel};
1193
1194         if (hasLatency && rightLabel) {
1195             var total = this.formatValue(resource.duration);
1196             var tooltip = WebInspector.UIString("%s latency, %s download (%s total)", leftLabel, rightLabel, total);
1197         } else if (hasLatency)
1198             var tooltip = WebInspector.UIString("%s latency", leftLabel);
1199         else if (rightLabel)
1200             var tooltip = WebInspector.UIString("%s download", rightLabel);
1201
1202         if (resource.cached)
1203             tooltip = WebInspector.UIString("%s (from cache)", tooltip);
1204         return {left: leftLabel, right: rightLabel, tooltip: tooltip};
1205     },
1206
1207     updateBoundaries: function(resource)
1208     {
1209         var didChange = false;
1210
1211         var lowerBound;
1212         if (this.startAtZero)
1213             lowerBound = 0;
1214         else
1215             lowerBound = this._lowerBound(resource);
1216
1217         if (lowerBound !== -1 && (typeof this.minimumBoundary === "undefined" || lowerBound < this.minimumBoundary)) {
1218             this.minimumBoundary = lowerBound;
1219             didChange = true;
1220         }
1221
1222         var upperBound = this._upperBound(resource);
1223         if (upperBound !== -1 && (typeof this.maximumBoundary === "undefined" || upperBound > this.maximumBoundary)) {
1224             this.maximumBoundary = upperBound;
1225             didChange = true;
1226         }
1227
1228         return didChange;
1229     },
1230
1231     formatValue: function(value)
1232     {
1233         return Number.secondsToString(value);
1234     },
1235
1236     _lowerBound: function(resource)
1237     {
1238         return 0;
1239     },
1240
1241     _upperBound: function(resource)
1242     {
1243         return 0;
1244     }
1245 }
1246
1247 WebInspector.NetworkTimeCalculator.prototype.__proto__ = WebInspector.NetworkBaseCalculator.prototype;
1248
1249 WebInspector.NetworkTransferTimeCalculator = function()
1250 {
1251     WebInspector.NetworkTimeCalculator.call(this, false);
1252 }
1253
1254 WebInspector.NetworkTransferTimeCalculator.prototype = {
1255     formatValue: function(value)
1256     {
1257         return Number.secondsToString(value);
1258     },
1259
1260     _lowerBound: function(resource)
1261     {
1262         return resource.startTime;
1263     },
1264
1265     _upperBound: function(resource)
1266     {
1267         return resource.endTime;
1268     }
1269 }
1270
1271 WebInspector.NetworkTransferTimeCalculator.prototype.__proto__ = WebInspector.NetworkTimeCalculator.prototype;
1272
1273 WebInspector.NetworkTransferDurationCalculator = function()
1274 {
1275     WebInspector.NetworkTimeCalculator.call(this, true);
1276 }
1277
1278 WebInspector.NetworkTransferDurationCalculator.prototype = {
1279     formatValue: function(value)
1280     {
1281         return Number.secondsToString(value);
1282     },
1283
1284     _upperBound: function(resource)
1285     {
1286         return resource.duration;
1287     }
1288 }
1289
1290 WebInspector.NetworkTransferDurationCalculator.prototype.__proto__ = WebInspector.NetworkTimeCalculator.prototype;
1291
1292 WebInspector.NetworkDataGridNode = function(panel, resource)
1293 {
1294     WebInspector.DataGridNode.call(this, {});
1295     this._panel = panel;
1296     this._resource = resource;
1297 }
1298
1299 WebInspector.NetworkDataGridNode.prototype = {
1300     createCells: function()
1301     {
1302         this._nameCell = this._createDivInTD("name");
1303         this._methodCell = this._createDivInTD("method");
1304         this._statusCell = this._createDivInTD("status");
1305         this._typeCell = this._createDivInTD("type");
1306         this._sizeCell = this._createDivInTD("size");
1307         this._timeCell = this._createDivInTD("time");
1308         this._createTimelineCell();
1309         this._nameCell.addEventListener("click", this.select.bind(this), false);
1310     },
1311
1312     select: function()
1313     {
1314         this._panel._showResource(this._resource);
1315         WebInspector.DataGridNode.prototype.select.apply(this, arguments);
1316     },
1317
1318     get selectable()
1319     {
1320         if (!this._panel._viewingResourceMode)
1321             return false;
1322         if (!this._panel._hiddenCategories.all)
1323             return true;
1324         if (this._panel._hiddenCategories[this._resource.category.name])
1325             return false;
1326         return true;
1327     },
1328
1329     _createDivInTD: function(columnIdentifier)
1330     {
1331         var td = document.createElement("td");
1332         td.className = columnIdentifier + "-column";
1333         var div = document.createElement("div");
1334         td.appendChild(div);
1335         this._element.appendChild(td);
1336         return div;
1337     },
1338
1339     _createTimelineCell: function()
1340     {
1341         this._graphElement = document.createElement("div");
1342         this._graphElement.className = "network-graph-side";
1343
1344         this._barAreaElement = document.createElement("div");
1345         //    this._barAreaElement.className = "network-graph-bar-area hidden";
1346         this._barAreaElement.className = "network-graph-bar-area";
1347         this._barAreaElement.resource = this._resource;
1348         this._graphElement.appendChild(this._barAreaElement);
1349
1350         this._barLeftElement = document.createElement("div");
1351         this._barLeftElement.className = "network-graph-bar waiting";
1352         this._barAreaElement.appendChild(this._barLeftElement);
1353
1354         this._barRightElement = document.createElement("div");
1355         this._barRightElement.className = "network-graph-bar";
1356         this._barAreaElement.appendChild(this._barRightElement);
1357
1358
1359         this._labelLeftElement = document.createElement("div");
1360         this._labelLeftElement.className = "network-graph-label waiting";
1361         this._barAreaElement.appendChild(this._labelLeftElement);
1362
1363         this._labelRightElement = document.createElement("div");
1364         this._labelRightElement.className = "network-graph-label";
1365         this._barAreaElement.appendChild(this._labelRightElement);
1366
1367         this._graphElement.addEventListener("mouseover", this._refreshLabelPositions.bind(this), false);
1368
1369         this._timelineCell = document.createElement("td");
1370         this._timelineCell.className = "timeline-column";
1371         this._element.appendChild(this._timelineCell);
1372         this._timelineCell.appendChild(this._graphElement);
1373     },
1374
1375     refreshResource: function()
1376     {
1377         this._refreshNameCell();
1378
1379         this._methodCell.textContent = this._resource.requestMethod;
1380
1381         this._refreshStatusCell();
1382
1383         if (this._resource.mimeType) {
1384             this._typeCell.removeStyleClass("network-dim-cell");
1385             this._typeCell.textContent = this._resource.mimeType;
1386         } else {
1387             this._typeCell.addStyleClass("network-dim-cell");
1388             this._typeCell.textContent = WebInspector.UIString("Pending");
1389         }
1390
1391         this._refreshSizeCell();
1392         this._refreshTimeCell();
1393
1394         if (this._resource.cached)
1395             this._graphElement.addStyleClass("resource-cached");
1396
1397         this._element.addStyleClass("network-item");
1398         if (!this._element.hasStyleClass("network-category-" + this._resource.category.name)) {
1399             this._element.removeMatchingStyleClasses("network-category-\\w+");
1400             this._element.addStyleClass("network-category-" + this._resource.category.name);
1401         }
1402     },
1403
1404     _refreshNameCell: function()
1405     {
1406         this._nameCell.removeChildren();
1407
1408         if (this._resource.category === WebInspector.resourceCategories.images) {
1409             var previewImage = document.createElement("img");
1410             previewImage.className = "image-network-icon-preview";
1411
1412             function onResourceContent()
1413             {
1414                 previewImage.src = this._resource.contentURL;
1415             }
1416             if (Preferences.useDataURLForResourceImageIcons)
1417                 this._resource.requestContent(onResourceContent.bind(this));
1418             else
1419                 previewImage.src = this._resource.url;
1420
1421             var iconElement = document.createElement("div");
1422             iconElement.className = "icon";
1423             iconElement.appendChild(previewImage);
1424         } else {
1425             var iconElement = document.createElement("img");
1426             iconElement.className = "icon";
1427         }
1428         this._nameCell.appendChild(iconElement);
1429         this._nameCell.appendChild(document.createTextNode(this._fileName()));
1430
1431
1432         var subtitle = this._resource.displayDomain;
1433
1434         if (this._resource.path && this._resource.lastPathComponent) {
1435             var lastPathComponentIndex = this._resource.path.lastIndexOf("/" + this._resource.lastPathComponent);
1436             if (lastPathComponentIndex != -1)
1437                 subtitle += this._resource.path.substring(0, lastPathComponentIndex);
1438         }
1439
1440         this._appendSubtitle(this._nameCell, subtitle);
1441         this._nameCell.title = this._resource.url;
1442     },
1443
1444     _fileName: function()
1445     {
1446         var fileName = this._resource.displayName;
1447         if (this._resource.queryString)
1448             fileName += "?" + this._resource.queryString;
1449         return fileName;
1450     },
1451
1452     _refreshStatusCell: function()
1453     {
1454         this._statusCell.removeChildren();
1455
1456         var fromCache = this._resource.cached;
1457         if (fromCache) {
1458             this._statusCell.textContent = WebInspector.UIString("(from cache)");
1459             this._statusCell.addStyleClass("network-dim-cell");
1460             return;
1461         }
1462
1463         this._statusCell.removeStyleClass("network-dim-cell");
1464         if (this._resource.statusCode) {
1465             this._statusCell.appendChild(document.createTextNode(this._resource.statusCode));
1466             this._statusCell.removeStyleClass("network-dim-cell");
1467             this._appendSubtitle(this._statusCell, this._resource.statusText);
1468             this._statusCell.title = this._resource.statusCode + " " + this._resource.statusText;
1469         } else {
1470             this._statusCell.addStyleClass("network-dim-cell");
1471             this._statusCell.textContent = WebInspector.UIString("Pending");
1472         }
1473     },
1474
1475     _refreshSizeCell: function()
1476     {
1477         var resourceSize = typeof this._resource.resourceSize === "number" ? Number.bytesToString(this._resource.resourceSize) : "?";
1478         var transferSize = typeof this._resource.transferSize === "number" ? Number.bytesToString(this._resource.transferSize) : "?";
1479         var fromCache = this._resource.cached;
1480         this._sizeCell.textContent = !fromCache ? resourceSize : WebInspector.UIString("(from cache)");
1481         if (fromCache)
1482             this._sizeCell.addStyleClass("network-dim-cell");
1483         else
1484             this._sizeCell.removeStyleClass("network-dim-cell");
1485         if (!fromCache)
1486             this._appendSubtitle(this._sizeCell, transferSize);
1487     },
1488
1489     _refreshTimeCell: function()
1490     {
1491         if (this._resource.duration > 0) {
1492             this._timeCell.removeStyleClass("network-dim-cell");
1493             this._timeCell.textContent = Number.secondsToString(this._resource.duration);
1494             this._appendSubtitle(this._timeCell, Number.secondsToString(this._resource.latency));
1495         } else {
1496             this._timeCell.addStyleClass("network-dim-cell");
1497             this._timeCell.textContent = WebInspector.UIString("Pending");
1498         }
1499     },
1500
1501     _appendSubtitle: function(cellElement, subtitleText)
1502     {
1503         var subtitleElement = document.createElement("div");
1504         subtitleElement.className = "network-cell-subtitle";
1505         subtitleElement.textContent = subtitleText;
1506         cellElement.appendChild(subtitleElement);
1507     },
1508
1509     refreshGraph: function(calculator)
1510     {
1511         var percentages = calculator.computeBarGraphPercentages(this._resource);
1512         this._percentages = percentages;
1513
1514         this._barAreaElement.removeStyleClass("hidden");
1515
1516         if (!this._graphElement.hasStyleClass("network-category-" + this._resource.category.name)) {
1517             this._graphElement.removeMatchingStyleClasses("network-category-\\w+");
1518             this._graphElement.addStyleClass("network-category-" + this._resource.category.name);
1519         }
1520
1521         this._barLeftElement.style.setProperty("left", percentages.start + "%");
1522         this._barRightElement.style.setProperty("right", (100 - percentages.end) + "%");
1523
1524         this._barLeftElement.style.setProperty("right", (100 - percentages.end) + "%");
1525         this._barRightElement.style.setProperty("left", percentages.middle + "%");
1526
1527         var labels = calculator.computeBarGraphLabels(this._resource);
1528         this._labelLeftElement.textContent = labels.left;
1529         this._labelRightElement.textContent = labels.right;
1530
1531         var tooltip = (labels.tooltip || "");
1532         this._barLeftElement.title = tooltip;
1533         this._labelLeftElement.title = tooltip;
1534         this._labelRightElement.title = tooltip;
1535         this._barRightElement.title = tooltip;
1536     },
1537
1538     _refreshLabelPositions: function()
1539     {
1540         if (!this._percentages)
1541             return;
1542         this._labelLeftElement.style.removeProperty("left");
1543         this._labelLeftElement.style.removeProperty("right");
1544         this._labelLeftElement.removeStyleClass("before");
1545         this._labelLeftElement.removeStyleClass("hidden");
1546
1547         this._labelRightElement.style.removeProperty("left");
1548         this._labelRightElement.style.removeProperty("right");
1549         this._labelRightElement.removeStyleClass("after");
1550         this._labelRightElement.removeStyleClass("hidden");
1551
1552         const labelPadding = 10;
1553         const barRightElementOffsetWidth = this._barRightElement.offsetWidth;
1554         const barLeftElementOffsetWidth = this._barLeftElement.offsetWidth;
1555
1556         if (this._barLeftElement) {
1557             var leftBarWidth = barLeftElementOffsetWidth - labelPadding;
1558             var rightBarWidth = (barRightElementOffsetWidth - barLeftElementOffsetWidth) - labelPadding;
1559         } else {
1560             var leftBarWidth = (barLeftElementOffsetWidth - barRightElementOffsetWidth) - labelPadding;
1561             var rightBarWidth = barRightElementOffsetWidth - labelPadding;
1562         }
1563
1564         const labelLeftElementOffsetWidth = this._labelLeftElement.offsetWidth;
1565         const labelRightElementOffsetWidth = this._labelRightElement.offsetWidth;
1566
1567         const labelBefore = (labelLeftElementOffsetWidth > leftBarWidth);
1568         const labelAfter = (labelRightElementOffsetWidth > rightBarWidth);
1569         const graphElementOffsetWidth = this._graphElement.offsetWidth;
1570
1571         if (labelBefore && (graphElementOffsetWidth * (this._percentages.start / 100)) < (labelLeftElementOffsetWidth + 10))
1572             var leftHidden = true;
1573
1574         if (labelAfter && (graphElementOffsetWidth * ((100 - this._percentages.end) / 100)) < (labelRightElementOffsetWidth + 10))
1575             var rightHidden = true;
1576
1577         if (barLeftElementOffsetWidth == barRightElementOffsetWidth) {
1578             // The left/right label data are the same, so a before/after label can be replaced by an on-bar label.
1579             if (labelBefore && !labelAfter)
1580                 leftHidden = true;
1581             else if (labelAfter && !labelBefore)
1582                 rightHidden = true;
1583         }
1584
1585         if (labelBefore) {
1586             if (leftHidden)
1587                 this._labelLeftElement.addStyleClass("hidden");
1588             this._labelLeftElement.style.setProperty("right", (100 - this._percentages.start) + "%");
1589             this._labelLeftElement.addStyleClass("before");
1590         } else {
1591             this._labelLeftElement.style.setProperty("left", this._percentages.start + "%");
1592             this._labelLeftElement.style.setProperty("right", (100 - this._percentages.middle) + "%");
1593         }
1594
1595         if (labelAfter) {
1596             if (rightHidden)
1597                 this._labelRightElement.addStyleClass("hidden");
1598             this._labelRightElement.style.setProperty("left", this._percentages.end + "%");
1599             this._labelRightElement.addStyleClass("after");
1600         } else {
1601             this._labelRightElement.style.setProperty("left", this._percentages.middle + "%");
1602             this._labelRightElement.style.setProperty("right", (100 - this._percentages.end) + "%");
1603         }
1604     }
1605 }
1606
1607 WebInspector.NetworkDataGridNode.NameComparator = function(a, b)
1608 {
1609     var aFileName = a._resource.displayName + (a._resource.queryString ? a._resource.queryString : "");
1610     var bFileName = b._resource.displayName + (b._resource.queryString ? b._resource.queryString : "");
1611     if (aFileName > bFileName)
1612         return 1;
1613     if (bFileName > aFileName)
1614         return -1;
1615     return 0;
1616 }
1617
1618 WebInspector.NetworkDataGridNode.SizeComparator = function(a, b)
1619 {
1620     if (b._resource.cached && !a._resource.cached)
1621         return 1;
1622     if (a._resource.cached && !b._resource.cached)
1623         return -1;
1624
1625     if (a._resource.resourceSize === b._resource.resourceSize)
1626         return 0;
1627
1628     return a._resource.resourceSize - b._resource.resourceSize;
1629 }
1630
1631 WebInspector.NetworkDataGridNode.ResourcePropertyComparator = function(propertyName, revert, a, b)
1632 {
1633     var aValue = a._resource[propertyName];
1634     var bValue = b._resource[propertyName];
1635     if (aValue > bValue)
1636         return revert ? -1 : 1;
1637     if (bValue > aValue)
1638         return revert ? 1 : -1;
1639     return 0;
1640 }
1641
1642 WebInspector.NetworkDataGridNode.prototype.__proto__ = WebInspector.DataGridNode.prototype;
1643
1644 WebInspector.NetworkTotalGridNode = function(element)
1645 {
1646     this._summaryBarElement = element;
1647     WebInspector.DataGridNode.call(this, {summaryRow: true});
1648 }
1649
1650 WebInspector.NetworkTotalGridNode.prototype = {
1651     createCells: function()
1652     {
1653         var td = document.createElement("td");
1654         td.setAttribute("colspan", 7);
1655         td.className = "network-summary";
1656         td.appendChild(this._summaryBarElement);
1657         this._element.appendChild(td);
1658     }
1659 }
1660
1661 WebInspector.NetworkTotalGridNode.prototype.__proto__ = WebInspector.DataGridNode.prototype;